Test API authorization in TanStack Start

Test that anonymous users and other accounts cannot access protected TanStack Start API data.

By Antoine RossPublished

A successful request from the owner does not show that another user is blocked. Test the same API with separate browser sessions and check the response body as well as its status. This guide builds a small project API with TanStack Start server routes, then tests it with an anonymous session and two signed-in accounts.

Before you start

You need a TanStack Start app that signs users in and verifies them on the server. This example uses the cookie-backed Supabase helper and /sign-in page from Supabase authentication in TanStack Start. If your app uses another authentication library, keep it: only the currentUserId function below is provider-specific.

Create the project API

Set APP_ORIGIN in the server environment to the exact origin of your local app, such as http://localhost:3000. In production, set it to your public HTTPS origin. Create for the checks every project endpoint shares:

src/lib/projects.server.ts
import '@tanstack/react-start/server-only'
import { supabaseServer } from './supabase-server'

type Project = { id: string; ownerId: string; name: string }
// Local learning only: resets on restart and is not shared between server instances.
export const projects = new Map<string, Project>()

export function json(body: unknown, status = 200) {
  return Response.json(body, {
    status,
    headers: { 'Cache-Control': 'private, no-store', Vary: 'Cookie' },
  })
}

// The only provider-specific function. With another auth library, return its
// server-verified user ID here, or null when the request is not signed in.
export async function currentUserId() {
  const { data, error } = await supabaseServer().auth.getUser()
  if (error || !data.user || data.user.is_anonymous) return null
  return data.user.id
}

export function rejectUntrustedWrite(request: Request) {
  const origin = process.env.APP_ORIGIN
  const type = request.headers.get('Content-Type')?.split(';', 1)[0].trim().toLowerCase()
  if (!origin || request.headers.get('Origin') !== origin || type !== 'application/json') {
    return json({ error: 'Request denied' }, 403)
  }
  return null
}

export async function readName(request: Request) {
  let input: unknown
  try { input = await request.json() } catch {
    return json({ error: 'Invalid JSON' }, 400)
  }
  if (typeof input !== 'object' || input === null || Array.isArray(input) ||
      Object.keys(input).some(key => key !== 'name') ||
      !('name' in input) || typeof input.name !== 'string') {
    return json({ error: 'Expected a project name' }, 400)
  }
  const name = input.name.trim()
  if (!name || name.length > 80) return json({ error: 'Name must be 1 to 80 characters' }, 400)
  return name
}

The example stores projects in process memory to make the HTTP path easy to try. It is for local learning only: data disappears when the process restarts and is not shared between instances. Use a database and migrations before relying on the data.

Create :

src/routes/api/projects.ts
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/api/projects')({
  server: {
    handlers: {
      GET: async () => {
        const api = await import('../../lib/projects.server')
        const userId = await api.currentUserId()
        if (!userId) return api.json({ error: 'Authentication required' }, 401)
        const own = [...api.projects.values()]
          .filter(project => project.ownerId === userId)
          .map(({ id, name }) => ({ id, name }))
        return api.json({ data: own })
      },
      POST: async ({ request }) => {
        const api = await import('../../lib/projects.server')
        const denied = api.rejectUntrustedWrite(request)
        if (denied) return denied
        const userId = await api.currentUserId()
        if (!userId) return api.json({ error: 'Authentication required' }, 401)
        const name = await api.readName(request)
        if (typeof name !== 'string') return name
        const project = { id: crypto.randomUUID(), ownerId: userId, name }
        api.projects.set(project.id, project)
        return api.json({ data: { id: project.id, name } }, 201)
      },
    },
  },
})

GET /api/projects returns { data: [...] } with only the signed-in user's projects. POST /api/projects accepts a JSON name and returns { data: { id, name } }. The server derives the owner from the verified session, not the request body, and both endpoints require a signed-in user. The handlers import the server module when a request arrives, which keeps server-only code out of the browser bundle. Restart the dev server if your route generator has not picked up the new file. See TanStack Start server routes.

The exact-origin and JSON checks narrow cross-site request exposure for this browser-oriented example; the server-function middleware from the sign-in guide does not cover server routes. Configure the trusted origin yourself rather than deriving it from a request header, and add body-size limits, rate limits and durable storage before production. OWASP's CSRF guidance explains the tradeoffs.

Add a single-project route

Listing only your own projects does not stop someone from requesting another user's project by ID. Add a route that reads and renames one project, so the test can check direct access. Create ; it reuses the helpers from :

src/routes/api/projects.$id.ts
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/api/projects/$id')({
  server: {
    handlers: {
      GET: async ({ params }) => {
        const api = await import('../../lib/projects.server')
        const userId = await api.currentUserId()
        if (!userId) return api.json({ error: 'Authentication required' }, 401)
        const project = api.projects.get(params.id)
        if (!project || project.ownerId !== userId) return api.json({ error: 'Not found' }, 404)
        return api.json({ data: { id: project.id, name: project.name } })
      },
      PATCH: async ({ request, params }) => {
        const api = await import('../../lib/projects.server')
        const denied = api.rejectUntrustedWrite(request)
        if (denied) return denied
        const userId = await api.currentUserId()
        if (!userId) return api.json({ error: 'Authentication required' }, 401)
        const project = api.projects.get(params.id)
        if (!project || project.ownerId !== userId) return api.json({ error: 'Not found' }, 404)
        const name = await api.readName(request)
        if (typeof name !== 'string') return name
        project.name = name
        return api.json({ data: { id: project.id, name } })
      },
    },
  },
})

Both handlers check the stored owner before returning or changing the record, and return the same 404 for a missing project and another user's project. This is a single-owner example, not an organization role model. A valid login alone is not enough.

Prepare two accounts

Run the app locally with its /sign-in page and /api/projects routes. Create two confirmed test users in your authentication provider, such as the Supabase project from the sign-in guide. Use accounts with no real customer data. The sample API keeps data in memory; keep the same server process running throughout this test.

Install Playwright's test runner and browser if your project does not already have them, following the Playwright installation guide. Supply these values to the test process through your local environment, without committing them:

  • TEST_USER_A_EMAIL and TEST_USER_A_PASSWORD
  • TEST_USER_B_EMAIL and TEST_USER_B_PASSWORD
  • TEST_BASE_URL, for example http://localhost:3000

Set the app's APP_ORIGIN to the same origin. Do not put credentials, cookies, or tokens in the test file or attach them to reports. Run against a disposable environment, not production.

Exercise the real API from separate sessions

Create tests/project-authorization.spec.ts:

tests/project-authorization.spec.ts
import { test, expect, type Page } from '@playwright/test'

const base = process.env.TEST_BASE_URL!
const aEmail = process.env.TEST_USER_A_EMAIL!
const aPassword = process.env.TEST_USER_A_PASSWORD!
const bEmail = process.env.TEST_USER_B_EMAIL!
const bPassword = process.env.TEST_USER_B_PASSWORD!

async function signIn(page: Page, email: string, password: string) {
  await page.goto(`${base}/sign-in`)
  // Fill only after hydration; earlier input is reset and the click would not sign in.
  await expect(page.getByRole('button', { name: 'Sign in' })).toBeEnabled()
  await page.getByLabel('Email').fill(email)
  await page.getByLabel('Password').fill(password)
  await page.getByRole('button', { name: 'Sign in' }).click()
  await expect(page.getByText(`Signed in as ${email}`)).toBeVisible()
}

async function list(page: Page) {
  return page.evaluate(async () => {
    const response = await fetch('/api/projects')
    return { status: response.status, body: await response.json() }
  })
}

test('projects stay within the signed-in account', async ({ browser }) => {
  if (!base || !aEmail || !aPassword || !bEmail || !bPassword || aEmail === bEmail) {
    throw new Error('Set the test URL and two distinct test accounts')
  }
  const anonymous = await browser.newContext()
  const contextA = await browser.newContext()
  const contextB = await browser.newContext()
  try {
    const anonPage = await anonymous.newPage()
    await anonPage.goto(`${base}/sign-in`)
    expect((await list(anonPage)).status).toBe(401)

    const pageA = await contextA.newPage()
    const pageB = await contextB.newPage()
    await signIn(pageA, aEmail, aPassword)
    await signIn(pageB, bEmail, bPassword)
    const name = `Authorization test ${Date.now()}`
    const created = await pageA.evaluate(async (projectName) => {
      const response = await fetch('/api/projects', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: projectName }),
      })
      return { status: response.status, body: await response.json() }
    }, name)
    expect(created.status).toBe(201)
    expect((await list(pageA)).body.data).toContainEqual({ id: created.body.data.id, name })
    expect((await list(pageB)).body.data).not.toContainEqual({ id: created.body.data.id, name })

    const id = created.body.data.id as string
    const otherActor = await pageB.evaluate(async (projectId) => {
      const path = `/api/projects/${encodeURIComponent(projectId)}`
      const read = await fetch(path)
      const update = await fetch(path, {
        method: 'PATCH', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name: 'Wrong owner' }),
      })
      return { read: read.status, update: update.status }
    }, id)
    expect(otherActor).toEqual({ read: 404, update: 404 })
    const ownRead = await pageA.evaluate(async (projectId) => {
      const response = await fetch(`/api/projects/${encodeURIComponent(projectId)}`)
      return { status: response.status, body: await response.json() }
    }, id)
    expect(ownRead.status).toBe(200)
    expect(ownRead.body.data).toEqual({ id, name })

    const wrongOrigin = await contextA.request.post(`${base}/api/projects`, {
      headers: { Origin: 'https://untrusted.example', 'Content-Type': 'application/json' },
      data: { name: 'Denied' },
    })
    expect(wrongOrigin.status()).toBe(403)
    expect((await list(pageA)).body.data).not.toContainEqual(expect.objectContaining({ name: 'Denied' }))
  } finally {
    await Promise.all([anonymous.close(), contextA.close(), contextB.close()])
  }
})

The signIn helper fills the email and password form from Supabase authentication in TanStack Start. If your app signs in another way, change only that helper so it finishes signed in; the authorization checks stay the same.

With the app running and variables set, run:

bunx playwright test tests/project-authorization.spec.ts

A passing run shows that this API returned 401 to the anonymous session, created a project for A, omitted that project from B's list, denied B's direct read and update, preserved the original name, and rejected the wrong-origin write. It does not prove every endpoint, organization role, deployment, or database policy is safe. The example uses browser.newContext() so cookies are not shared between the three actors. See Playwright browser contexts.

If sign-in times out, verify each account manually first. If B sees A's project, stop and inspect server-side identity and the storage query; do not fix the test by filtering the response in the browser. If wrong-origin succeeds, inspect the mutation guard and the configured public origin. The test calls only HTTP endpoints, so it also works for an API with the same contract built another way, such as Hono in TanStack Start.

Extend the test for your application

For each protected endpoint, test a permitted actor, an anonymous caller, and an authenticated actor without permission. Include direct requests with another owner's resource ID, and check that denied writes did not change stored state. If your app has organizations, test roles and a user from a different organization. A 403 or 404 may both be deliberate for inaccessible records; assert your documented contract without revealing the record. Test invalid input and sign-out separately. OWASP's authorization testing guidance covers additional cases.

CoreMVP's TanStack Start Projects path checks organization membership and action permissions on the server. The project structure guide shows where its routes, services, and repositories live so you can add tests for your own resources. See project structure.