In my last post, we looked at how OAuth 2.0 works and examined how to generate access tokens and refresh tokens. Now we’re diving into how to store tokens in your front-end.

Access tokens are usually short-lived JWT Tokens that are signed by your server and are included in every HTTP request to your server to authorize the request. Refresh tokens are usually long-lived opaque strings that are stored in your database and used to get a new access token when it expires.

Where should I store my tokens in the front-end?

There are two common ways to store your tokens. The first is in localStorage and the second is in cookies. There is a lot of debate over which one is better with most people leaning toward cookies as they are more secure.

Let’s go over the comparison between localStorage and cookies. This article is mainly based on  this article and the comments on this post.

Local Storage

Pros: It’s convenient.

  • It’s pure JavaScript and it’s convenient. If you don’t have a back-end and you’re relying on a third-party API, you can’t always ask the third-party API to set a specific cookie for your site.
  • Works with APIs that require you to put your access token in the header, like this: Authorization Bearer ${access_token}.

#cookies #web-development #javascript

LocalStorage vs. Cookies: All You Need to Know About Storing JWT Tokens Securely in the Front-End
4.10 GEEK