import { NextFetchEvent, NextMiddleware, NextResponse } from 'next/server'; import settings from 'settings'; import { PzNextRequest } from '.'; import logger from '../utils/log'; import { urlLocaleMatcherRegex } from '../utils'; import { getUrlPathWithLocale } from '../utils/localization'; import { shouldIgnoreRedirect } from '../utils/redirect-ignore'; import { ROUTES } from 'routes'; // This middleware is used to handle url redirections set in Omnitron const withUrlRedirection = (middleware: NextMiddleware) => async (req: PzNextRequest, event: NextFetchEvent) => { if (settings.usePrettyUrlRoute) { return middleware(req, event); } const url = req.nextUrl.clone(); const ip = req.headers.get('x-forwarded-for') ?? ''; const pathnameWithoutLocale = url.pathname.replace( urlLocaleMatcherRegex, '' ); if ( Object.entries(ROUTES).find(([, value]) => new RegExp(`^${value}$`).test(pathnameWithoutLocale) ) || pathnameWithoutLocale.startsWith('/orders') ) { return middleware(req, event); } try { const request = await fetch( `${settings.commerceUrl}${pathnameWithoutLocale}${url.search}`, { headers: { 'x-forwarded-for': ip, Cookie: req.headers.get('cookie') ?? '' }, redirect: 'manual', next: { revalidate: 0 } } ); if (request.headers.get('location')) { const location = request.headers.get('location'); const redirectUrl = new URL( request.headers.get('location'), location.startsWith('http') ? '' : url.origin ); redirectUrl.pathname = getUrlPathWithLocale( redirectUrl.pathname, req.middlewareParams.rewrites.locale ); const setCookies = request.headers.getSetCookie(); if ( shouldIgnoreRedirect( url.pathname, req.middlewareParams.rewrites.locale ) ) { return middleware(req, event); } const response = NextResponse.redirect(redirectUrl.toString(), { status: request.status }); if (setCookies && setCookies.length > 0) { for (const cookie of setCookies) { response.headers.append('Set-Cookie', cookie); } } return response; } } catch (error) { logger.error('withUrlRedirection error', { error, ip }); } return middleware(req, event); }; export default withUrlRedirection;