What is ExpressJWT?

ExpressJS is a popular Node.js framework for building backend applications. Many Node.js projects run on Express. It helps to create web applications quickly, by providing basic utilities such as middleware functions, routing, and HTTP request or response handling.

Express has some key features which include: Routing, Middleware, Templating engines, and Error handling.

expressjs jwt

Security is paramount in building applications, especially in the world of APIs and authorization. Securing our application can be done in two ways: authorization and authentication. The essence of security is to protect our application from vulnerability and unauthorized access. One popular concept of security that is widely used is the JSON Web Token, also known as JWT.

The JSON Web Token (JWT)

JSON means “JavaScript Object Notation.” JSON is a lightweight format that is easy for humans to read and write and, most importantly, easy for machines to parse and generate. A JSON object is usually a collection of key-value pairs.

Here’s JSON object example:

{
  "sub": "1234567890",
  "name": "Wade",
  "role": "frontend engineer",
  "country": "Canada",
  "iat": 1516239022
}

This is a JSON object.

Here are some functions of JSON in building web applications:

  • Storing and exchanging data in NoSQL databases, e.g., MongoDB
  • Storing and transmitting data between client and server.
  • Parsing and generating data in web APIs.

The concept of JWT is not far-fetched from what the JSON object does. The JSON object makes it easy for various applications to share data between themselves. But transferring raw data can lead to a breach or the exposure of important details that can cause harm to our applications.

Hence the need for JWT. The JSON web token encrypts this information using a cryptographic algorithm. This algorithm encrypts our data, making it secure to be transferred over the network.

JWT is used to encrypt data that is transferred between two parties or systems. Basically, it transfers data as a JSON object.

Component of the JWT

The cryptographic token is composed of three parts.

  1. Header: The header information describes the type of algorithm that is used to generate a token. There are various types of algorithms that can be used. Basically, the header consists of two parts: the signing algorithm and the type of token, which is commonly JWT.
  2. Payload: The payload contains the data that is being transferred over the network.
  3. Signature: It ensures that the user who is sending the message is an authentic sender & the message has not been tampered. i.e. Authenticity of data.

Here we have an example of what the token looks like. i.e. A JWT token

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwiaWF0IjoxNTE2MjM5MDIyLCJuYW1lIjoiQ2h1a3d1ZWJ1a2EgVmljdG9yIiwidXNlcklkIjoiYmFjZDMtaG5kNjAtOWRhZGYtNjdmc3QtcG9sbjUifQ.AbliZwNtpN87XznPcImREYIqDgioAEFZ1WkAFffBBI0

Here is what makes up this token:

JWT tokens

What is ExpressJWT?

Now that we have seen what Express and JWT is, understanding what ExpressJWT is not far-fetched. ExpressJWT is a middleware for the Express framework in Node.js that provides authorization and authentication functionalities using JSON Web Tokens.

When a user login, a token is generated for that user, which encrypts details about that user and resends it to the user. By using this token, the user will have access to the server for other request.

When the server receives any request after the user has logged in, the server checks whether ths token is valid and has not expired.

Benefits of Using ExpressJWT

ExpressJWT offers some number of advantages over other libraries that perform the same or similar functions. Some of the examples can be seen below:

  1. Scalable: Large numbers of concurrent requests can be handled with the Express JWT library without sacrificing speed. It makes it a good choice for high-traffic web applications that require fast and reliable authentication and authorization.
  2. Easy to use: ExpressJWT simplifies the authentication and authorization of our application by offering a straightforward and understandable API for working with JWTs. Additionally, it seamlessly communicates with the Express web framework, enabling you to protect particular routes with minimal code.
  3. Lightweight: Express JWT is a lightweight library designed to provide simply the essential functionalities needed to interact with JSON Web Tokens. Because of its quick and effective architecture, it is a suitable option for applications that have to handle a lot of requests.

How does Express JWT Library work?

ExpressJWT works by protecting routes that require authentication with middleware. When a user login, a token is generated for that user. This token is then included in all subsequent requests to the server. The ExpressJWT middleware checks each request for a valid token before allowing access to protected resources.

ExpressJWT middleware working
Diagramatic representation of how the ExpressJWT middleware works

The image above gives a pictorial representation of how the ExpressJWT library works.

  1. The client generates a send request to the server.
  2. The server checks the request for a JSON Web Token (JWT).
  3. If a JWT is present, the server verifies the token’s signature and expiration date.
  4. If the token is valid, the server allows the client to access the requested resource.
  5. If the token is invalid, the server denies the client access to the requested resource.

Step-by-Step method of using Express JWT

To use Express JWT, you need to include it as a middleware in your Express.js application. Once included, it can be used to protect the routes that require authentication. Express JWT provides various options to customize the authentication process, such as setting the secret key, defining the expiration time of tokens, and more. Here is a defined step for using ExpressJWT in our Node.js application

  • Import the express-jwt module.
  • To use express-jwt as a middleware, we would need to pass the secret we used to encode the data and also specify what type of hashing algorithm was used.

Implementing ExpressJWT in a project

1. Let’s start up our project by initializing with the npm command

npm init -y

2. Install the required libraries which are express jsonwebtoken express-jwt

npm i express express-jwt jsonwebtoken

3. Create the index.js file and get the server running

const express = require('express');

const app = express();

app.use(express.json());

app.get("/home", (req, res) => {
    res.send("Welcome to ExpressJWT tutorial");
})


app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
})

With this, our server is up and running, and if we visit (http://localhost:3000/home) on our browser, we should get a response saying:

Welcome to ExpressJWT tutorial

4. We add a login route that generates a token if the user has a username that matches the correct data.

const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const secret = 'this-is-my-secret';

app.post("/login", (req, res) => {
    const { username, password } = req.body;

    if (username === 'algoideas' && password === 'password123') {
        // the password matches the values above generate a token
        const token = jwt.sign({ username }, secret, { expiresIn: '1h' })
        // the above connnotes that the username have been hashed using the secret key we provided and will expire in 1 hour
        res.json({ status: true, message: "User logged in successfully", token })
    } else {
        res.status(401).json({ status: false, message: "invalid username or password" });
    }
})

If we log in to the platform, a token is generated and will be used anytime the user wants to access any protected resource.

Here is an example of the type of response we are going to get when we log in

5. Now that a user has successfully logged in, let’s depict how a user can use the token to access a protected resource, by adding these lines of code.

app.get("/protectedroute", expressJwt.expressjwt({ secret: secret, algorithms: ["HS256"],  }), (req, res) => {
    res.status(200).json({ status: true, message: "You were able to access the protected resourece" })
});

This line of code shows us how we can use express-jwt as a middleware for our protected route.

For us to test this out we are going to copy the token from the login response and send it as a bearer token in our header.

First, we are going to send a wrong token and see what response we would get

The response we get is the UnauthorizedError which tells us that we don’t have access to the server and the server throws an error.

We can always build an error handler that catches errors anytime an error pops up

For a correct token, we get access to the requested resource without any form of error.

Best practices for using ExpressJWT

  • Use strong and random secret keys
  • Set expiration times on the generated JWTs
  • Ensure that when a user logs out, the generated token is revoked

Wrapping Up

In summary, Express JWT is a middleware package for Express.js that provides a simple and secure way of implementing JWT authentication in web applications. Its ease of use and customizability make it a popular choice among Node.js developers.

Stay in the Loop

Get the weekly email from Algoideas that makes reading the AI/ML stuff instructive. Join our mailing list to stay in the loop to stay informed, for free.

Latest stories

- Advertisement -

You might also like...