Untitled
unknown
typescript
a year ago
2.6 kB
5
No Index
import { authMiddleware } from "@descope/nextjs-sdk/server";
import { env } from "./env";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
import { i18nRouter } from 'next-i18n-router';
import i18nConfig from './i18nConfig';
export async function middleware(req: NextRequest) {
// Initialize a NextResponse object
const nextResponse = NextResponse.next();
const activatedMiddleware = [
authMiddleware({
projectId: env.NEXT_PUBLIC_AUTH_DESCOPE_ID || "",
redirectUrl: "/en/auth",
publicRoutes: ["/", "/en", "/en/auth"],
}),
i18nRouter(req, i18nConfig)
];
// Map through activated middleware functions
const middlewareFunctions = activatedMiddleware
.filter((middleware) => typeof middleware === 'function') // Filter out NextResponse objects
.map(async (middleware) => await middleware(req));
// Array to store middleware headers
const middlewareHeader = [];
// Loop through middleware functions
for (const middleware of middlewareFunctions) {
// Execute middleware function and await the result
const result = await middleware;
console.log("middleware result", result);
// Check if the result is not okay and return it
if (!result.ok) {
return result;
}
// Push middleware headers to the array
middlewareHeader.push(result.headers);
}
//First we are going to define a redirectTo variable
let redirectTo = null;
// Check each header in middlewareHeader
middlewareHeader.some((header) => {
// Look for the 'x-middleware-request-redirect' header
const redirect = header.get('x-middleware-request-redirect');
if (redirect) {
// If a redirect is found, store the value and break the loop
redirectTo = redirect;
return true; // Break the loop
}
// Continue to the next header in case the redirect header is not found
return false; // Continue the loop
});
// If a redirection is required based on the middleware headers
if (redirectTo) {
// Perform the redirection
return NextResponse.redirect(new URL(redirectTo, req.url), {
status: 307, // Use the appropriate HTTP status code for the redirect
});
}
// If no redirection is needed, proceed to the next middleware or route handler
return nextResponse;
}
// Read more: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher
export const config = {
matcher: [
'/',
'/(en)/:path*',
"/((?!api|_next/static|_next/image|favicon.ico).*)"
],
};
Editor is loading...
Leave a Comment