JavaScript method to clear browser session data and cookies

I’m working on a web application and need to figure out how to remove stored session data from the user’s browser using JavaScript. I want to clear all the cookie information when someone logs out of my site. I’ve been searching around but I’m not sure if this is even possible to do with client-side JavaScript. Can anyone tell me if there’s a way to accomplish this? I need to make sure that when users click the logout button, all their session cookies get removed properly.

Here’s what I’m currently trying:

function clearUserSession() {
    // Not sure what goes here
    console.log('Attempting to clear session data');
}

clearUserSession();

Any help would be really appreciated. Thanks!

Your authentication setup makes a huge difference here. I’ve run into cases where just clearing client-side data doesn’t work because the server keeps the session alive. What fixed it for me was doing both - clean up the client side AND hit a proper logout API that kills the server session. Also heads up, browsers handle cookie clearing differently, especially with SameSite stuff. Safari gave me headaches with certain path configs. I’d set up a server logout endpoint that sends back headers to clear the important cookies, then handle client storage cleanup after that.

totally get it! for cookies, set them to a past date like this: document.cookie = "cookiename=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;". for session storage, sessionStorage.clear() is ur friend! just remember, httpOnly cookies can’t b touched by js.

You’ll need to handle cookies and browser storage separately. There’s no built-in way to clear all cookies at once, so you have to iterate through them. Here’s what I use:

function clearUserSession() {
    // Clear all cookies
    document.cookie.split(";").forEach(function(c) {
        const eqPos = c.indexOf("=");
        const name = eqPos > -1 ? c.substr(0, eqPos) : c;
        document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/";
    });
    
    // Clear storage
    sessionStorage.clear();
    localStorage.clear();
}

This only works for cookies JavaScript can access. If your server sets httpOnly cookies for auth, handle those server-side during logout. Don’t forget localStorage if you’re storing user data there.