Next.js Discord

Discord Forum

Page Reload on Setting Cookies using cookies()

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
### Issue Summary: Page Reload on Setting Cookies

## Context:
- On the email verification page, using the cookies() function to set cookies causes the page to reload.

## Problem:
- The page reload interrupts the state, leading to conditionally rendered components not displaying as expected.

## Impact:
- This results in a disrupted user experience, with components either disappearing or not rendering correctly after the reload.

## Desired Outcome:
- Set cookies without triggering a page reload.
- Ensure that application state and conditional components remain intact.


## Server Action:
export async function verifyEmail({
  id,
  token,
}: {
  id: string;
  token: string;
}) {
  const res = await fetch(`${API_URL}/auth/credentials/verify/${id}/${token}`, {
    method: RequestMethod.Post,
    credentials: "include",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ id, token }),
  });

  if (!res.ok) {
    const error: Error = await res.json();
    throw new Error(error.message);
  }
  const cookieRaw = res.headers.get("set-cookie");
  const cookie = parseCookie(cookieRaw as string);
  const expiresAt = new Date(Date.now() + 60000 * 2);

  cookies().set("connect.sid", cookie["connect.sid"] as string, {
    expires: expiresAt,
    path: "/",
  });

  revalidateTag("user");

  return;
}

19 Replies

@Polar bear
Just don't update the page then
The thing is when you update cookies and revalidate tag in nextjs in a server action, nextjs will rerender since you are asking it to update.

What you can do is just not revalidate tag, that's gonna only update cookies and not rerender your screen
@Polar bear ### Issue Summary: Page Reload on Setting Cookies ## **Context**: - On the email verification page, using the `cookies()` function to set cookies causes the page to reload. ## **Problem**: - The page reload interrupts the state, leading to conditionally rendered components not displaying as expected. ## **Impact**: - This results in a disrupted user experience, with components either disappearing or not rendering correctly after the reload. ## **Desired Outcome**: - Set cookies without triggering a page reload. - Ensure that application state and conditional components remain intact. ## **Server Action**: tsx export async function verifyEmail({ id, token, }: { id: string; token: string; }) { const res = await fetch(`${API_URL}/auth/credentials/verify/${id}/${token}`, { method: RequestMethod.Post, credentials: "include", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ id, token }), }); if (!res.ok) { const error: Error = await res.json(); throw new Error(error.message); } const cookieRaw = res.headers.get("set-cookie"); const cookie = parseCookie(cookieRaw as string); const expiresAt = new Date(Date.now() + 60000 * 2); cookies().set("connect.sid", cookie["connect.sid"] as string, { expires: expiresAt, path: "/", }); revalidateTag("user"); return; }
That what Arinji said.
You can also remove this reload behavior when you set the cookie directly (but with an invalid or missing value) and then update the cookie. Then no reload is triggered, even if you use it somewhere on your page
@Polar bear How can I do that? removing revalidateTag didn't solve the issue
you can do that by directly setting the cookie (but with an invalid or missing value) and then only update the cookie later (instead of setting them later).
Polar bearOP
I need an example please
wait... my bad. I was confused. That's not a possible solution. However. Only setting a cookie will trigger a reload. Deleting an cookie for example won't trigger a reload
Polar bearOP
The issue here that I'm triggering animation after server action but setting cookie will relaod the page
I don't know how can I solve it
Polar bearOP
I tried removing cookies().set and tried removing revalidateTag and I discovered that both revalidateTag and cookies().set reload the page
so removing one of them will also reload the page
yea, revalidateTag also updates your page. Like Arinji said
...don't update the page...
Polar bearOP
Then what should I do
I think revalidateTag is more suitable for requests which don't manipulate with cookies
because either delete or set cookie refreshes the page
Anyone agrees with me?
Polar bearOP
I have a simple test did and I want someone checks it and tell me If I'm wrong:
export async function signout() {
  const c = cookies();
  const res = await fetch(`${API_URL}/auth/credentials/signout`, {
    method: RequestMethod.Get,
    credentials: "include",
    signal: AbortSignal.timeout(10000),
    headers: {
      Cookie: c.toString(),
      "Content-Type": "application/json",
    },
  });
  if (res.ok) {
    cookies().delete("connect.sid"); // Page is reloaded > Layout User Fetch > User is cached;
    revalidateTag("user") // User is refetched > User is recached so revalidateTag here is useless isn't it?
    redirect("/");
  }
}