Subscribe
How to Use JWT Authentication with Node.js Express.js
5 mins read

By: vishwesh

How to Use JWT Authentication with Node.js Express.js

Introduction

JWT (JSON Web Token) is a popular authentication mechanism that is widely used in modern web applications. It is a JSON-based open standard that allows transmitting data between parties securely. JWT authentication is easy to implement and can be used to authenticate users in a Node.js and Express.js application.

In this article, we will discuss how to use JWT authentication with Node.js and Express.js. We will cover the following topics:

  • What is JWT authentication?
  • How does JWT authentication work?
  • Setting up a Node.js and Express.js application
  • Installing dependencies
  • Creating a JWT authentication middleware
  • Protecting routes with JWT authentication
  • Testing JWT authentication

What is JWT Authentication?

JWT authentication is a mechanism that uses a JSON web token (JWT) to authenticate users in web applications. The JWT is a JSON object that is signed using a secret key and contains user information, such as username and user ID. When a user logs in, the server generates a JWT and sends it back to the client. The client stores the JWT and sends it back to the server with every subsequent request. The server can then use the JWT to authenticate the user.

How Does JWT Authentication Work?

JWT authentication works in the following way:

  1. The user logs in by sending their username and password to the server.
  2. The server verifies the user's credentials and generates a JWT token.
  3. The JWT token is sent back to the client.
  4. The client stores the JWT token.
  5. The client sends the JWT token with every subsequent request.
  6. The server verifies the JWT token to authenticate the user.

JWT authentication is stateless, meaning that the server does not store any session information. This makes it easy to scale web applications.

Setting up a Node.js and Express.js Application

Before we can start implementing JWT authentication, we need to set up a Node.js and Express.js application.

  1. Create a new directory for your application:
mkdir my-app
cd my-app
  1. Initialize a new Node.js project:
npm init -y
  1. Install Express.js:

Copy code

npm install express
  1. Create an index.js file:
touch index.js

Installing Dependencies

To implement JWT authentication, we need to install the following dependencies:

  • jsonwebtoken: to generate and verify JWT tokens
  • bcrypt: to hash passwords
  • dotenv: to load environment variables

Install these dependencies using the following command:

npm install jsonwebtoken bcrypt dotenv

Creating a JWT Authentication Middleware

To protect routes with JWT authentication, we need to create a middleware that verifies the JWT token.

Create a new file called middleware.js:

const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');

dotenv.config();

const authenticateJWT = (req, res, next) => {
  const authHeader = req.headers.authorization;

  if (authHeader) {
    const token = authHeader.split(' ')[1];

    jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
      if (err) {
        return res.sendStatus(403);
      }

      req.user = user;
      next();
    });
  } else {
    res.sendStatus(401);
  }
};

module.exports = authenticateJWT;

This middleware function extracts the JWT token from the Authorization header of the request, verifies the token using the secret key, and sets the authenticated user in the request object. If the token is invalid or missing, the middleware sends an HTTP 401 or 403 response.

Protecting Routes with JWT Authentication

To protect routes with JWT authentication, we need to use the JWT authentication middleware we just created.

First, let's create a new route that requires authentication. Create a new file called protectedRoute.js:

const express = require('express');
const router = express.Router();
const authenticateJWT = require('./middleware');

router.get('/', authenticateJWT, (req, res) => {
  res.send(`Hello ${req.user.username}!`);
});

module.exports = router;

This route uses the authenticateJWT middleware to verify the JWT token before returning a response. The response includes the username of the authenticated user.

Next, let's add the protectedRoute to our main index.js file:

const express = require('express');
const app = express();
const protectedRoute = require('./protectedRoute');

app.use('/protected', protectedRoute);

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

This code sets up an Express.js app that listens on port 3000. It also uses the protectedRoute middleware to protect the /protected route.

Testing JWT Authentication

To test JWT authentication, we need to send a request to the protected route with a valid JWT token.

We can generate a JWT token using the jsonwebtoken library:

const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');

dotenv.config();

const token = jwt.sign({ username: 'john' }, process.env.JWT_SECRET);
console.log(token);

This code generates a JWT token that includes the username "john". The token is signed using the secret key loaded from the .env file.

Copy the JWT token and send a request to the protected route using a tool such as curl or Postman:

curl -H "Authorization: Bearer <jwt-token>" http://localhost:3000/protected

Replace <jwt-token> with the JWT token you generated. You should see a response that says "Hello john!".

Congratulations, you have successfully implemented JWT authentication with Node.js and Express.js!

Conclusion

JWT authentication is a secure and easy-to-implement mechanism for authenticating users in web applications. In this article, we discussed how to use JWT authentication with Node.js and Express.js. We covered how to set up a Node.js and Express.js application, install dependencies, create a JWT authentication middleware, protect routes with JWT authentication, and test JWT authentication.

By following these steps, you can easily add JWT authentication to your own Node.js and Express.js applications.

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories