@payloadpack/redirectsGuides
Match query strings in a proxy
Add a Next.js 16 proxy so redirects with query strings answer before cached page routes and keep visitor parameters.
When to use this
Section titled “When to use this”- You need redirects that match a query string, such as
/news.aspx?id=123, even at a path where a page still renders. - You want redirects to keep the visitor’s query string parameters, such as
utm_source. - You want all your redirect code in
proxy.ts, at a database query on every page view. See Answer every redirect in the proxy.
Every request passes through this proxy, though only URLs with a query string run a database query.
Prerequisites: Complete Installation (keep your page route) on a Next.js 16 site using proxy.ts.
A page route cached per path never sees query strings, so a Next.js proxy checks requests that carry one before they reach your page route. Next.js 16 runs proxy.ts on Node.js.
Add the proxy
Section titled “Add the proxy”Put proxy.ts next to the src/find-page.ts you wrote in step 5 of Installation, whose findPage it calls.
import payloadConfig from '@payload-config'import { findRedirect } from '@payloadpack/redirects'import { NextResponse, type NextRequest } from 'next/server'import { getPayload } from 'payload'
import { findPage } from './find-page'
// Answers the redirects that match a query string, which the page route never sees when its page is// cached per path. A URL without one goes on to the page route, which checks for a redirect itself.export async function proxy(request: NextRequest) { if (request.nextUrl.search === '') return NextResponse.next()
let path: string try { // A page's path has no slash at its end, which a site with trailingSlash adds. path = decodeURIComponent(request.nextUrl.pathname).replace(/\/$/, '') || '/' } catch { return NextResponse.next() } const payload = await getPayload({ config: payloadConfig }) const hasDocument = async (pathAsked: string) => (await findPage({ path: pathAsked, payload })) !== null
const { foundRedirect } = await findRedirect({ hasDocument, path, payload, searchParams: request.nextUrl.searchParams }) if (!foundRedirect) return NextResponse.next() // A page always wins over a redirect from its path, but not over one that matched the query string. if (!foundRedirect.matchedQueryString && (await hasDocument(path))) return NextResponse.next() // A path on this site goes below its basePath, which Next adds to a page route's redirect() itself. const { destination, permanent } = foundRedirect const url = destination.startsWith('/') ? `${request.nextUrl.basePath}${destination}` : destination return NextResponse.redirect(new URL(url, request.url), permanent ? 308 : 307)}
// Skips the admin, the API and Next's own files, whole segments only, so a path such as /apiary passes.export const config = { matcher: ['/((?!(?:admin|api|_next)(?:/|$)).*)'] }How requests flow
Section titled “How requests flow”- URLs without a query string: The proxy returns
NextResponse.next()with no database query. Keep your page route redirect check to handle URLs without a query string. - URLs with a query string: The proxy runs one lookup (one database query, plus one more if the winning redirect sends visitors to a document). When a redirect sends visitors to another path on your site,
findRedirectaskshasDocumentand follows any chain. - Page vs query-string redirect: A page always wins over a redirect from its path alone, so the proxy checks
hasDocument(path)only whenfoundRedirect.matchedQueryStringisfalse. A redirect that matched the query string wins over the page, so/products?id=5can redirect while/productsstays. - Visitor query strings: The proxy passes
request.nextUrl.searchParamstofindRedirect, so destinations keep visitor parameters such asutm_source(minus parameters the redirect matched). A page route withoutsearchParamsdoes not pass them on. - Matcher:
config.matcherskipsadmin,api, and_nextas whole segments, so a path such as/apiarystill reaches the proxy. - Hosting cost: Every request passes through the proxy. On
next startthat costs next to nothing; on Vercel it is a function call per request. See Speed.
Answer every redirect in the proxy
Section titled “Answer every redirect in the proxy”To keep all your redirect code in proxy.ts, let the proxy check every request, with or without a query string:
// Answers the redirects that match a query string, which the page route never sees when its page is// cached per path. A URL without one goes on to the page route, which checks for a redirect itself.// Answers every redirect, with or without a query string, so the page route asks for none.export async function proxy(request: NextRequest) { if (request.nextUrl.search === '') return NextResponse.next()Then remove the redirect check from your page route, so it only renders the page or calls notFound().
A page still wins over a redirect from its path alone, as above. Keep the proxy’s hasDocument(path) check: the proxy in Let redirects win over pages has none, so without winOverDocuments it sends visitors away from published pages.
Sites with basePath or trailingSlash
Section titled “Sites with basePath or trailingSlash”basePath: Next.js addsbasePathautomatically toredirect()in a page route, not toNextResponse.redirect(). The proxy prependsrequest.nextUrl.basePathwheneverdestinationstarts with/.trailingSlash: The proxy strips a trailing slash before checkinghasDocument, matching how page paths and a From are stored while keeping/for the home page.
Add your own tracking parameters
Section titled “Add your own tracking parameters”Redirects never compare utm_source, utm_medium, utm_campaign, utm_term, utm_content, gclid, or fbclid. To add your site’s own parameters, configure trackingParameters in redirectsPlugin().