-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathauth-guard.ts
29 lines (24 loc) · 915 Bytes
/
auth-guard.ts
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
import { createMiddleware } from "@tanstack/start";
import { getWebRequest, setResponseStatus } from "@tanstack/start/server";
import { auth } from "~/lib/server/auth";
// https://tanstack.com/start/latest/docs/framework/react/middleware
// This is a sample middleware that you can use in your server functions.
/**
* Middleware to force authentication on a server function, and add the user to the context.
*/
export const authMiddleware = createMiddleware().server(async ({ next }) => {
const { headers } = getWebRequest()!;
const session = await auth.api.getSession({
headers,
query: {
// ensure session is fresh
// https://www.better-auth.com/docs/concepts/session-management#session-caching
disableCookieCache: true,
},
});
if (!session) {
setResponseStatus(401);
throw new Error("Unauthorized");
}
return next({ context: { user: session.user } });
});