JavaScript Answers

How to add session-only cookies with JavaScript?

Spread the love

In JavaScript, you cannot directly create session-only cookies because cookies are managed by the browser, and there is no built-in option to specify a session-only cookie using JavaScript alone.

However, you can achieve session-only behavior by setting the expiration time of the cookie to a time in the past, effectively causing the cookie to expire immediately when the session ends.

To create a session-only cookie using JavaScript, we:

// Function to create a session-only cookie
function createSessionCookie(name, value) {
    // Set expiration time to a time in the past
    var expirationDate = new Date(0); // Expired immediately
    document.cookie = name + '=' + encodeURIComponent(value) + ';expires=' + expirationDate.toUTCString() + ';path=/';

// Usage example
createSessionCookie('sessionCookieName', 'sessionCookieValue');

This function sets a cookie with the given name and value, but it sets the expiration time to a time in the past (specifically, January 1, 1970).

As a result, the cookie will expire immediately when the session ends or when the browser is closed, effectively behaving as a session-only cookie.

Keep in mind that setting cookies in JavaScript is subject to the same-origin policy, so we can only set cookies for the domain from which our JavaScript code is being served.

Additionally, setting cookies via JavaScript might be subject to browser settings and restrictions, such as the user’s privacy settings or the browser’s cookie policies.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *