While finding a way to capture JWT tokens for a recent project I was working on, I was looking for a way to save the JWT token I was getting in my return promise of my authorization fetch. This lead me down a path of doing research and stumbling across a possible solution to my problem: localStorage. So what is localStorage you ask? Let me tell you.
LocalStorage is a read only property of your DOM’s origin, or the scheme (protocol), host (domain), and port of the URL used to access it. You are able to assign Storage objects places in your DOM’s memory. LocalStorage is very similar to sessionStorage but there is a key difference. While sessionStorage resets every time you leave the page, localStorage has no expiration date. This makes it possible to add functionality like auto-login and persisting a user’s login across multiple sessions.
Saving objects to localStorage is easy. Take a look at the following example:
Here we have a simple POST request to our authorization url for our website. Once we successfully access the user’s information, we are receiving in return a JWT token as a string. We are then taking that string and assigning it to a place in localStorage as an object identified as “token” . When assigning Objects in localStorage, the keys and the values are always in the UTF-16
DOMString format, which uses two bytes per character. As with objects, integer keys are automatically converted to strings.
So now that we have some values stored in localStorage what are we actually able to do with them? The following are a list of methods that you are able to use when calling on localStorage:
- setItem(key of type string, value of type string): sets a value to the given string identifier that allows you to access the data later on.
- getItem(key of type string): grabs the value you stored perviously, will always be a string so if you are expecting an integer value or need an integer value don’t forget to parseInt!
- removeItem(key of type string): removes the specified object stored with the given string identifier.
- clear(): Clears ALL objects in localStorage.
- key(some number n): grabs the nth index of localStorage and returns the value of that key.
Overall, localStorage can be a convenient way of storing safely encrypted data that you need to persist on the client side. Use it for things like bearer tokens that make authorization much easier to implement!