124_webcalibre2/src/proxy.ts

47 lines
No EOL
1.5 KiB
TypeScript

import { NextResponse } from "next/server";
import { auth } from "@/auth";
const protectedRoutes = ["/dashboard", "/profile"];
const apiAuthPrefix = "/api/auth";
export const proxy = auth((req) => {
const { nextUrl } = req;
const path = nextUrl.pathname;
/**
* 1. IMMEDIATE BYPASS FOR UPLOADS
* We check this first. If the user is hitting the upload route,
* we let the request pass through directly to the page/action.
* This prevents the middleware from trying to parse the 100MB body.
*/
if (path.startsWith('/upload')) {
return NextResponse.next();
}
const isLoggedIn = !!req.auth;
const isApiAuthRoute = path.startsWith(apiAuthPrefix);
// Check if the current path is in our protected list
const isProtectedRoute = protectedRoutes.includes(path);
// 2. Allow API Auth calls (Login/Logout/Callback)
if (isApiAuthRoute) {
return NextResponse.next();
}
// 3. Redirect to HOME (/) if trying to access a protected route while logged out
if (isProtectedRoute && !isLoggedIn) {
return NextResponse.redirect(new URL("/", nextUrl));
}
return NextResponse.next();
});
/**
* The Matcher tells Next.js which routes this proxy should run on.
* By adding '|upload' to the negative lookahead (?!...), we tell
* Next.js to ignore the /upload route entirely at the engine level.
*/
export const config = {
matcher: ["/((?!api|_next/static|_next/image|favicon.ico|upload).*)"],
};