Next.js Discord

Discord Forum

Issue with Using a Variable for matcher in Next.js Middleware Configuration

Unanswered
Flemish Giant posted this in #help-forum
Open in Discord
Flemish GiantOP
Hi everyone! I'm having an issue with the matcher configuration in my Next.js middleware. Here's what I'm trying to do:

I'm defining publicPattern like this:
const public_pages = [
  'login',
  'register',
]
const public_apis = [
  'api/example'
]
const publicPattern = `/((?!`+[...public_pages,...public_apis].join('|')+`|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)`;

Then, I'm using it in the middleware config like this:
export const config = {
  matcher: [
    publicPattern,
  ],
};

However, this doesn't work—the middleware doesn't seem to process requests as expected. But if I copy-paste the publicPattern string value directly into the matcher array, like this:
export const config = {
  matcher: [
    `^((?!login|register|api/example|_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|css|js)$).*\\?.*)$`,
  ],
};

It works perfectly.

Does anyone know why referencing publicPattern as a variable might not work in the matcher configuration? Is there a limitation or specific behavior of matcher that I’m missing? Any insights would be greatly appreciated!

0 Replies