Middleware - Better Auth

Hello everyone! I'm having an issue where my /dashboard route is not being protected even when the user isn't logged in. I'm following the documentation: https://www.better-auth.com/docs/integrations/next#middleware Additionally, how could I protect a route in case the user is not an admin? I noticed there's nothing like sessionCookie.user?.role. middleware.ts import { getSessionCookie } from "better-auth/cookies"; import { NextRequest, NextResponse } from "next/server"; export async function middleware(request: NextRequest) { const sessionCookie = getSessionCookie(request); if (!sessionCookie) { return NextResponse.redirect(new URL("/", request.url)); } return NextResponse.next(); } export const config = { matcher: ["/dashboard"], }; auth.ts import { betterAuth } from "better-auth"; import { MongoClient } from "mongodb"; import { mongodbAdapter } from "better-auth/adapters/mongodb"; import { admin } from "better-auth/plugins" import { nextCookies } from "better-auth/next-js"; const client = new MongoClient("mongodb://127.0.0.1:27017/teste"); const db = client.db(); export const auth = betterAuth({ database: mongodbAdapter(db), emailAndPassword: { enabled: true, minPasswordLength: 5 }, plugins: [ admin(), nextCookies() ], }); In files for registering and logging in a user, I'm using authClient.admin.createUser and authClient.signIn.email
Next.js integration | Better Auth
Integrate Better Auth with Next.js.
No description
9 Replies
daveycodez
daveycodez3w ago
Middleware is for optimistic checks only, maybe there should be a way to get the payload from the cookie? @bekacru
bekacru
bekacru3w ago
there is getCookieCache helper that can be imported from better-auth/cookies not documented yet
roque
roqueOP3w ago
So should I use getCookieCache and something like sessionCookie.session? Or await betterFetch is the better way? In this case
bekacru
bekacru3w ago
in your case getSessionCookie should return null unless there is a valid cookie If it's returning non-null value while getSession is returning null, most likely it's beause the cookie value is invalid but getSession wasn't able to clear it.
roque
roqueOP3w ago
Sorry for any dumb questions, I'm new using auths But in my case, when the user is logged in, I get a better-auth.session_token in the Cookies Browser. Isn't this a valid cookie so the middleware can validate? And I'm also using admin(), nextCookies() for plugins. Should I use betterFetch instead? @bekacru
bekacru
bekacru3w ago
no if it returns the cookie that's valid
roque
roqueOP3w ago
So if its valid…why my middleware isnt working? Do you have any idea
bekacru
bekacru3w ago
is it retuning null?
roque
roqueOP3w ago
I found the issue…it was because my middleware wasnt int the scr folder…sorry For the other question, if I want to protect some routes only for admin, how can I do this? Because I cant get the role with getSessionCookie or getCookieCache

Did you find this page helpful?