import { PzNextRequest, withPzDefault } from '@akinon/next/middlewares'; import { PREVIEW_ID_QUERY_PARAM } from '@akinon/next/utils/preview'; import { NextMiddleware, NextResponse } from 'next/server'; /** * !IMPORTANT * Do not remove this file or withPzDefault wrapper. * It is required for the application to work properly. * If you need to add custom matcher, don't remove the existing one. */ export const config = { // For .xml.gz type sitemap urls, update '/(.*sitemap\\.xml)' with this regex '/(.*sitemap\\.xml|sitemap/.*.xml(?:.gz)?)/', matcher: [ '/((?!api|_next|[\\w-\\/*]+\\.\\w+).*)', '/(.*sitemap\\.xml)', '/(.+\\.)(html|htm|aspx|asp|php)', '/(.*orders\\/checkout-with-token.*)' ] }; const proxy: NextMiddleware = () => // req: PzNextRequest, // event: NextFetchEvent { // If you use a custom response such as NextResponse.json(), // you should set pz-override-response header to true as shown below. // Otherwise, you'll get a 404 error. // Example: // return NextResponse.json({ status: 'ok' }, { headers: { 'pz-override-response': 'true' } }); return NextResponse.next(); }; const pzMiddleware = withPzDefault(proxy); const PREVIEW_EXIT_VALUES = new Set(['exit', 'off', '0', 'false']); /** * Widget preview entry: any page url carrying `?preview` is redirected to the * draft-mode route handler (/api/preview), which sets/clears the bypass and * preview-id cookies and returns to the same page without the params. Runs * BEFORE withPzDefault so the redirect is not subject to its response * rewriting (pz-override-response). * * The `?preview` value is a signed token naming WHICH preview to view (see * utils/preview-token.ts); it travels only as far as the route handler, which * stores the preview id for the rest of the session. A stray `preview_id` * from an old-style link is dropped from the return url. */ const middleware: NextMiddleware = (req, event) => { const url = req.nextUrl; if (url.searchParams.has('preview')) { const value = url.searchParams.get('preview') ?? ''; const target = url.clone(); target.searchParams.delete('preview'); target.searchParams.delete(PREVIEW_ID_QUERY_PARAM); const previewApi = url.clone(); previewApi.pathname = '/api/preview'; previewApi.search = ''; previewApi.searchParams.set( 'redirect', `${target.pathname}${target.search}` ); if (PREVIEW_EXIT_VALUES.has(value.toLowerCase())) { previewApi.searchParams.set('exit', '1'); } else { if (value) previewApi.searchParams.set('token', value); } return NextResponse.redirect(previewApi); } return pzMiddleware(req as PzNextRequest, event); }; export default middleware;