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.emailNext.js integration | Better Auth
Integrate Better Auth with Next.js.

9 Replies
Middleware is for optimistic checks only, maybe there should be a way to get the payload from the cookie? @bekacru
there is
getCookieCache
helper that can be imported from better-auth/cookies
not documented yetSo should I use
getCookieCache
and something like sessionCookie.session
?
Or await betterFetch
is the better way?
In this casein 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.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
no if it returns the cookie that's valid
So if its valid…why my middleware isnt working? Do you have any idea
is it retuning null?
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