I have an app with two pages; index / and login /login. I should redirect the visitors from / to /login page if they're not logged in(I check this using a simple token cookie). For the redirection, I'm using getServerSideProps like this:
const authenticate = async context => {
const { token } = nextCookies(context);
console.log(token ? '✅ Token Found' : '❌Token Not Foond')
if (!token) {
console.log('🏠Redirecting to login')
context.res.setHeader('location', '/login');
context.res.statusCode = 302;
context.res.end();
return { props: {} };
}
return {
props: {
token,
},
};
};
But, it seems like next-pwa is caching 302 redirects when I reload the index / page(Even when I'm logged in, and token exists, it redirects me to /login page). I noticed that this issue only appears on the production bundle. Please pay attention to reproduced GIF I provided down below:
Here's the reproduced repo. Steps to reproduce the behavior:
npm run build and run it using npm start./login page(expected behavior)/, and it will redirect you to /login page(expected behavior. This step is important and it's causing the bug)/login page. You will be sent to / page/ page/login!(This is not expected)Redirection should not be cached when changing the URL manually.

Changing the URL manually is somehow causing this error. The interesting thing is that if you change the URL to / again after the step 5, and then reload the page, it wouldn't redirect you wrongly again! I'm using this config:
const withPWA = require('next-pwa');
module.exports = withPWA({
pwa: {
dest: 'public',
precacheHomePage: false,
additionalManifestEntries: [],
},
pageExtensions: ['page.js'],
});
@Kiarash-Z and @LucasMallmann, please see my fix at this PR.
https://github.com/Kiarash-Z/next-pwa-redirect-bug/pull/1
@shadowwalker Thank you! this fixes the issue! For anyone referencing this later, as the PR suggests, you need to set others cache in `toNetworkFirstinnext.config.js`:
module.exports = withPWA({
...
pwa: {
...
runtimeCaching: [
{
urlPattern: /.*/i,
handler: 'NetworkFirst', // ✅
options: {
cacheName: 'others',
expiration: {
maxEntries: 16,
maxAgeSeconds: 24 * 60 * 60,
},
},
},
]
}
})
Most helpful comment
@Kiarash-Z and @LucasMallmann, please see my fix at this PR.
https://github.com/Kiarash-Z/next-pwa-redirect-bug/pull/1