How to use JSON web tokens with Node.js ?
Last Updated :
02 Sep, 2022
JSON Web Token (JWT) is an Internet Standard that is used for exchanging data between two parties in a secure manner. It can't be easily hacked as it creates a digital signature with the secret key along with the HMAC algorithm).Â
JWT Structure: JSON Web Tokens consist of three parts separated by dots (xxxxx.yyyyy.zzzzz), which are:
- Header: This contains the type of the token (JWT in this case) and the algorithm used.
- Payload: This contains the payload data that was used while creating the token
- Signature: The digital signature that is created using the header, payload, and secret key along with an algorithm as specified in the header).
Integration with Node.js:Â
Step 1: First up, initialize a simple node app using the below command and add express, dotenv package.
npm init -y
npm i express dotenv
Step 2: Then, install JWT using the below command
npm i jsonwebtoken
Example: Let's illustrate the use of JWT using a simple user authentication app.
Copy the below contents in the index.js file. For illustration purposes let's assume we have a user "admin" with the password "admin".Â
Our aim is to protect the "/home" endpoint using JWT that only authenticated users can access.
JavaScript
const express = require("express");
const app = express();
app.use(express.json());
app.post("/login", (req, res) => {
console.log("Login router");
res.json({ msg: "Login Endpoint" });
});
app.get("/home", (req, res) => {
console.log(
"Protected endpoint that only authorized users can access");
res.json({ msg: "Home Endpoint" });
});
app.listen(8000, () => console.log("Listening on 8000"));
First, we will use JWT to sign the token and send it back to the user on a successful login. Then on every subsequent request, the user will send the JWT token through the request header.Â
Create a .env file with the following content:
JWT_SECRET_KEY=<your_secret_key>
Replace with your secret key. This secret key is used by JWT to digitally sign the tokens. This shouldn't be exposed in the codebase as it may lead to security breaches. This should be saved securely when working with real-time apps.
Now, let's modify the login endpoint in the index.js file as below:
JavaScript
// Add these two lines at the top of the file
require("dotenv").config();
const jwt = require("jsonwebtoken");
// Modify the login route as below
app.post("/login", (req, res) => {
const { username, password } = req.body;
if (username === "admin" && password === "admin") {
const token = jwt.sign({ username },
process.env.JWT_SECRET_KEY, {
expiresIn: 86400
});
return res.json({ username, token, msg: "Login Success" });
}
return res.json({ msg: "Invalid Credentials" });
});
Here when the user is successfully logged in, we are using JWT to sign the token with the username as the payload and it will expire in 86400 seconds (24 hours).
Steps to run the application: Now start the application using the below command:
node index.js
Open any REST Client of your choice (Postman/ Insomnia/ Thunder Client etc.,) and make a POST request to the login endpoint with the request body as below
Login request body
When we run it, we will get a response as below:
Login Response
Now copy the token and save it for later for the next request to the home endpoint. As the login endpoint is done, let's move on to the home endpoint.
Now edit the index.js file as below:
JavaScript
/* This middleware function is used to verify
the token before granting access to the user
to the protected endpoints. If the token is
invalid it will restrict the user from
accessing the protected endpoints
We can use this middleware to any endpoints
that we desire to make as protected*/
const verifyTokenMiddleware = (req, res, next) => {
const { token } = req.body;
if (!token) return res.status(403).json({
msg: "No token present"
});
try {
const decoded = jwt.verify(token,
process.env.JWT_SECRET_KEY);
req.user = decoded;
} catch (err) {
return res.status(401).json({
msg: "Invalid Token"
});
}
next();
};
// Modify the home endpoint as below
// to use the verifyTokenMiddleware
app.get("/home", verifyTokenMiddleware, (req, res) => {
const { user } = req;
res.json({ msg: `Welcome ${user.username}` });
});
Here, We have created a verifyToken middleware that verifies the validity and integrity of the token and the user will be able to access the home endpoint only if the token is valid.
Open the REST Client and try to access the home endpoint without any token.
Home endpoint without any request body
When we run this we will get the below error.
No Token Present error
Now, paste the token copied in the login step in the request header and try to access the home endpoint.
Home endpoint with token
When we run this we will get the following success response.
Success
Success!. When provided with the correct token, we are able to access the home endpoint. In this way, we can secure our Node.js apps using jwt.
Similar Reads
How to Send ERC20 Token with Web3.js?
Sending ERC20 tokens is a common task in the world of Ethereum and decentralized applications. ERC20 tokens are a type of digital asset that lives on the Ethereum blockchain and follows a specific set of rules. The article focuses on discussing how to send ERC20 tokens using Web3.js, a popular JavaS
6 min read
How to Use jQuery with Node.js ?
jQuery is a popular JavaScript library primarily used for client-side scripting to simplify HTML document traversal, event handling, animation, and AJAX interactions. Although jQuery is designed for the browser, you might find scenarios where you want to use it on the server side with Node.js, such
3 min read
How to Parse JSON using Node.js?
JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configu
2 min read
How to Send JSON Response using Node.js ?
NodeJS is the runtime environment, which can execute the javascript code on any platform. It is widely used to create and run web application servers because of its salient features.During production, several times we need to send the resources or some type of information as a response, and javascri
5 min read
How to Update value with put in Express/Node JS?
Express JS provides various HTTP methods to interact with data. Among these methods, the PUT method is commonly used to update existing resources. PrerequisitesNode JS Express JS In this article, we are going to setup the request endpoint on the server side using Express JS and Node JS. This endpoin
2 min read
How to work with Node.js and JSON file ?
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. With node.js as backend, the developer can maintain a single codebase for an entire application in javaScript.JSON on the other hand, stands for JavaScript Object Notation. It is a lightweight format for storing and exchanging d
4 min read
How to generate unique ID with node.js?
In this article, we are going to learn how to generate a unique ID using Node.js. Unique ID means a string contains a unique identity throughout the program. Table of Content Using UUIDUsing CryptoPrerequisitesJavaScript Node JSApproach 1: Using UUIDUUID is a module of NPM (Node Package Manager). UU
1 min read
How to Use Session Variables with NodeJS?
When building web applications with NodeJS, managing session data becomes an important task, especially for things like user authentication, shopping carts, or temporary data storage. In this article, we will explore how to use session variables in NodeJS.What are Session Variables?Session variables
5 min read
Flask API Authentication with JSON Web Tokens
Authentication is the process of verifying the identity of the user. It checks whether the user is real or not. It is used to provide access to resources only to valid users. There are two types of Authentication: Single Factor Authentication: In this only one piece of information is needed to verif
7 min read
How to use TypeScript to build Node.js API with Express ?
TypeScript is a powerful version of JavaScript that incorporates static typing and other features, making it easy to build and maintain large applications. Combined with Node.js and Express, TypeScript can enhance your development experience by providing better type safety and tools. This guide will
4 min read