Below is the middleware file I've implemented:
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";
import { getApiAuth } from "./app/middleware/api/auth";
const validateApi = (req: Request) => {
const isValid = getApiAuth(req);
if (!isValid)
return new NextResponse(
JSON.stringify({
message: "Un-authorized",
}),
{
status: 401,
}
);
};
// To make this function asynchronous, mark it as `async` when using `await`
export function middleware(request: NextRequest) {
console.log("Cookie", request.cookies);
const isApiPath = request.nextUrl.pathname.startsWith("/api");
if (isApiPath) {
return validateApi(request);
}
return NextResponse.next();
}
export const config = {
matcher: "/((?!api/login|_next/static|_next/image|favicon.ico).*)",
};
I am looking for a way to dynamically generate the matcher regex in JavaScript or find a more concise method to protect routes. My goal is to configure the matcher variable with minimal code to secure routes and specify public routes.
// Matcher example: '/((?!api|_next/static|_next/image|favicon.ico).*)'
const publicRoutes = [
"api/login",
"_next/static",
"_next/image",
"favicon.ico",
];
export const config = {
matcher: `/((?!${publicRoutes.join("|")}).*)`,
};