#Delete cookies when user exits the page

1 messages · Page 1 of 1 (latest)

gentle spade
#

`"use server";

import { cookies } from "next/headers";
import { redirect } from "next/navigation";

interface ILoginUserAction {
access: string;
refresh: string;
}

export async function cookieSetter({ access, refresh }: ILoginUserAction) {
cookies().set("Authorization", access, {
httpOnly: true,
secure: true,
});
cookies().set("Refresh", refresh, {
httpOnly: true,
secure: true,
});
redirect("/admin/dashboard")
}
`

This is a server action which login's the user. I want to delete this cookies when the user exits the page. How to do it ?

sullen schoonerBOT
#

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

#

To delete cookies when a user exits the page, you can use the cookies().delete(name) method provided by the Next.js cookies API. This method allows you to delete a cookie with a given name.

Here's how you can modify your cookieSetter function to delete the cookies:

export async function cookieSetter({ access, refresh }: ILoginUserAction) {
  // Set cookies
  cookies().set("Authorization", access, {
    httpOnly: true,
    secure: true,
  });
  cookies().set("Refresh", refresh, {
    httpOnly: true,
    secure: true,
  });

  // Redirect to dashboard
  redirect("/admin/dashboard");

  // Delete cookies when user exits the page
  // Note: This is a simplified example and may not work as expected. 
  // You might need to listen for the page unload event and then delete the cookies.
  if (typeof window !== 'undefined') {
    window.addEventListener('beforeunload', (event) => {
      cookies().delete('Authorization');
      cookies().delete('Refresh');
    });
  }
}

Please note that this is a simplified example and may not work as expected. You might need to listen for the page unload event and then delete the cookies. Also, keep in mind that you can only delete cookies in a Server Action or Route Handler, and you can only delete cookies that belong to the same domain from which .set() is called. The code must be executed on the same protocol (HTTP or HTTPS) as the cookie you want to delete.

For more information, you can refer to the following sources:


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