Skip to content

Commit d74ed2c

Browse files
authored
feat: add throwRedirect option to requireAuth (closes #785) (#812)
The PR closes #785. It adds new `throwRedirect` option to `requireAuth` that instead of throwing `HTTPException` that results in a following scenario: > A logged-out visitor gets a plain-text page that says "Unauthorized". On a client visit, the client gets a non-JSON response and does a full reload, which lands on the same text. On main the 401 doesn't go to _error either, because only 404s and unexpected errors render a boundary. This allows using `requireAuth` consistently in handlers and loaders for the same purpose leaving `getUser` for cases when devs need to serve page with `user: null` ```ts const user = getUser(); if (!user) { return c.redirect("/login"); } ``` -> ```ts const user = requireAuth(c, { throwRedirect: "/login" }); ``` Additionally, the PR adds correct redirect semantics of returning `302` or `303` depending on the method: - `GET`/`HEAD` → `302`: a normal temporary redirect. - Other → `303`: explicitly tells the browser to follow the redirect with `GET`, rather than repeat the original method and body.
1 parent ae024fb commit d74ed2c

49 files changed

Lines changed: 1516 additions & 31 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/guide/auth.md‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,9 @@ await auth.signIn.email({
3838
});
3939
```
4040

41-
### 3. Protect a server route
41+
### 3. Protect a server route {#protect-a-server-route}
4242

43-
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:
43+
Call `requireAuth` in a route handler or action to get the signed-in user or reject unauthenticated requests with `401`:
4444

4545
```ts
4646
// routes/api/profile.ts
@@ -53,21 +53,29 @@ export const GET = defineHandler((c) => {
5353
});
5454
```
5555

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

5858
```ts
5959
// pages/dashboard.server.ts
6060
import { defineHandler, type InferProps } from 'void';
61-
import { getUser } from 'void/auth';
61+
import { requireAuth } from 'void/auth';
6262

6363
export type Props = InferProps<typeof loader>;
6464

65-
export const loader = defineHandler(() => {
66-
const user = getUser();
65+
export const loader = defineHandler((c) => {
66+
const user = requireAuth(c, {
67+
throwRedirect: '/login',
68+
});
6769
return { user };
6870
});
6971
```
7072

73+
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.
74+
75+
Signing in does not replay a rejected action.
76+
77+
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.
78+
7179
### 4. Sign out
7280

7381
```tsx
@@ -119,7 +127,8 @@ import { getSession, getUser, requireAuth } from 'void/auth';
119127
- `getUser()` returns the current `AuthUser | null`
120128
- `getSession()` returns `{ user, session } | null`
121129
- `requireAuth(c)` returns the authenticated user or throws `401`
122-
- [`getAuth(c)`](../reference/api/auth.md#getauth-c) returns the request's Better Auth instance, including typed plugin APIs from `auth.ts`.
130+
- `requireAuth(c, { throwRedirect: '/login' })` returns the user or throws a login redirect
131+
- [`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.
123132

124133
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).
125134

‎docs/integrations/hono.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,3 +104,24 @@ throw new HTTPException(404, { message: 'User not found' });
104104
```
105105

106106
For the full list of built-in middleware, see the [Hono documentation](https://hono.dev/docs/middleware/builtin).
107+
108+
### Redirects
109+
110+
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:
111+
112+
```ts
113+
// lib/require-page-user.ts
114+
import { HTTPException } from 'hono/http-exception';
115+
import type { CloudContext } from 'void';
116+
import { getUser } from 'void/auth';
117+
118+
export function requirePageUser(c: CloudContext) {
119+
const user = getUser();
120+
if (!user) {
121+
throw new HTTPException(302, { res: c.redirect('/login') });
122+
}
123+
return user;
124+
}
125+
```
126+
127+
After a mutation, use `303` for both the exception and `c.redirect('/login', 303)` so the browser follows with a GET.

‎docs/reference/api/auth.md‎

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,9 +77,11 @@ Enable [authentication](../../guide/auth.md) before calling this helper; it thro
7777
function getAuth(c: CloudContext): AuthInstance;
7878
```
7979

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

82-
Extracts the authenticated user from the request context. Throws a 401 `HTTPException` if no session is present.
82+
Returns the authenticated user from the request context. Without `throwRedirect`, throws a 401 `HTTPException` if no session is present.
83+
84+
Use it without options in route handlers or actions when you want a plain-text `401`, not an error page:
8385

8486
```ts
8587
import { defineHandler } from 'void';
@@ -91,10 +93,26 @@ export const GET = defineHandler((c) => {
9193
});
9294
```
9395

96+
For protected pages, pass `throwRedirect` to [redirect unauthenticated visitors to login](../../guide/auth.md#protect-a-server-route):
97+
98+
```ts
99+
import { defineHandler } from 'void';
100+
import { requireAuth } from 'void/auth';
101+
102+
export const loader = defineHandler((c) => {
103+
const user = requireAuth(c, { throwRedirect: '/login' });
104+
return { email: user.email };
105+
});
106+
```
107+
108+
`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.
109+
110+
The destination is application-controlled.
111+
94112
**Signature:**
95113

96114
```ts
97-
function requireAuth(c: CloudContext): AuthUser;
115+
function requireAuth(c: CloudContext, options?: { throwRedirect?: string }): AuthUser;
98116
```
99117

100118
## `AuthUser` {#authuser}

‎packages/void/skills/void/SKILL.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ Use `void deploy --skip-migrations` when database migrations run separately; it
4545
| Pages mode, loader/action, forms, layouts | `docs/guide/pages-routing/*.md`, `docs/guide/type-safety.md` |
4646
| Database and migrations | `docs/guide/database.md`, `docs/guide/type-safety.md` |
4747
| Typed fetch and end-to-end typing | `docs/guide/typed-fetch.md`, `docs/guide/type-safety.md` |
48-
| Authentication | `docs/guide/auth.md`, `docs/guide/env-vars.md` |
48+
| Authentication | `docs/guide/auth.md`, `docs/reference/api/auth.md`, `docs/guide/env-vars.md` |
4949
| Cloudflare runtime bindings and config | `docs/integrations/cloudflare.md`, `docs/reference/config.md`, `docs/guide/env-vars.md` |
5050
| AI inference (Workers AI, providers) | `docs/guide/ai.md` |
5151
| Platform AI logging policy | `docs/reference/cli/platform-users.md#ai-gateway-logging` |

‎packages/void/src/runtime/auth.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,14 @@ export function getAuth(c: Context): AuthInstance {
101101

102102
export function requireAuth<E extends Env & { Variables: { user: AuthUser | null } }>(
103103
c: Context<E>,
104+
options?: { throwRedirect?: string },
104105
): AuthUser {
105106
const user = c.get('user');
106107
if (!user) {
108+
if (options?.throwRedirect !== undefined) {
109+
const status = c.req.method === 'GET' || c.req.method === 'HEAD' ? 302 : 303;
110+
throw new HTTPException(status, { res: c.redirect(options.throwRedirect, status) });
111+
}
107112
throw new HTTPException(401, { message: 'Unauthorized' });
108113
}
109114
return user;

‎packages/void/test/integration/auth-types-typecheck.test.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,11 @@ describe('generated auth types in a consumer project', () => {
8888
' getSession()?.session.impersonatedBy;\n' +
8989
' const user = requireAuth(c);\n' +
9090
' const requiredRole: string | null | undefined = user.role;\n' +
91+
' const redirectedUser = requireAuth(c, { throwRedirect: "/login" });\n' +
92+
' const redirectedId: string = redirectedUser.id;\n' +
93+
' const redirectedRole: string | null | undefined = redirectedUser.role;\n' +
94+
' // @ts-expect-error throwRedirect must be a string\n' +
95+
' requireAuth(c, { throwRedirect: 123 });\n' +
9196
' const fields: Record<string, unknown> = user;\n' +
9297
' logger.info("signed in", user);\n' +
9398
' // @ts-expect-error not a field of the inferred user\n' +

0 commit comments

Comments
 (0)