Skip to content

@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.

  • 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.

Put proxy.ts next to the src/find-page.ts you wrote in step 5 of Installation, whose findPage it calls.

src/proxy.ts
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)(?:/|$)).*)'] }
  • 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, findRedirect asks hasDocument and 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 when foundRedirect.matchedQueryString is false. A redirect that matched the query string wins over the page, so /products?id=5 can redirect while /products stays.
  • Visitor query strings: The proxy passes request.nextUrl.searchParams to findRedirect, so destinations keep visitor parameters such as utm_source (minus parameters the redirect matched). A page route without searchParams does not pass them on.
  • Matcher: config.matcher skips admin, api, and _next as whole segments, so a path such as /apiary still reaches the proxy.
  • Hosting cost: Every request passes through the proxy. On next start that costs next to nothing; on Vercel it is a function call per request. See Speed.

To keep all your redirect code in proxy.ts, let the proxy check every request, with or without a query string:

src/proxy.ts
// 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.

  • basePath: Next.js adds basePath automatically to redirect() in a page route, not to NextResponse.redirect(). The proxy prepends request.nextUrl.basePath whenever destination starts with /.
  • trailingSlash: The proxy strips a trailing slash before checking hasDocument, matching how page paths and a From are stored while keeping / for the home page.

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().