JWT tokens are a popular form of token-based authentication because they are self-contained and can contain user information. We can use the js-cookie library to store JWT tokens in cookies in React. You should start by installing the library using npm install js-cookie
or yarn add js-cookie
. Once that is done, go ahead and import the Cookie instance as shown below:
import Cookies from 'js-cookie';
We can then set the cookie name and value using the Cookies.set()
method like this:
const token = 'YOUR_JWT_TOKEN';
Cookies.set('token', token, { expires: 7, secure: true });
In the code above, we set the cookie name to ‘token’ and the value to the JWT token. The expires
option sets the expiration date of the cookie, and the secure
option ensures that the cookie is only sent over HTTPS. There are several other properties that can be set to further customize how you want to handle your cookies, but theses are the two most important options to set.
To retrieve the JWT token from the cookie, we can use the following code:
const token = Cookies.get('token');
With this code, we retrieve the JWT token from the cookie named ‘token’.