import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request, {
cookieName: "session_token",
cookiePrefix: "auth_token",
// useSecureCookies:
// request.nextUrl.protocol === "https:" ||
// process.env.NODE_ENV === "production",
});
const { pathname } = request.nextUrl;
const publicRoutes = [
"/signup",
"/login",
"/forgot-password",
"/reset-password",
"/",
];
// If the user is logged in, prevent access to /signup and /login
if (sessionCookie && publicRoutes.includes(pathname)) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
// If the user is NOT logged in, protect the /dashboard route
if (!sessionCookie && pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/",
"/dashboard/:path*",
"/signup",
"/login",
"/forgot-password",
"/reset-password",
],
};
import { NextRequest, NextResponse } from "next/server";
import { getSessionCookie } from "better-auth/cookies";
export async function middleware(request: NextRequest) {
const sessionCookie = getSessionCookie(request, {
cookieName: "session_token",
cookiePrefix: "auth_token",
// useSecureCookies:
// request.nextUrl.protocol === "https:" ||
// process.env.NODE_ENV === "production",
});
const { pathname } = request.nextUrl;
const publicRoutes = [
"/signup",
"/login",
"/forgot-password",
"/reset-password",
"/",
];
// If the user is logged in, prevent access to /signup and /login
if (sessionCookie && publicRoutes.includes(pathname)) {
return NextResponse.redirect(new URL("/dashboard", request.url));
}
// If the user is NOT logged in, protect the /dashboard route
if (!sessionCookie && pathname.startsWith("/dashboard")) {
return NextResponse.redirect(new URL("/login", request.url));
}
return NextResponse.next();
}
export const config = {
matcher: [
"/",
"/dashboard/:path*",
"/signup",
"/login",
"/forgot-password",
"/reset-password",
],
};