0

I was working on server-side redirection in react.

Inside getInitalProps i had done something like this

const { res } = ctx

if(some condtion === true){
    redirection
    res.writeHead(301, {
      Location: 'new/url/destination/here'
    });
    res.end();
}

It worked but the thing is I'm not able to go to this page again even though the condition is false.

I removed the entire block but was still not able to go to this page. Tried restarting the server but no use. Help needed

i followed solution as per this but used 301 instead of 302 Conditional redirection in Next.js

Thanks in advance.

  • You want an equality (`==`) or identity (`===`) operator for comparisons. Alternatively, since it's a boolean, you can omit the comparison. `if (some_condition === true)` or just `if (some_condition)` – Nick Jul 16 '21 at 12:03
  • @Nick yep it was a comparison operator. Updated my question pls check – Vijay Thomas Jul 16 '21 at 12:06
  • 1
    @VijayThomas Have you tried using `getServerSideProps` instead? It is working for me: https://codesandbox.io/s/agitated-tdd-22qu2 -- only `/contact` is being redirected to `/about` in this example, and all other routes except base are resulting in 404. Also if your condition is just some pattern matching then you can do: https://nextjs.org/docs/api-reference/next.config.js/redirects – brc-dd Jul 16 '21 at 13:31
  • @brc-dd now i have removed the complete code releated to url but still im not able to go to that page. – Vijay Thomas Jul 16 '21 at 13:59

1 Answers1

1

Status Code 301 is used if the site is moved permanently to the given address. That means your application likely cached the URL it received when the condition was fulfilled.

On consequent requests it just uses that cached address without checking for your condition again. I don't know why you changed that status code from the example you linked, but switching it back to 302 (Moved temporarily) should resolve your issue after emptying the cache of your next-server.