# Sessions and Guards

> How the signed-in user reaches loaders, actions, API handlers and components, and why guards don't replace authorization.

*Canonical: https://makerkit.dev/docs/void-cloudflare/authentication/sessions-and-guards*

---

The session middleware reads the session once per request. Loaders, actions and handlers read it from the request context; components read the user's public fields from shared data.

This page is part of the [Authentication documentation](./overview).

## Guards Gate Navigation Only

`apps/web/middleware/06.session.ts` redirects by folder (`pages/(app)/` needs a session, `pages/auth/` refuses one) and marks those pages `Cache-Control: private, no-store`. That stops someone opening a page. It doesn't stop a request to an action or an API route: anyone can send one directly.

**Every loader, action and handler that reads or changes a user's data checks the session itself**, even inside `pages/(app)/`.

If the session can't be read (the database is down), public pages such as the marketing site and the `pages/auth/` pages still render, signed out and marked `private, no-store`, and the error is logged. Pages under `pages/(app)/` and every `/api` route answer 500: there an outage isn't a signed-out visitor.

## Loaders and Actions

```ts {% title="apps/web/pages/(app)/projects/index.server.ts" %}
import { defineHandler, type InferProps } from 'void';

import { requireSession } from '#/lib/session.server.ts';
import { listProjects } from '#/lib/projects.service.ts'; // yours

export type Props = InferProps<typeof loader>;

export const loader = defineHandler(async (c) => {
  const { user } = requireSession({ c });

  return { projects: await listProjects({ userId: user.id }) };
});
```

| Helper (`lib/session.server.ts`) | Returns | Without a session |
|---|---|---|
| `requireSession({ c })` | `{ session, user }` | Pages: redirect to sign-in with `next`. `/api`: `401` |
| `getSession({ c })` | `{ session, user }` or `null` | `null`, for pages signed-out visitors can open too |
| `getNextPath(c)` | the `next` query parameter if it's a safe same-site path, else the app home (`APP_HOME_PATH`) | |

Take the user's id from the session, never from the request body or URL.

## Sensitive Account Changes

Changing the email or password, linking or unlinking a sign-in method and signing out sessions need a **fresh session**: a sign-in from the last 10 minutes (`FRESH_SESSION_MINUTES`). An **impersonation session** never makes them. Better Auth's hooks refuse these endpoints (`ACCOUNT_CHANGE_PATHS` in `packages/better-auth/src/fresh-session.ts`, one list for both rules), over HTTP and from `auth.api` alike, with `403 SESSION_NOT_FRESH` or `403`. A name change stays allowed. Account deletion has its own rule ([Deleting an Account](../account/deletion)).

A page action whose `auth.api` call has no path the hooks see (`setPassword`) checks first:

```ts
import { requireAccountChange } from '#/lib/account-change.server.ts';

// 403 SESSION_NOT_FRESH or IMPERSONATED, else { session, user }
const { user } = requireAccountChange({ c });
```

Forms built for these changes map the code (`useForm` with `throwOnError: false` keeps the 403 in `form.error`). On `SESSION_NOT_FRESH` they offer to sign in again and come back: `<SignInAgain href={signInAgainPath(authPaths.security)} />` (`@kit/auth/shared`, `lib/auth-links.ts`). It signs out first, since the sign-in page is for signed-out visitors.

## API Routes

The same helpers work in `routes/api/**` handlers. `requireSession` answers `401` there instead of redirecting:

```ts {% title="apps/web/routes/api/projects.ts" %}
import { defineHandler } from 'void';

import { requireSession } from '#/lib/session.server.ts';
import { listProjects } from '#/lib/projects.service.ts'; // yours

export const GET = defineHandler(async (c) => {
  const { user } = requireSession({ c });

  return c.json(await listProjects({ userId: user.id }));
});
```

## Components

```tsx
import { useShared } from '@void/react';

const { user } = useShared(); // null when signed out
```

`user` holds only `id`, `name`, `email`, `image` and `emailVerified`. Never put the session or other user fields into `shared` or page props: they're serialized into the page.

## Signing In and Out from the Browser

Forms call Better Auth over HTTP through `authClient`, so its rate limits and origin checks apply:

```ts
import { authClient } from '@kit/better-auth/client';

await authClient.signOut();
window.location.reload(); // the middleware sees no session and redirects
```

Don't call `getAuth().api.signIn*` from page actions for user sign-in flows: server calls skip the rate limiter.

## Suspended (Banned) Accounts

Better Auth's admin plugin refuses any new session to a user whose `banned` flag is set, whatever the sign-in method. Forms show the `auth.errors.BANNED_USER` message; a magic link or an OAuth callback lands on the sign-in page with `?error=BANNED_USER`. Better Auth checks the flag only when a session is created, so whatever bans a user must also delete their sessions. The plugin's own `/api/auth/admin/*` endpoints always answer 404; the admin area uses them only from the server, after its own checks.

## Adding a Page

- **Signed-in only:** put it under `apps/web/pages/(app)/`. `(app)` is a route group, so it adds nothing to the URL.
- **Signed-out only** (an auth flow): under `apps/web/pages/auth/`. Add its path to `authPaths` (`config/auth-paths.ts`) if code links or redirects to it.
- **Public:** anywhere else. The middleware marks pages `private, no-store` only for a signed-in visitor or a guarded folder; a public page with a token or user data in its URL sets `Cache-Control: private, no-store` in its own loader, as `pages/password-reset/index.server.ts` does.

A new auth page follows the existing ones (`pages/auth/sign-in.tsx`):

- `apps/web/pages/auth/<name>.tsx` and `<name>.server.ts` serve `/auth/<name>`; `pages/auth/layout.tsx` wraps it in the auth layout.
- The loader returns `next: getNextPath(c)` and passes it on in links and callbacks.
- `head` sets the title with `getServerTranslator({ c, namespace })`.
- It's a public page, so links use `LocalizedLink` and redirects `localizedRedirect`.
- Its strings go in your namespace in `apps/web/messages/<locale>/` (the `app_translations_*` MCP tools), not the kit's `auth` namespace. See [Managing Translations](../internationalization/managing-translations).

Moving a file is the only way to change who can open it. Guards are built from the files at build time, including `[param]`, `[...rest]`, `.island` and `.dev`/`.prod` pages.

## Redirects After Sign-In

`next` survives sign-in, sign-up, email verification and password reset. Only same-site relative paths are followed (`/dashboard?tab=a`); anything else (`https://evil.com`, `//evil.com`) falls back to the app home. Better Auth callback URLs pointing off-site are rejected with `403 INVALID_CALLBACK_URL`.

When `next` is an invitation's link (`/invitation/<id>`), sign-in and sign-up prefill the invited address, still editable (`getInvitedEmail` in `apps/web/lib/invited-email.server.ts`, passed as `defaultEmail` to the `@kit/auth` email forms). The address is read from the stored invitation, never from the URL, so it doesn't end up in request logs. It's only a hint: accepting checks the signed-in user's own verified address.
