Files
store_ai_front/middleware.ts
2026-05-09 18:49:15 +08:00

34 lines
1.1 KiB
TypeScript

import {NextRequest, NextResponse} from "next/server";
const AUTH_COOKIE_NAME = "storeai-auth";
const PROTECTED_PREFIXES = ["/dashboard", "/onboarding"];
const AUTH_PATHS = ["/login", "/signup"];
export function middleware(request: NextRequest) {
const {pathname, search} = request.nextUrl;
const isAuthenticated = request.cookies.get(AUTH_COOKIE_NAME)?.value === "1";
const isProtectedPath = PROTECTED_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
const isAuthPath = AUTH_PATHS.includes(pathname);
if (isProtectedPath && !isAuthenticated) {
const url = request.nextUrl.clone();
url.pathname = "/login";
url.search = "";
url.searchParams.set("next", `${pathname}${search}`);
return NextResponse.redirect(url);
}
if (isAuthPath && isAuthenticated) {
const url = request.nextUrl.clone();
url.pathname = "/dashboard";
url.search = "";
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/dashboard/:path*", "/onboarding/:path*", "/login", "/signup"],
};