'Next.js redirect if there is no cookie
Is there a way to redirect the user from checkout to the join page ONLY if there is no cookie user_token. Next.js allows to set only strings and undefined as value, but I need to validate that there is no cookie:
redirects: async () => [
{
source: '/checkout',
has: [
{
type: 'cookie',
key: 'user_token',
value: '',
},
],
permanent: true,
destination: '/join',
},
],
I tried to use regex for empty string, but it did not work:
redirects: async () => [
{
source: '/checkout',
has: [
{
type: 'cookie',
key: 'user_token',
value: '(^$)',
},
],
permanent: true,
destination: '/join',
},
],
Solution 1:[1]
I think that the problem you have is, that you just limit it to an empty cookie.
You will have to check for the absence of a cookie inside the route and send a res.redirect from there (https://nextjs.org/docs/api-routes/response-helpers)
And: are you sure you want a permanent redirect?? The browser caches it and those users will be redirected without a request to the server in the future.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cyberbrain |
