Created
March 4, 2026 00:58
-
-
Save Ynng/fa9360a37633631de394a71c8becc91e to your computer and use it in GitHub Desktop.
Example middleware for tanstack start + better auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export const userMiddleware = createMiddleware({ | |
| type: 'function', | |
| }).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, | |
| }, | |
| }) | |
| return next({ | |
| context: { | |
| user: session?.user, | |
| }, | |
| }) | |
| }) | |
| export const userRequiredMiddleware = createMiddleware({ | |
| type: 'function', | |
| }) | |
| .middleware([userMiddleware]) | |
| .server(async ({ next, context }) => { | |
| if (!context.user) { | |
| throw json( | |
| { error: 'You must be logged in to access this resource' }, | |
| { status: 401 }, | |
| ) | |
| } | |
| return next({ | |
| context: { | |
| user: context.user, // make user non-nullable | |
| }, | |
| }) | |
| }) | |
| export const adminRequiredMiddleware = createMiddleware({ | |
| type: 'function', | |
| }) | |
| .middleware([userRequiredMiddleware]) | |
| .server(async ({ next, context }) => { | |
| const adminQuery = await db | |
| .select() | |
| .from(adminUsers) | |
| .where(eq(adminUsers.userId, context.user.id)) | |
| if (adminQuery.length === 0) { | |
| throw json( | |
| { error: 'You must be an admin to access this resource' }, | |
| { status: 403 }, | |
| ) | |
| } | |
| return next() | |
| }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment