-
-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathmiddleware.ts
More file actions
48 lines (40 loc) · 1.8 KB
/
middleware.ts
File metadata and controls
48 lines (40 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { createMiddleware } from "@tanstack/react-start";
import { setResponseStatus } from "@tanstack/react-start/server";
import { _getUser } from "@/lib/auth/functions";
// https://tanstack.com/start/latest/docs/framework/react/guide/middleware
/**
* Middleware to force authentication on server requests (including server functions), and add the user to the context.
*
* Follows the cookieCache option in the auth config (template default: 5 mins).
* This is recommended for most cases, like route-level data fetching operations where some staleness may be acceptable and reduced server load is beneficial.
*
* @see https://better-auth.com/docs/concepts/session-management#cookie-cache
*/
export const authMiddleware = createMiddleware().server(async ({ next }) => {
const user = await _getUser();
if (!user) {
setResponseStatus(401);
throw new Error("Unauthorized");
}
return next({ context: { user } });
});
/**
* Middleware to force authentication on server requests (including server functions), and add the user to the context.
*
* Auth cookie cache is disabled, and fresh user session is always fetched from database.
* This is recommended for sensitive/destructive operations and mutations that require the freshest auth state, e.g. to prevent a user from performing an action after their session has expired or been revoked.
*
* @see https://better-auth.com/docs/concepts/session-management#cookie-cache
*/
export const freshAuthMiddleware = createMiddleware().server(async ({ next }) => {
const user = await _getUser({
// ensure session is fresh
// https://better-auth.com/docs/concepts/session-management#cookie-cache
disableCookieCache: true,
});
if (!user) {
setResponseStatus(401);
throw new Error("Unauthorized");
}
return next({ context: { user } });
});