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
image.png
Integrate Better Auth with Next.js.
Was this page helpful?