Explain Codes LogoExplain Codes Logo

Session only cookies with Javascript

javascript
session-management
cookies
javascript-utility-functions
Nikita BarsukovbyNikita Barsukov·Oct 21, 2024
TLDR

To create a session-only cookie in JavaScript, you simply leave out the expires and max-age attributes:

document.cookie = "sessionKey=yourValue; path=/; secure";

The sessionKey is your cookie's name, yourValue is the data you wish to store, and it lasts until the end of the browser session. The secure attribute ensures that the cookie is sent over HTTPS only.

For a quick and easy client-side session storage solution beyond cookies, try sessionStorage:

sessionStorage.setItem('sessionData', 'yourSessionValue');

sessionData is the item's key, and yourSessionValue is the session's value.

The need for session handling without access to server-side scripts may arise when working with sites purely using HTML. In such situations, sessionStorage provides a ready-made solution for session management.

However, it's important to remember that sessionStorage comes with its limitations. Each sessionStorage is isolated to the tab or window that created it. This means that unlike cookies that persist across all tabs, sessionStorage can't share data across different tabs or windows.

Multidimensional cookies: storing complex data

The JSON.stringify() trick

When you need to store multidimensional data, JSON.stringify() can convert it to a format that sessionStorage can handle:

sessionStorage.setItem('complexData', JSON.stringify({ key: 'value' })); // Notice we've gone INCEPTION mode here. We're storing an object within an object within...you get the point let data = JSON.parse(sessionStorage.getItem('complexData'));

Beware! We're now entering a world that even Leo DiCaprio might find confusing.

Instead of writing document.cookie everywhere, wrapping your code into clear, reusable functions can greatly improve the maintainability of your JavaScript:

function setSessionCookie(name, value) { document.cookie = `${name}=${value}; path=/; secure`; // Order up! One secure cookie, coming right up! } function getSessionCookie(name) { let matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; // The cookie ninja has returned and brought your cookie. Bonus: No extra calories! } function clearSessionCookie(name) { document.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;`; // WHOOSH! And like that, your cookie is gone. }

Utility functions like these are the true "cookie monsters" of your JavaScript files. 🍪

Peculiar paths

A path attribute decides which URLs can receive a cookie. By specifying a path, you're making sure that a cookie is only sent to requests within that path. This improves security and efficiency:

document.cookie = "sessionKey=yourValue; path=/secure; secure";

This is a cookie jar with a secret code. Not all cookies are created equal, so be careful!

Securing your sweet tooth

When setting cookies, remember to use the secure attribute. This ensures that cookies are only sent over secure driver connections, HTTPS:

document.cookie = "sessionKey=yourValue; secure";

Keep your cookies safe from the pesky cookie-thieving elves lurking in the middle!

A frequent mistake is deleting cookies incorrectly, this usually happens when an incorrect path or domain is used:

// Incorrect way, you might not clear the cookie if paths don't match document.cookie = "sessionKey=yourValue; path=/; expires=Thu, 01 Jan 1970 00:00:01 GMT;"; // Correct way document.cookie = "sessionKey=; path=/theCorrectPath; expires=Thu, 01 Jan 1970 00:00:01 GMT;";

Make sure you're correctly matching the cookie name and path for successful deletion. No man, or cookie, left behind!

The Tab Troubles

Opening a new tab or window starts a new session with its own sessionStorage:

// Session storage in the original tab sessionStorage.setItem('data', 'originalTab'); // This won't be accessible in a new tab let newData = sessionStorage.getItem('data'); // returns null

Every tab is a world in itself, the cookies from one tab can't visit another. They're just shy like that.