39 lines
1.2 KiB
TypeScript
39 lines
1.2 KiB
TypeScript
|
|
import { NextRequest, NextResponse } from "next/server";
|
||
|
|
|
||
|
|
// Better Auth's session cookie name (default prefix "better-auth"); the
|
||
|
|
// "__Secure-" variant is used when cookies are served over HTTPS in production.
|
||
|
|
const SESSION_COOKIES = ["better-auth.session_token", "__Secure-better-auth.session_token"];
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Optimistic edge gate: redirect anonymous users away from authed surfaces.
|
||
|
|
* Only checks for the *presence* of a session cookie — real session validation
|
||
|
|
* (and admin/role checks) happen in the route-group layouts. Reading the cookie
|
||
|
|
* directly keeps the middleware bundle free of the auth/jose internals.
|
||
|
|
*/
|
||
|
|
export function middleware(req: NextRequest) {
|
||
|
|
const hasSession = SESSION_COOKIES.some((name) => req.cookies.has(name));
|
||
|
|
const { pathname, search } = req.nextUrl;
|
||
|
|
|
||
|
|
if (!hasSession) {
|
||
|
|
const signIn = new URL("/sign-in", req.url);
|
||
|
|
signIn.searchParams.set("redirect", pathname + search);
|
||
|
|
return NextResponse.redirect(signIn);
|
||
|
|
}
|
||
|
|
|
||
|
|
return NextResponse.next();
|
||
|
|
}
|
||
|
|
|
||
|
|
export const config = {
|
||
|
|
matcher: [
|
||
|
|
"/dashboard/:path*",
|
||
|
|
"/episodes/:path*",
|
||
|
|
"/series/:path*",
|
||
|
|
"/usage/:path*",
|
||
|
|
"/billing/:path*",
|
||
|
|
"/team/:path*",
|
||
|
|
"/api-keys/:path*",
|
||
|
|
"/settings/:path*",
|
||
|
|
"/admin/:path*",
|
||
|
|
],
|
||
|
|
};
|