next/link causes cookies to be deleted when used in layout
Unanswered
Bull Terrier posted this in #help-forum
Bull TerrierOP
Hi,
I'm using
After the user logs in, they are redirected to a dynamic "home" page. The layout (including the header) contains Links to other dynamic, protected pages.
The issue:
Cookies are being deleted automatically upon loading the "home" page, and when the user clicks on one of those links the middleware is set up to redirect them back to the login page, since no cookies = no authenticated user.
I suspect this happens because Next.js tries to prefetch those dynamic pages, and something goes wrong during that process. In fact, if the links to those protected pages are initially hidden—say, inside a client component that only renders later—the cookies stay intact until that part of the UI is shown and the links are rendered. At that moment, I can see the cookies being deleted.
Workaround:
For now, I've replaced all Links in the layout with regular
I don’t know the internal workings of Link in detail, so my question is:
Is this expected behavior, or could it be a bug?
I'm using
Link
from next/link
for navigation inside my header, which is part of a shared layout since I need the header on every page. Everything works fine on static pages.After the user logs in, they are redirected to a dynamic "home" page. The layout (including the header) contains Links to other dynamic, protected pages.
The issue:
Cookies are being deleted automatically upon loading the "home" page, and when the user clicks on one of those links the middleware is set up to redirect them back to the login page, since no cookies = no authenticated user.
I suspect this happens because Next.js tries to prefetch those dynamic pages, and something goes wrong during that process. In fact, if the links to those protected pages are initially hidden—say, inside a client component that only renders later—the cookies stay intact until that part of the UI is shown and the links are rendered. At that moment, I can see the cookies being deleted.
Workaround:
For now, I've replaced all Links in the layout with regular
<a>
tags, and the issue disappears—cookies are no longer removed. I still use Link inside individual pages (even for protected routes), and it works fine there. The issue seems to happen only when Link is used in the layout.I don’t know the internal workings of Link in detail, so my question is:
Is this expected behavior, or could it be a bug?
1 Reply
Bull TerrierOP
Oh, I should specify that this happens only for a deployed application. Locally, it works just fine. So it might be due to specific implementation on the hosting. I use Amplify hosting (AWS). I have already posted an issue on their repo: https://github.com/aws-amplify/amplify-js/issues/14444