5

I am using Next.js and I am trying to redirect to a given path base on some regex conditions and cookie.

The goal is to redirect to /foo/bar when the source does not have the key bar and have a given cookie.

I have tried several different ways with next.config.js and none works.

Right now I have the following

async redirects() {
    return [
      {
        source: '/(^(?:(?!bar).)*$)',
        has: [{
          type: 'cookie',
          key: 'utm_source',
          value: 'bar',

        }],
        destination: '/foo/bar',
        permanent: true
      }
    ]
  }

The documentation is quite vague.

3
  • 3
    have you checked this out ? github.com/vercel/next.js/issues/15712 Commented Oct 10, 2021 at 19:22
  • I never gave it the attention i gave now. Yes it solves the problem, but it's too verbose. I would like to specify only a word that should not be in the source. I dont't care about the path. But thank you, worst case scenario i have this. Commented Oct 10, 2021 at 19:58
  • You can for sure, but i think (hope) there is another answer. Commented Oct 10, 2021 at 21:54

2 Answers 2

9

I also had a regex issue and was digging deep into next.js source code and did a little debugging. What I found is that unfortunately nobody tells you that next.js wraps your regex inside /^(?:\/( your regex ))$/i

Actually, the first part (\/) might depend on your source property. But if you remove everything apart from the actual "word regex" it should work:

source: '/(?!bar)',

(Check out regexp.source in getPathMatch() in node_modules\next\dist\shared\lib\router\utils\path-match.js)

Sign up to request clarification or add additional context in comments.

Comments

2

Next.js started using the path-to-regexp library for matching the routes. The project's README has more examples and a link to the testing tool: http://forbeslindesay.github.io/express-route-tester/

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.