Cookies, Session Storage and Local Storage

Cookies, Session Storage and Local Storage

When building web applications, managing data on the client side is essential for tasks such as authentication, user preferences, and state management. JavaScript provides several mechanisms for storing data on the client side: Cookies, Session Storage, and Local Storage. Each has its own strengths and use cases. This article will explore these options, including their differences, use cases, and how to implement them with code examples in JavaScript.

Cookies

Cookies are small pieces of data sent from a website and stored on the user's browser. They are used to remember stateful information for the stateless HTTP protocol, such as authentication tokens, user preferences, or tracking data. Cookies can be set to expire at a specific time or last only for the duration of the session.

Properties:

  • Size Limit: Approximately 4KB per cookie.

  • Expiration: Can be set to expire after a specific time or last only for the session.

  • Scope: Cookies can be accessed server-side (via HTTP headers) or client-side (via JavaScript).

  • Security: Can be marked as HttpOnly (not accessible via JavaScript), Secure (only transmitted over HTTPS), and SameSite (restricts cross-site sharing).

Code Example:

// Setting a cookie
document.cookie = "username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/";

//The path attribute in a cookie defines the URL path that must exist 
// in the requested resource before the browser sends the cookie header. 
// Here, the path=/ specifies that the cookie will be sent in all requests made to the domain (for example, example.com) and all its sub-paths. It means that the cookie is accessible throughout
// the entire website, regardless of the specific page or route.
// If you set path=/somepath, then the cookie would only be sent for requests to URLs 
//that match /somepath and below, like /somepath/subpage.

// Reading a cookie
const cookies = document.cookie.split('; ');
const username = cookies.find(row => row.startsWith('username=')).split('=')[1];
console.log(username); // Output: JohnDoe

// Deleting a cookie
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";

Session Storage

Session Storage is a storage mechanism that allows you to store data for the duration of the page session. This means that the data is available only as long as the browser window or tab is open. Once the tab or window is closed, the data is lost.

Properties:

  • Size Limit: Approximately 5-10MB depending on the browser.

  • Expiration: Data is cleared when the page session ends (i.e., the tab or window is closed).

  • Scope: Data is available only within the same tab or window.

  • Security: Data is accessible only through JavaScript in the same origin.

Code Example:

// Setting an item in session storage
sessionStorage.setItem('sessionUsername', 'JaneDoe');

// Retrieving an item from session storage
const sessionUsername = sessionStorage.getItem('sessionUsername');
console.log(sessionUsername); // Output: JaneDoe

// Removing an item from session storage
sessionStorage.removeItem('sessionUsername');

// Clearing all items from session storage
sessionStorage.clear();

Local Storage

Local Storage is similar to Session Storage, but the data persists even after the browser window is closed. It is ideal for storing data that should remain available even after the user closes and reopens the browser.

Properties:

  • Size Limit: Approximately 5-10MB depending on the browser.

  • Expiration: Data does not expire and remains available until explicitly deleted.

  • Scope: Data is accessible across all tabs and windows in the same origin.

  • Security: Data is accessible only through JavaScript in the same origin.

Code Example:

// Setting an item in local storage
localStorage.setItem('localUsername', 'JohnSmith');

// Retrieving an item from local storage
const localUsername = localStorage.getItem('localUsername');
console.log(localUsername); // Output: JohnSmith

// Removing an item from local storage
localStorage.removeItem('localUsername');

// Clearing all items from local storage
localStorage.clear();

Key Differences

FeatureCookiesSession StorageLocal Storage
Size Limit~4KB per cookie5-10MB per origin5-10MB per origin
ExpirationConfigurable (session or longer)On tab/window closePersistent until deleted
AccessibilityServer-side and client-sideClient-side onlyClient-side only
ScopeAll tabs/windows in the same originSingle tab/window per originAll tabs/windows in the same origin
Use CasesAuthentication, user preferences, trackingTemporary state for a sessionLong-term user settings, state persistence

What should I use for saving jwt token on client side cookie or session storage or local storage?

  • Cookies (with HttpOnly, Secure, and SameSite flags) are usually the best option when security is critical, especially in server-side rendered (SSR) apps or any scenario requiring secure authentication.

  • If you're building a Single Page Application (SPA) and security is not the highest priority, localStorage is more convenient but has some risks (especially from XSS).

  • sessionStorage is good for temporary, short-lived tokens but doesn't persist across sessions.

In most cases, cookies with the proper security settings are recommended for secure authentication involving JWTs.

Conclusion

Cookies, Session Storage, and Local Storage are powerful tools in web development for managing client-side data. Cookies are ideal for server-side communication and persistent data across sessions, while Session Storage is perfect for temporary data within a single session. Local Storage is suitable for storing persistent data that needs to remain across sessions.

Understanding when and how to use each of these storage mechanisms will allow you to build more responsive, stateful, and secure web applications.