How to Write a Cookie-less Session Library for JavaScript

Share this article

the (JavaScript) Cookie Monster
In my previous post, Cookie-less Session Variables in JavaScript, we discovered how JavaScript session data could be saved to the window.name property. Today, we create a JavaScript library to exploit this property. View the JavaScript session library demonstration page… The code provides three main methods:
  • Session.set(name, object) — store a named session value/object
  • Session.get(name) — retrieve a named session value/object
  • Session.clear() — reset all the session data
Another Session.dump() method returns all the JSON-encoded session data. This would normally be used for debugging purposes only. The JavaScript code is loaded just before the closing body tag. First, we load the JSON library:

<script type="text/javascript" src="json-serialization.js"></script>
The JSON library provides cross-browser serialization methods that are required by our Session library. For more information, refer to Cross-browser JSON Serialization in JavaScript. The session.js file is loaded next. This is stand-alone code that can be implemented in any system — it does not depend on jQuery or any other JavaScript library. Working through the code:

 if (JSON && JSON.stringify && JSON.parse) var Session = Session || (function() {

	// window object
	var win = window.top || window;

	// session store
	var store = (win.name ? JSON.parse(win.name) : {});
The first line defines our Session module. However, it will only be defined if the JSON library has been loaded and there are no other conflicting Session variables or functions. The second line sets win to ‘window.top’. It is set to ‘window’ if that is not available (perhaps if the browser does not support frames). Next, we define a ‘store’ object to hold all our session data. Exisiting JSON-encoded data in the window.name property is parsed but, if that is not available, ‘store’ is set to an empty object.

	// save store on page unload
	function Save() {
		win.name = JSON.stringify(store);
	};

	// page unload event
	if (window.addEventListener) window.addEventListener("unload", Save, false);
	else if (window.attachEvent) window.attachEvent("onunload", Save);
	else window.onunload = Save;
The private Save() function assigns the serialized the ‘store’ object string to the window .name property. The following three lines define a cross-browser event which calls the Save function when the page is unloaded. Your pages can therefore modify the ‘store’ as much as necessary, but the heavy work of serializing and saving only occurs at the last possible moment.

	// public methods
	return {

		// set a session variable
		set: function(name, value) {
			store[name] = value;
		},

		// get a session value
		get: function(name) {
			return (store[name] ? store[name] : undefined);
		},

		// clear session
		clear: function() { store = {}; },

		// dump session data
		dump: function() { return JSON.stringify(store); }

	};

 })();
Finally, we have our four public set, get, clear and dump functions which handle the store object accordingly. The Session.get() method will return a JavaScript ‘undefined’ value if a session name can not be found. I hope you find the code useful. Feel free to use it in your own projects. Useful resources:
See also:

Frequently Asked Questions (FAQs) about JavaScript Session Variable Library

How can I access session variables in JavaScript?

Accessing session variables in JavaScript can be done using the sessionStorage object. This object allows you to store data for one session. The data is deleted when the user closes the specific browser tab. Here’s an example of how to use it:

// Store data
sessionStorage.setItem("key", "value");

// Get data
var data = sessionStorage.getItem("key");
In this example, “key” is the name of the data, and “value” is the data itself. You can replace these with any values you want.

How can I set session variables in JavaScript?

Setting session variables in JavaScript is similar to accessing them. You use the sessionStorage object’s setItem method. Here’s an example:

// Store data
sessionStorage.setItem("username", "John Doe");
In this example, “username” is the name of the data, and “John Doe” is the data itself. You can replace these with any values you want.

What is the difference between localStorage and sessionStorage in JavaScript?

Both localStorage and sessionStorage are part of the web storage API and allow you to store data in a user’s web browser. The main difference between them is the lifespan of the data. Data stored using localStorage persists even when the browser is closed and reopened, while data stored using sessionStorage is deleted when the page session ends (i.e., when the browser tab is closed).

Can I store objects or arrays in sessionStorage?

Yes, you can store objects or arrays in sessionStorage, but they need to be converted to strings first using the JSON.stringify method. When you retrieve the data, you can convert it back to an object or array using the JSON.parse method. Here’s an example:

// Store an object
var obj = {name: "John", age: 30};
sessionStorage.setItem("user", JSON.stringify(obj));

// Get the object
var user = JSON.parse(sessionStorage.getItem("user"));

Is it possible to clear all data from sessionStorage?

Yes, you can clear all data from sessionStorage using the clear method. Here’s how to do it:

// Clear all data
sessionStorage.clear();
This will remove all data stored in sessionStorage for the current domain.

How secure is sessionStorage?

sessionStorage is secure in the sense that the data is only accessible from the same domain that it was stored from. However, it’s not encrypted, so it’s not recommended to store sensitive information like passwords or credit card numbers in sessionStorage.

Can I use sessionStorage in all browsers?

sessionStorage is supported in all modern browsers, including Chrome, Firefox, Safari, Opera, and Internet Explorer 8 and above. However, it’s always a good idea to check the user’s browser support before using it.

How much data can I store in sessionStorage?

Most browsers allow you to store between 5MB and 10MB of data in sessionStorage. However, this limit can vary depending on the browser and the user’s settings.

Can I use sessionStorage with cookies?

Yes, you can use sessionStorage with cookies. However, they serve different purposes. Cookies are primarily for reading server-side, while sessionStorage and localStorage can only be read on the client-side. So, the data stored in sessionStorage and localStorage can’t be read by the server.

What happens to sessionStorage data when the browser crashes?

If the browser crashes or the system shuts down unexpectedly, the data in sessionStorage is lost. This is because sessionStorage is designed to be a temporary storage solution for one session only. If you need to store data persistently, consider using localStorage or a server-side database.

Craig BucklerCraig Buckler
View Author

Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week