#why using redirect() in server action causes the page it redirects to not have cookies?

1 messages · Page 1 of 1 (latest)

upper goblet
#

why using redirect() in server action causes the page it redirects to not have cookies?

prime gorgeBOT
#

Hi @upper goblet. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The behavior you're experiencing might be related to the way Next.js handles cookies and redirects. When you set a cookie in a server action and then use redirect(), the cookie might not be immediately available in the redirected page. This is because the Set-Cookie header won't be accounted for during the rendering of the page. This behavior is documented in a Github issue (https://github.com/vercel/next.js/issues/52799).

In a server action, you can set cookies using the cookies().set method as shown in the Next.js documentation (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions#using-headers). However, if you need to access the cookie in the same request flow, you might need to share state between middleware and the server component using something like unstable_cache(), redis, memcached, etc. Alternatively, you could split the job into two requests with a redirect, as suggested in this Github comment (https://github.com/vercel/next.js/issues/49442).

Here's an example of how you might set a cookie and then redirect:

// middleware.ts
export default async function (req: NextRequest) {
  if (needsToAddACookie) {
    const response = NextResponse.redirect(req.nextUrl.clone()); // <- redirect back to same url
    response.cookies.set({
      name: "something",
      value: "important",
      maxAge: 100,
    });
    return response;
  }
}

And then access the cookie in the page:

// page.tsx
export default function MyPage() {
  const somethingImportant = cookies().get('something')?.value;
}
#

Please note that this is a workaround and might not be suitable for all use cases. If you're experiencing issues with this, it might be worth raising an issue in the Next.js Github repository.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@upper goblet kapa.ai is still learning and improving, please let us know how it did by reacting below