Middleware in a Better Auth Project

how the middleware of a project using better-auth should look? because i was using this middleware:
import { betterFetch } from "@better-fetch/fetch";
import type { auth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";

type Session = typeof auth.$Infer.Session;

export async function middleware(request: NextRequest) {
const { data: session } = await betterFetch<Session>("/api/auth/get-session", {
baseURL: request.nextUrl.origin,
headers: {
cookie: request.headers.get("cookie") || "", // Forward the cookies from the request
},
});

if (!session) {
return NextResponse.redirect(new URL("/auth/signin", request.url));
}

return NextResponse.next();
}

export const config = {
matcher: "/private/:path*", // The middleware will apply to all routes that start with '/private'
};
import { betterFetch } from "@better-fetch/fetch";
import type { auth } from "@/lib/auth";
import { NextRequest, NextResponse } from "next/server";

type Session = typeof auth.$Infer.Session;

export async function middleware(request: NextRequest) {
const { data: session } = await betterFetch<Session>("/api/auth/get-session", {
baseURL: request.nextUrl.origin,
headers: {
cookie: request.headers.get("cookie") || "", // Forward the cookies from the request
},
});

if (!session) {
return NextResponse.redirect(new URL("/auth/signin", request.url));
}

return NextResponse.next();
}

export const config = {
matcher: "/private/:path*", // The middleware will apply to all routes that start with '/private'
};
and verified that my app is vunerable to the latest nextjs vunerability, how should i modify the middleware even after upgrading to the already patched version? because i heard that its not a good practice to do authentication in the middleware, so even after upgrading to the latest version of nextjs i wanna make things right
Solution:
We highly suggest using the middleware in next just to decide routing for a user and not the only place to check for auth. And fetching session from an api can make your site slow, since now you're running a server and a db on every call. I suggest checking for cookie and on the actual pages, checking for the actual session.
Jump to solution
2 Replies
Solution
bekacru
bekacru4w ago
We highly suggest using the middleware in next just to decide routing for a user and not the only place to check for auth. And fetching session from an api can make your site slow, since now you're running a server and a db on every call. I suggest checking for cookie and on the actual pages, checking for the actual session.
shadow
shadowOP4w ago
yep that's what I thought, thanks for the clarification! by the way, great project!

Did you find this page helpful?