46 lines
1.1 KiB
TypeScript
46 lines
1.1 KiB
TypeScript
import { NextRequest, NextResponse } from "next/server";
|
|
import { auth } from "@/lib/auth";
|
|
|
|
const publicPaths = ["/", "/explore", "/sign-in", "/sign-up", "/api/auth"];
|
|
const protectedPaths = ["/compare", "/profile"];
|
|
|
|
export async function middleware(request: NextRequest) {
|
|
const { pathname } = request.nextUrl;
|
|
|
|
if (
|
|
pathname.startsWith("/_next") ||
|
|
pathname.startsWith("/favicon") ||
|
|
pathname.includes(".")
|
|
) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
const isPublic = publicPaths.some(
|
|
(path) => pathname === path || pathname.startsWith(path + "/"),
|
|
);
|
|
|
|
const isProtected = protectedPaths.some(
|
|
(path) => pathname === path || pathname.startsWith(path + "/"),
|
|
);
|
|
|
|
if (isPublic && !isProtected) {
|
|
return NextResponse.next();
|
|
}
|
|
|
|
const session = await auth.api.getSession({
|
|
headers: request.headers,
|
|
});
|
|
|
|
if (!session && isProtected) {
|
|
const signInUrl = new URL("/sign-in", request.url);
|
|
signInUrl.searchParams.set("callbackUrl", pathname);
|
|
return NextResponse.redirect(signInUrl);
|
|
}
|
|
|
|
return NextResponse.next();
|
|
}
|
|
|
|
export const config = {
|
|
matcher: ["/((?!_next/static|_next/image|favicon.ico).*)"],
|
|
};
|