Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions docs/guide/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,9 @@ await auth.signIn.email({
});
```

### 3. Protect a server route
### 3. Protect a server route {#protect-a-server-route}

Call `requireAuth` in a route handler or page loader that needs a signed-in user. It returns that user, or throws `401` if the request isn't authenticated:
Call `requireAuth` in a route handler or action to get the signed-in user or reject unauthenticated requests with `401`:

```ts
// routes/api/profile.ts
Expand All @@ -53,21 +53,29 @@ export const GET = defineHandler((c) => {
});
```

In a pages-mode loader, use `getUser` or `getSession` when you want to allow unauthenticated access:
In a page loader, pass `throwRedirect` to send unauthenticated visitors to your login page instead of a plain-text `401`:

```ts
// pages/dashboard.server.ts
import { defineHandler, type InferProps } from 'void';
import { getUser } from 'void/auth';
import { requireAuth } from 'void/auth';

export type Props = InferProps<typeof loader>;

export const loader = defineHandler(() => {
const user = getUser();
export const loader = defineHandler((c) => {
const user = requireAuth(c, {
throwRedirect: '/login',
});
return { user };
});
```

The same option works in actions and middleware. It throws a redirect, stopping execution: `302` for GET/HEAD requests and `303` for other methods. Document requests follow the redirect normally; Pages client navigation follows it without reloading the document.

Signing in does not replay a rejected action.

To allow unauthenticated access, use `getUser()` and return the nullable user. For custom guards, you can also [throw a redirect](../integrations/hono.md#redirects) from a helper.

### 4. Sign out

```tsx
Expand Down Expand Up @@ -119,7 +127,8 @@ import { getSession, getUser, requireAuth } from 'void/auth';
- `getUser()` returns the current `AuthUser | null`
- `getSession()` returns `{ user, session } | null`
- `requireAuth(c)` returns the authenticated user or throws `401`
- [`getAuth(c)`](../reference/api/auth.md#getauth-c) returns the request's Better Auth instance, including typed plugin APIs from `auth.ts`.
- `requireAuth(c, { throwRedirect: '/login' })` returns the user or throws a login redirect
- [`getAuth(c)`](../reference/api/auth.md#getauth-c) returns the request's Better Auth instance, with plugin APIs inferred from `auth.ts`, for use with Better Auth helpers.

Import `AuthUser` and `AuthSession` from `void/auth` for type annotations. They include the fields your Better Auth plugins and `user.additionalFields` add, such as `role` from `admin()`. See their fields in the [API reference](../reference/api/auth.md#authuser).

Expand Down
21 changes: 21 additions & 0 deletions docs/integrations/hono.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,24 @@ throw new HTTPException(404, { message: 'User not found' });
```

For the full list of built-in middleware, see the [Hono documentation](https://hono.dev/docs/middleware/builtin).

### Redirects

Return `c.redirect()` from a handler to redirect. From a shared helper, throw an `HTTPException` with the redirect response in `res`. This works in loaders, actions, and middleware, including client-side page visits:

```ts
// lib/require-page-user.ts
import { HTTPException } from 'hono/http-exception';
import type { CloudContext } from 'void';
import { getUser } from 'void/auth';

export function requirePageUser(c: CloudContext) {
const user = getUser();
if (!user) {
throw new HTTPException(302, { res: c.redirect('/login') });
}
return user;
}
```

After a mutation, use `303` for both the exception and `c.redirect('/login', 303)` so the browser follows with a GET.
24 changes: 21 additions & 3 deletions docs/reference/api/auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,11 @@ Enable [authentication](../../guide/auth.md) before calling this helper; it thro
function getAuth(c: CloudContext): AuthInstance;
```

## `requireAuth(c)` {#requireauth-c}
## `requireAuth(c, options?)` {#requireauth-c}

Extracts the authenticated user from the request context. Throws a 401 `HTTPException` if no session is present.
Returns the authenticated user from the request context. Without `throwRedirect`, throws a 401 `HTTPException` if no session is present.

Use it without options in route handlers or actions when you want a plain-text `401`, not an error page:

```ts
import { defineHandler } from 'void';
Expand All @@ -91,10 +93,26 @@ export const GET = defineHandler((c) => {
});
```

For protected pages, pass `throwRedirect` to [redirect unauthenticated visitors to login](../../guide/auth.md#protect-a-server-route):

```ts
import { defineHandler } from 'void';
import { requireAuth } from 'void/auth';

export const loader = defineHandler((c) => {
const user = requireAuth(c, { throwRedirect: '/login' });
return { email: user.email };
});
```

`throwRedirect` works in loaders, actions, and middleware. When signed out, it throws a redirect with status `302` for GET/HEAD requests or `303` for other methods, stopping execution. When signed in, it returns the user normally.

The destination is application-controlled.

**Signature:**

```ts
function requireAuth(c: CloudContext): AuthUser;
function requireAuth(c: CloudContext, options?: { throwRedirect?: string }): AuthUser;
```

## `AuthUser` {#authuser}
Expand Down
2 changes: 1 addition & 1 deletion packages/void/skills/void/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Use `void deploy --skip-migrations` when database migrations run separately; it
| Pages mode, loader/action, forms, layouts | `docs/guide/pages-routing/*.md`, `docs/guide/type-safety.md` |
| Database and migrations | `docs/guide/database.md`, `docs/guide/type-safety.md` |
| Typed fetch and end-to-end typing | `docs/guide/typed-fetch.md`, `docs/guide/type-safety.md` |
| Authentication | `docs/guide/auth.md`, `docs/guide/env-vars.md` |
| Authentication | `docs/guide/auth.md`, `docs/reference/api/auth.md`, `docs/guide/env-vars.md` |
| Cloudflare runtime bindings and config | `docs/integrations/cloudflare.md`, `docs/reference/config.md`, `docs/guide/env-vars.md` |
| AI inference (Workers AI, providers) | `docs/guide/ai.md` |
| Platform AI logging policy | `docs/reference/cli/platform-users.md#ai-gateway-logging` |
Expand Down
5 changes: 5 additions & 0 deletions packages/void/src/runtime/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,14 @@ export function getAuth(c: Context): AuthInstance {

export function requireAuth<E extends Env & { Variables: { user: AuthUser | null } }>(
c: Context<E>,
options?: { throwRedirect?: string },
): AuthUser {
const user = c.get('user');
if (!user) {
if (options?.throwRedirect !== undefined) {
const status = c.req.method === 'GET' || c.req.method === 'HEAD' ? 302 : 303;
throw new HTTPException(status, { res: c.redirect(options.throwRedirect, status) });
}
throw new HTTPException(401, { message: 'Unauthorized' });
}
return user;
Expand Down
5 changes: 5 additions & 0 deletions packages/void/test/integration/auth-types-typecheck.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@ describe('generated auth types in a consumer project', () => {
' getSession()?.session.impersonatedBy;\n' +
' const user = requireAuth(c);\n' +
' const requiredRole: string | null | undefined = user.role;\n' +
' const redirectedUser = requireAuth(c, { throwRedirect: "/login" });\n' +
' const redirectedId: string = redirectedUser.id;\n' +
' const redirectedRole: string | null | undefined = redirectedUser.role;\n' +
' // @ts-expect-error throwRedirect must be a string\n' +
' requireAuth(c, { throwRedirect: 123 });\n' +
' const fields: Record<string, unknown> = user;\n' +
' logger.info("signed in", user);\n' +
' // @ts-expect-error not a field of the inferred user\n' +
Expand Down
Loading
Loading