why regex is not working on header to check request?

Viewed 233

I am using regex to add some value to the response header. I am following this documentation

https://nextjs.org/docs/api-reference/next.config.js/headers

here it is mentioned how to add Regex Path Matching it is not working.

For example, I have created a demo application, in which I have written if the request is /about.css it adds my custom header value in Edge-Cache-Tag. it is working fine

module.exports = {
  async headers() {
    return [
      {
        source: '/about.css',
        headers: [
          {
            key: 'Edge-Cache-Tag',
            value: 'my custom header value',
          }
        ],
      },
       {
        source: '/(name-)',
        headers: [
          {
            key: 'Edge-Cache-Tag',
            value: 'peivarer value',
          }
        ],
      },
    ]
  },
}

But I want if a request starting from name- then it adds peivarer value in Edge-Cache-Tag .That is not working.

in documentation it is written To match a regex path you can wrap the regex in parenthesis after a parameter, for example /blog/:slug(\d{1,}) will match /blog/123 but not /blog/abc:

enter image description here here is my code https://repl.it/@naveennsit/KindlySomberCleaninstall#next.config.js

2 Answers

I don't use that framework, but my understanding of regex is that you need to match beginnings with ^... so in this case ^name

Following the example of the docs, this config works:

module.exports = {
  async headers() {
    return [
      {
        source: "/about.css",
        headers: [
          {
            key: "Edge-Cache-Tag",
            value: "my custom header value",
          },
        ],
      },
      {
        source: "/:slug(name-[a-zA-Z0-9]*\\.css)",
        headers: [
          {
            key: "Edge-Cache-Tag",
            value: "peivarer value",
          },
        ],
      },
    ];
  },
};

The regex will allow name- followed by any character or number, followed by .css.

Related