Files
AbelBirdNest-Stock/middleware.ts

49 lines
1.2 KiB
TypeScript

import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { AUTH_COOKIE_NAME } from "@/lib/auth";
const publicPaths = [
"/login",
"/reset-password",
"/verify-email",
"/contact-admin",
"/help-public",
"/privacy-policy",
"/terms-and-conditions"
];
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const hasSession = Boolean(request.cookies.get(AUTH_COOKIE_NAME)?.value);
const isPublic = publicPaths.some((path) => pathname === path);
const isStaticAsset =
pathname.startsWith("/api/") ||
pathname.startsWith("/_next") ||
pathname.startsWith("/favicon.ico") ||
pathname.match(/\.(.*)$/);
if (isStaticAsset) {
return NextResponse.next();
}
if (pathname === "/") {
const url = request.nextUrl.clone();
url.pathname = hasSession ? "/dashboard" : "/login";
return NextResponse.redirect(url);
}
if (!hasSession && !isPublic) {
const url = request.nextUrl.clone();
url.pathname = "/login";
url.searchParams.set("next", pathname);
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"]
};