React Authentication With JWT: The Complete Guide
JWT AuthMERNReactJWTAuth

React Authentication With JWT: The Complete Guide

hmd kamrul
March 10, 2024
8 min read

Authenticating Users

Authenticating users entails being able to identify and confirm that a user is exactly who they say they are. In web apps, this is achieved by providing user credentials, such as a username and password, on the client side. When a user attempts to log in, their credentials are verified on the server side. If correct, a JSON web token is generated and saved.

Setting Up the Backend

You will use a custom-built Express server API to relay the JSON web token. Clone the main branch of the express-auth-api GitHub repository to kick off.

Developer Prerequisites

  • Node.js and npm
  • Express
  • Bcrypt
  • jsonwebtoken
  • Nodemon
  • Mongoose

Run the following command to install dependencies:


npm install

Defining Routes

The Express app has two routes, /sign-up and /sign-in, defined inside userRoutes.js.

/sign-up

When a user makes a POST request to /sign-up, an email and password are required. The email is checked in the database, and if the user doesn't exist, the password is hashed and stored.

/sign-in

The /sign-in endpoint verifies the user and generates a JWT token upon successful authentication.

Creating a JSON Web Token

To generate a token, use jsonwebtoken:


const jwt = require("jsonwebtoken");

Use jwt.sign() to create a token:



    const JWT_SECRET = process.env.JWT_SECRET;
    const token = jwt.sign({ email }, JWT_SECRET);
    return res.status(200).json({ message: "User Logged in Successfully", token });
        

Validating a JSON Web Token

A middleware function can be used to validate tokens and protect routes.



    const jwt = require("jsonwebtoken");
    const mongoose = require("mongoose");
    const User = mongoose.model("User");
    require("dotenv").config();

    module.exports = (req, res, next) => {
        const JWT_SECRET = process.env.JWT_SECRET;
        const { authorization } = req.headers;
        if (!authorization) {
            return res.status(404).send({ error: "Must be logged in" });
        }
        const token = authorization.replace("Bearer ", "");
        jwt.verify(token, JWT_SECRET, async (err, payload) => {
            if (err) {
                return res.status(403).send("Could not verify token");
            }
            req.user = payload;
        });
        next();
    };
        

Setting Up the React Frontend

Install Axios to handle API requests in your React project:


npm install axios

Making Requests to the Authentication Endpoint

Here’s how to make API requests in React using Axios:



    import React, { useEffect } from "react";
    import axios from "axios";

    const MyComponent = () => {
        useEffect(() => {
            axios.post("/sign-up", { username: "exampleuser", password: "password123" })
                .then(response => console.log("Sign up successful", response.data))
                .catch(error => console.error("Sign up error", error));

            axios.post("/sign-in", { username: "exampleuser", password: "password123" })
                .then(response => {
                    console.log("Sign in successful", response.data);
                    const token = response.data.token;
                    axios.defaults.headers.common["Authorization"] = `Bearer ${token}`;
                })
                .catch(error => console.error("Sign in error", error));

            axios.get("/test")
                .then(response => console.log("Test request successful", response.data))
                .catch(error => console.error("Test request error", error));
        }, []);

        return <div>...</div>;
    };

    export default MyComponent;
        

Conclusion

Integrating JWT authentication into a React app provides a secure way to authenticate users and protect data. By leveraging jsonwebtoken, you can easily implement token-based authentication.






Develop By - Hmd Kamrul