Next.js Discord

Discord Forum

Middleware match by query param existence

Answered
Eastern Towhee posted this in #help-forum
Open in Discord
Eastern TowheeOP
Is it possible to write middleware matcher that matches routes which contain query param? Some examples include matchers which match by missing headers (https://nextjs.org/docs/app/building-your-application/configuring/content-security-policy) but these features seem to be completely undocumented so I'm not sure how flexible the undocumented matcher syntax is. Also, if these features are not undocumented I'd appreciate if someone knows where they are documented. Middleware docs don't mention them at all: https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher

I know I can check the query params inside the middleware, but the question is can I make the matcher check that to avoid unecessary calls to the middleware?
Answered by fuma
You can't match query parameters in middleware through matcher config, however, matching the query parameters in middleware can also avoid unnecessary calls by an early return
if (condition) return NextResponse.next()

So that the code below won't be executed
View full answer

1 Reply

You can't match query parameters in middleware through matcher config, however, matching the query parameters in middleware can also avoid unnecessary calls by an early return
if (condition) return NextResponse.next()

So that the code below won't be executed
Answer