MKTSoft
MKTSoft
BABetter Auth
Created by jeffreyyvdb on 4/20/2025 in #help
Better auth does not work on NextJS
For better performance, you can change your middleware to see. 
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export async function middleware(request: NextRequest) {
// add here all your public paths
const path = request.nextUrl.pathname;
const publicPaths = ["/", "/sign-in", "/sign-up", "/forgot-password"];
// and here your api path
const apiPaths = "/api";

const cookies = getSessionCookie(request);

// Ignore your API path
if (path.startsWith(apiPaths)) {
return NextResponse.next();
}

if (!cookies && !publicPaths.includes(path)) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
return NextResponse.next();
}

// Change your config like this
export const config = {
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
};
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";

export async function middleware(request: NextRequest) {
// add here all your public paths
const path = request.nextUrl.pathname;
const publicPaths = ["/", "/sign-in", "/sign-up", "/forgot-password"];
// and here your api path
const apiPaths = "/api";

const cookies = getSessionCookie(request);

// Ignore your API path
if (path.startsWith(apiPaths)) {
return NextResponse.next();
}

if (!cookies && !publicPaths.includes(path)) {
return NextResponse.redirect(new URL("/sign-in", request.url));
}
return NextResponse.next();
}

// Change your config like this
export const config = {
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
};
28 replies