Ending a Session Using JWT Token

Joseph Patterson
3 min readMar 28, 2021

No Chill Sesh?

My latest Ruby on Rails project brought me back to the confusing world of the session. Sessions always gave me a slight headache. There is a ton of reference material online but there never seemed a definitive way to start and end a session using JWT authentication that seemed satisfying. Today we are going to look at why sessions can be confusing and a solution that may work for you.

Code is in Session

Storing session data using a JWT (JSON Web Tokens) token is way to handle the information without requiring any hits to the database. When a user logs in, a JWT auth token is assigned containing data we can use to track the session. We then use the token to make requests and authenticate whether the user has access to whatever features they are trying to use. Handling all of this out of state is lightweight but it can also come with its share of difficulties. It is easy enough to issue an auth token but it isn’t as simple as logging out and quitting the session. Whenever a token is created, it can be used forever or until it expires. The JWT generator can get an option to invalidate the token after a specified time.

Expiring a JWT

One of the more illuminating examples of expiring a JWT actually comes from a developer friend of mine. I was trying to figure out the best way to timeout and he showed me this example he had come up. Here is a link to the gitcode

Here we can see a pretty straightforward approach. The setAuthToken (line 14) function is exported to a button component which is analogous to a login button.

App.js

Back to the auth function, we can see that onClick generates the auth-token using the localStorage.setItem command and also captures the time it was created. This time is important as it will be integral in establishing how long we want our JWT to be valid.

Two variables are declared that establish how long in between checks for expiration ( const INTERVAL) and how long we want the token to last for (const TIMEOUT). A function, checkTime, is declared which looks at the current time minus the auth-token-set-time value and compares it to the TIMEOUT. If it is greater than or equal to our TIMEOUT variable, it will remove the token from local storage and we will no longer have it.

The last step is to call setInterval() which is a built in function that will take two args (a callback, and the interval in milliseconds).

NOTE: setInterval() will run forever. To stop it you must run clearInterval() or close the window.

Takeaway

This might not be the most efficient method for your needs but I think it is a great illustration of the flow necessary to expire your JWT. It helped me to wrap my head around a problem that has given me plenty of issues in the past. After seeing this I implemented something similar into my app and it works like a charm. Hopefully it is as illuminating for you as it was for me.

Happy Coding!

--

--