You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit d74ed2c
Browse filesBrowse the repository at this point in the historyBrowse files
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.
Copy file name to clipboardExpand all lines: docs/guide/auth.md
+16-7Lines changed: 16 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -38,9 +38,9 @@ await auth.signIn.email({
38
38
});
39
39
```
40
40
41
-
### 3. Protect a server route
41
+
### 3. Protect a server route {#protect-a-server-route}
42
42
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`:
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.
-`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.
123
132
124
133
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).
Copy file name to clipboardExpand all lines: docs/integrations/hono.md
+21Lines changed: 21 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -104,3 +104,24 @@ throw new HTTPException(404, { message: 'User not found' });
104
104
```
105
105
106
106
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:
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
+
exportconst 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
+
94
112
**Signature:**
95
113
96
114
```ts
97
-
function requireAuth(c:CloudContext):AuthUser;
115
+
function requireAuth(c:CloudContext, options?: { throwRedirect?:string }):AuthUser;
0 commit comments