35 lines
1.1 KiB
TypeScript
35 lines
1.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { getToken } from "next-auth/jwt";
|
|
|
|
const protectedPaths = ["/dashboard", "/finances", "/instagram", "/tiktok", "/twitch", "/youtube"];
|
|
|
|
export async function middleware(req: NextRequest) {
|
|
const { pathname } = req.nextUrl;
|
|
const isProtected = protectedPaths.some((p) => pathname.startsWith(p));
|
|
|
|
const token = await getToken({
|
|
req,
|
|
secret: process.env.AUTH_SECRET,
|
|
cookieName: process.env.NODE_ENV === "production"
|
|
? "__Secure-authjs.session-token"
|
|
: "authjs.session-token"
|
|
});
|
|
|
|
if (isProtected && !token) {
|
|
const loginUrl = new URL("/", req.url);
|
|
return NextResponse.redirect(loginUrl);
|
|
}
|
|
|
|
// Redirect already-authenticated users away from login page
|
|
if (pathname === "/" && token) {
|
|
const dashboardUrl = new URL("/dashboard", req.url);
|
|
return NextResponse.redirect(dashboardUrl);
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
|
|
};
|