DEV Community

Cover image for How To Use JWT Token in React JS
Udemezue John
Udemezue John

Posted on

How To Use JWT Token in React JS

Introduction.

When building modern web applications, security is a top priority. One of the most common ways to secure your app’s interactions with external services, like APIs, is by using JWT (JSON Web Tokens).

In the world of React applications, JWT has become a go-to solution for handling authentication and session management.

Understanding how to implement and use JWT in a React application is key to ensuring that data stays protected while providing a seamless user experience.

In this guide, I'll walk you through the process of integrating JWT into a React app, breaking down what JWT is, why it’s effective for authentication, and how you can use it to secure your API requests.

You'll see how to store tokens safely, manage user sessions, and ensure your app remains both functional and secure.

What is JWT and Why Use It?

JWT (JSON Web Token) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between two parties.

The token is signed using a secret key or a public/private key pair (like RSA).

Here are a few reasons why JWT is often preferred:

  • Stateless Authentication: JWTs contain all the necessary information about a user, allowing the server to remain stateless. This makes them ideal for modern RESTful APIs.
  • Security: Tokens are signed, ensuring that they can't be altered by the client.
  • Portability: Being a string (often formatted as xxxxx.yyyyy.zzzzz), it's easy to send JWTs in HTTP headers, URL parameters, or even in local storage.
  • Compact: JWTs are concise, making them efficient to send over HTTP.
  • JWT Structure

A JWT consists of three parts:

  • Header: Contains the token type (JWT) and the signing algorithm used (e.g., HMAC, SHA256).
  • Payload: This includes the claims (data) you want to store, like the user's ID, role, and expiration time.
  • Signature: This is used to verify that the token hasn’t been tampered with. It’s created by encoding the header and payload, then signing it with a secret.

Here's an example of a JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

Enter fullscreen mode Exit fullscreen mode

How Do I Use JWT Token in React JS?

Handling authentication and securely managing user sessions is a fundamental part of building modern web applications.

One of the most common approaches is using JWT (JSON Web Tokens) for user authentication in React.js applications.

If you're new to JWTs or just looking for a hands-on guide on how to integrate them with React, this article will walk through the entire process.

Setting Up JWT Authentication in React.js

Step 1: Backend Setup.

To authenticate users with JWT in a React application, I'll first need a backend that generates the tokens.

Typically, a Node.js/Express backend would generate and validate the JWT, but any language/framework capable of signing and verifying tokens can be used.

For instance, in Node.js using the jsonwebtoken package, I can create a token like this:

const jwt = require('jsonwebtoken');

const user = { id: 1, username: "exampleUser" };
const accessToken = jwt.sign(user, process.env.JWT_SECRET, { expiresIn: '1h' });

Enter fullscreen mode Exit fullscreen mode

This token is then sent to the frontend after the user successfully logs in.

Step 2: Install Dependencies in React.

In the React app, I'll need two main libraries: axios for making API calls and jwt-decode for decoding the JWT token.

First, install both libraries:

npm install axios jwt-decode
Enter fullscreen mode Exit fullscreen mode
  • Axios: For making HTTP requests to the backend.
  • jwt-decode: A small library to decode JWT tokens without verifying the signature. It’s useful to extract user data from the token.

Step 3: Create a Login Form.

I'll need a basic form to let users enter their login credentials. When they submit the form, the credentials will be sent to the backend, and if they're valid, the backend will return a JWT.

import React, { useState } from 'react';
import axios from 'axios';

const Login = () => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await axios.post('http://localhost:5000/api/login', { email, password });
      const { token } = response.data;

      // Save token to local storage
      localStorage.setItem('token', token);

      // Redirect user or update state
      console.log('Login successful, token saved.');
    } catch (error) {
      console.error('Login failed:', error.response.data);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
        placeholder="Email"
      />
      <input
        type="password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
        placeholder="Password"
      />
      <button type="submit">Login</button>
    </form>
  );
};

export default Login;
Enter fullscreen mode Exit fullscreen mode

Step 4: Storing the Token.

After receiving the JWT from the backend, I'll store it in the browser's localStorage or sessionStorage.

In this example, I'll use localStorage because it persists even after the browser is closed.

However, it’s important to note that storing JWTs in local storage can make your app vulnerable to XSS (cross-site scripting) attacks.

A better option in production is to store the token in an HTTP-only cookie.

localStorage.setItem('token', token);
Enter fullscreen mode Exit fullscreen mode

Step 5: Making Authenticated Requests.

Now that I have the token, I can include it in the headers of requests to the backend to access protected routes.

const getUserProfile = async () => {
  const token = localStorage.getItem('token');

  if (token) {
    try {
      const response = await axios.get('http://localhost:5000/api/profile', {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      console.log(response.data);
    } catch (error) {
      console.error('Failed to fetch profile:', error);
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

Step 6: Decoding the JWT.

If I need to access user information stored in the JWT (like the user’s ID or role), I can decode it using jwt-decode.

import jwt_decode from 'jwt-decode';

const token = localStorage.getItem('token');
if (token) {
  const decoded = jwt_decode(token);
  console.log('Decoded token:', decoded);
}
Enter fullscreen mode Exit fullscreen mode

This will output an object containing the information stored in the token (such as userID, role, etc.).

Step 7: Implementing Logout.

To log the user out, simply remove the JWT from local storage.

const logout = () => {
  localStorage.removeItem('token');
  console.log('User logged out');
};
Enter fullscreen mode Exit fullscreen mode

Token Expiration and Refreshing Tokens

JWTs typically have an expiration time (exp claim in the payload). When a token expires, the user will need to log in again or refresh the token.

To handle this:

  • Check for Expiry: Before making API calls, I can check if the token has expired.
  • Refresh Token: Implement a refresh token system where the backend sends a new token before the old one expires.

This process ensures that users don’t need to log in again frequently while still maintaining security.

Security Considerations

While JWT is convenient, it comes with security risks if not handled properly. Here are some best practices:

  • Use HTTPS: Always use HTTPS to transmit tokens to prevent man-in-the-middle attacks.
  • Avoid Storing Tokens in Local Storage: Prefer HTTP-only cookies for storing JWTs to mitigate XSS attacks.
  • Validate Tokens on the Server: Never trust the data inside the JWT on the client-side without validating it on the server.

Conclusion.

Using JWTs in React.js for authentication provides a powerful and scalable solution, especially for stateless applications.

The workflow involves sending user credentials to the backend, receiving a JWT, and then storing and using that token for authenticated requests.

With proper attention to security, JWT authentication can be both efficient and safe in any React application.

Top comments (0)