JavaScript: how to save a JSON Web Token (JWT) and use it with the Fetch API

JavaScript: how to save a JSON Web Token (JWT) and use it with the Fetch API

In this article we will see how to save a JSON Web Token (JWT) and use it with the JavaScript Fetch API.

In this article we will see how to save a JSON Web Token (JWT) and use it with the JavaScript Fetch API.

Cookies

Saving a JWT in a cookie is relatively simple. First, you need to retrieve the token and place it inside a cookie. There are several JavaScript libraries available to help do this. For example, the js-cookie library is one of the most popular and allows you to easily save a value in a cookie:


import Cookies from 'js-cookie';

const jwt = 'my-json-web-token';
Cookies.set('jwt', jwt);

Once the JWT is saved in a cookie, we can use it to authenticate to our APIs using the JavaScript Fetch API. Typically, we should send the JWT as an authorization header with every request to our APIs:


import Cookies from 'js-cookie';

const jwt = Cookies.get('jwt');

fetch('https://my-api.com/data', {
  headers: {
    'Authorization': `Bearer ${jwt}`
  }
})

In this example, we fetch the JWT from the cookie using the js-cookie library and use it as an authorization header with the JavaScript Fetch API. This allows us to authenticate with our API and receive the requested data.

Web Storage

To save for example a JWT in localStorage, you can use the following JavaScript code:


localStorage.setItem('jwtToken', jwt);

where jwtToken is the name of the key used to store the token in the localStorage and jwt is the value of the token.

Once the token is saved, it can be used in HTTP requests via the JavaScript Fetch API. To do this, you need to retrieve the token from the localStorage and add it to the Authorization header of the request. The following code illustrates how to do this:


'use strict';

const jwt = localStorage.getItem('jwtToken');

fetch('https://my-api.com/data', {
  headers: {
    'Authorization': `Bearer ${jwt}`
  }
});

In this example, the token is retrieved from the localStorage using the getItem() method. Next, the token is added to the Authorization header of the request using the prefix Bearer.