Middleware & Auth

Middleware runs when a request enters the Start server. Use it for auth, sessions, logs, request IDs, and context injection.

Auth Layers

A robust Start app uses three layers:

  1. Middleware parses session and injects user
  2. beforeLoad protects route entry
  3. Server Function / Server Route authorizes writes

Hiding UI is not a security boundary.

Protect a Route

export const Route = createFileRoute('/dashboard')({
  beforeLoad: ({ context }) => {
    if (!context.user) throw redirect({ to: '/login' })
  },
})

Authorize Writes

const deletePost = createServerFn({ method: 'POST' })
  .validator((input: { id: string }) => input)
  .handler(async ({ data, context }) => {
    if (!context.user) throw new Error('Unauthorized')
    await assertCanDelete(context.user, data.id)
    return db.post.delete({ where: { id: data.id } })
  })

CSRF and Same Origin

Server Functions are same-origin RPCs. Keep CSRF / Origin checks enabled. Public cross-origin endpoints should use Server Routes.

Next Steps