Maintaining session info in AngularJS when you refresh the page

EDIT: This article has proved to be the most popular article on my site, but I thought it was a bit “rambly” and also the code examples were out of date. So this is the March 2016 Remix with added super powers! P.S. I’m using Angular v1.4.6 for the code examples. P.P.S. Some of the comments may seem a little odd, but that’s probably because they’re referring to the original article.

The main problem we have when building Angular sites, is that any client-side data is lost when we hit the F5 button. This data usually consists of a way to identify the user when they make API calls (e.g. an authentication token) or user metadata such as name, signed-in status etc. Short of writing some crazy code to disable the F5 keypress (or the “Ctrl+R” keypress, or clicking on the Reload icon etc.) we need a way to persist that data on the client when our page is refreshed.

For a recent project I worked on, I store this data in cookies. You could just as easily store this data in your browser’s Local Storage as I have done when building Phonegap Apps, but this example will walk you through using cookies to store and retrieve local data.

ngCookies

Angular rather conveniently has a module called ngCookies which allows you to interact with cookies, and it’s REALLY simple to use!

You can write stuff to a cookie like this:

$cookies.put("username", "Maff");

You can read stuff from a cookie like this:

var username = $cookies.get("username");

and remove stuff from a cookie like this:

$cookies.remove("username");

Using ngCookies in your application

To use the ngCookies module in your application, the first thing you need to do is inject the ngCookies module in your Angular application (Psst – don’t forget to reference the angular-cookies.min.js file in your markup!):

var ngApp = angular.module("myApp", ["ngCookies"]);

Next you need to create a Service to manage the writing and reading from your cookies. You could in theory put this in your controller, but putting it in a service means you’re separating your logic out from your controller and you’re creating reusable code that all controllers can use. They’re both good things, right?

So – create a Service and inject the ngCookies module into it:

ngApp.factory("userPersistenceService", ["$cookies", function($cookies) {
	//your service code goes here
	}
]);

Notice I’ve called this Service “userPersistenceService” and not just “cookiesService” – because there’s more happening in here than just reading and writing to cookies. For example I’m storing an API token in a cookie when a user signs in, so I can use this service to check that the token exists, and redirect the user to a sign in page if it doesn’t.

There are now 3 key functions you want to add to your service – setCookieData, getCookieData and clearCookieData. Here’s a simplified version of how the service would look:

ngApp.factory("userPersistenceService", [
	"$cookies", function($cookies) {
		var userName = "";

		return {
			setCookieData: function(username) {
				userName = username;
				$cookies.put("userName", username);
			},
			getCookieData: function() {
				userName = $cookies.get("userName");
				return userName;
			},
			clearCookieData: function() {
				userName = "";
				$cookies.remove("userName");
			}
		}
	}
]);

And that’s pretty much all there is to it – you can add more functionality into your service, but the key elements I’ve highlighted above allow you to store, retrieve and clear session data from your cookies.

Enjoy!

Tagged with: , , , , , ,