Skip to content

Next Link clears cookies when used inside layout #14444

Open
@kolodi

Description

@kolodi

Before opening, please confirm:

JavaScript Framework

Next.js

Amplify Version

v6

Amplify Categories

hosting

Backend

Amplify Gen 2

Describe the bug

I have cookies set like this

cookies.set(COOKIE_SESSION_KEY, sessionId, {
  secure: true,
  httpOnly: true,
  sameSite: "lax",
  expires: Date.now() + SESSION_EXPIRATION_SECONDS * 1000,
})

Inside layout I have a header with a bunch of links, they are created dynamically based on logged in user.
Cookies are being emptied once you load the page. If I have those links inside a client component that is initially hidden (not rendered), once I open a menu containing them cookies are emptied at that exact moment. This is a huge problem, my middleware redirects user to the login page as there are no more cookies, use is basically logged out.

This happen only if I have links inside layout, putting them on pages works without issues.

I think bug happen because Link tries to prrefetch pages it is pointing to but I do not know the exact mechanism of how it is working under the hood.

Expected behavior

Cookies remain despite having Link inside layout.

Reproduction steps

  1. Create nextjs app
  2. Set cookies httpOnly, secure, lax (in my case it set after login, but any server action can do)
  3. create layout and a page
  4. in layout get cookies and have async components receiving some data and rendering next/link
  5. have same in a regular page
  6. observe cookies being emptied upon navigation to the page with layout having links

Additional information and screenshots

As a workaround, I use regular 'a' tag instead of nextjs Link.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions