Auth Preset

defineAuthMiddleware — protect actions, resolve ctx.user, reject with 401

The problem: an account endpoint must only run for signed-in users, and the handler wants the current user without re-reading the session every time.

The fix: wrap the action with defineAuthMiddleware. It resolves the session into ctx.user or throws a typed 401. Here a demo session header stands in for a real cookie/session.

Session

Signed out

When signed in, the request carries x-demo-session. When signed out, it does not — the middleware rejects it.

How it works

// server/actions/account.post.ts
export default createActionClient()
  .use(defineAuthMiddleware((event) => {
    const session = getHeader(event, 'x-demo-session')
    return session ? { id: session, name: `User ${session}`, plan: 'pro' } : null
  }))
  .action(async ({ ctx }) => ({ user: ctx.user }))

// client — send the session header only when signed in
useAction(account, {
  headers: () => signedIn.value ? { 'x-demo-session': 'u_42' } : {},
})