How to Create and Verify JWTs with Node?
Last Updated :
08 Jan, 2025
In this article, we will see how to create JWT tokens in Node.js. We will implement secure authentication in Node.js by creating and verifying JSON Web Tokens (JWTs) using libraries like `jsonwebtoken`.
Prerequisites:
Steps to Implement and Verify JWT
Step 1: Firstly set up the NodeJs project. If you do not have NodeJs or NPM please refer to this article. Initiate NodeJs project with npm.
npm init -y
Step 2: After initiating the project install some dependencies. Install express, and jsonwebtoken through npm
npm install express jsonwebtoken
Step 3: Install nodemon as a dev-dependency.
npm install -d nodemon
Project Structure:

The updated dependencies in package.json file will look like
"dependencies": {
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"nodemon": "^3.0.2",
}
Step 4: Add one more script in the package.json file. Open the package.json file and add one line below to the test script.
Approach
- Before create and verify the API endpoint with the help of JWT, and express firstly write some code for further use.
- After the dummy code is ready, then create a json database object and store some dummy data.
- Allow JSON data to make communicate with API. Allow the JSON data in a request by adding middleware for the body parser.
- Create a login route and create a JWT token. Here, create a login post route and create a JWT token and return it to the response., read code comments for better understanding.
- JWT sign method is used to creating a token the take are three arguments one is a response object, and the second one is a secret key and the last one is an options object for better use of the token.
jwt.sign(
{data_obeject},
"secret_key",
{Options}
)
- Now we will make another route for authentication jwt token. Here, we create an authentication route and authenticate the coming JWT token.
// Verify route
app.get('/auth', (req, res) => {
// Get token value to the json body
const token = req.body.token;
// If the token is present
if(token){
// Verify the token using jwt.verify method
const decode = jwt.verify(token, 'secret');
// Return response with decode data
res.json({
login: true,
data: decode
});
}else{
// Return response with error
res.json({
login: false,
data: 'error'
});
}
});
- JWT verify method is used for verify the token the take two arguments one is token string value, and second one is secret key for matching the token is valid or not. The validation method returns a decode object that we stored the token in.
jwt.verify(token_value, 'secret_key');
Example: Below is the complete code of the above step by step implementation
Node
// index.js
// Import express for creating API's endpoints
const express = require("express");
// Import jwt for API's endpoints authentication
const jwt = require("jsonwebtoken");
// Creates an Express application, initiate
// express top level function
const app = express();
// A port for serving API's
const port = 3000;
// A fake database object
let database = [
{
name: "gfg",
work: "knowledge provider",
password: "abc",
},
{
name: "suryapratap",
work: "technical content writer",
password: "123",
},
];
// A demo get route
app.get("/", (req, res) => {
res.json({
route: "/",
authentication: false,
});
});
// Allow json data
app.use(express.json());
// Login route
app.post("/login", (req, res) => {
// Get the name to the json body data
const name = req.body.name;
// Get the password to the json body data
const password = req.body.password;
// Make two variable for further use
let isPresent = false;
let isPresentIndex = null;
// iterate a loop to the data items and
// check what data are matched.
for (let i = 0; i < database.length; i++) {
// If data name are matched so check
// the password are correct or not
if (database[i].name === name
&& database[i].password === password) {
// If both are correct so make
// isPresent variable true
isPresent = true;
// And store the data index
isPresentIndex = i;
// Break the loop after matching successfully
break;
}
}
// If isPresent is true, then create a
// token and pass to the response
if (isPresent) {
// The jwt.sign method are used
// to create token
const token = jwt.sign(database[isPresentIndex], "secret");
// Pass the data or token in response
res.json({
login: true,
token: token,
data: database[isPresentIndex],
});
} else {
// If isPresent is false return the error
res.json({
login: false,
error: "please check name and password.",
});
}
});
// Verify route
app.get("/auth", (req, res) => {
// Get token value to the json body
const token = req.body.token;
// If the token is present
if (token) {
// Verify the token using jwt.verify method
const decode = jwt.verify(token, "secret");
// Return response with decode data
res.json({
login: true,
data: decode,
});
} else {
// Return response with error
res.json({
login: false,
data: "error",
});
}
});
// Listen the server
app.listen(port, () => {
console.log(`Server is running :
http://localhost:${port}/`);
});
Step to test the routes: We will use Postman to test the API routes. Firstly test the login route. Open the postman and make a post request on the '/login' route with appropriate JSON data.
Output: Send a POST request to localhost at '/login' with login data, receive a JSON response with login status and token/object data, then use the token to authenticate a GET request to '/auth'. After validation, you will get the proper data object store in the token.
Similar Reads
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 Create HTTPS Server with Node.js ?
Creating an HTTPS server in Node.js ensures secure communication between your server and clients. HTTPS encrypts data sent over the network, providing a layer of security essential for handling sensitive information. This guide will walk you through the process of setting up an HTTPS server in Node.
4 min read
How to Create A REST API With JSON Server ?
Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Re
4 min read
How To Create a Simple HTTP Server in Node?
NodeJS is a powerful runtime environment that allows developers to build scalable and high-performance applications, especially for I/O-bound operations. One of the most common uses of NodeJS is to create HTTP servers. What is HTTP?HTTP (Hypertext Transfer Protocol) is a protocol used for transferri
3 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
How to Create and View Access Tokens in NPM ?
Access tokens are important components in the npm ecosystem, used as authentication mechanisms for users to interact with npm registries securely. They grant permissions for actions such as publishing packages, accessing private packages, or managing user accounts. In this article, we will see how t
2 min read
Node.js x509.verify() Function
The x509.verify() is an inbuilt application programming interface of class X509Certificate within crypto module which is used to check if the certificate was signed by the given public key. Syntax: const x509.verify(publicKey) Parameters: This function takes the public key object as a parameter. Re
2 min read
How to use SSL/TLS with Node.js ?
TLS/SSL is used for establishing secure connections over the internet. Today, most websites use HTTPS to communicate with clients. HTTPS is basically HTTP running over TLS/SSL. Web clients like browsers alert users about websites that do not use HTTPS since such websites are vulnerable to cyber-atta
5 min read
How to Install an SSL Certificate on NodeJS?
Security is essential in today's internet-driven environment to safeguard users and guarantee that users trust your web apps. Using SSL (Secure Sockets Layer) certificates, which enable HTTPS and encrypt interactions between the server and client, is one of the fundamental security precautions. You
5 min read
How to Generate and Validate OTPs in Node.js with 'Speakeasy' Module ?
Speakeasy is a very important and useful npm module that can generate and validate OTPs (One Time Passwords). OTPs are mainly used for security-related purposes. This module basically supports two types of OTPs: TOTP and HOTP. The main difference between these two types of OTPs is TOTP generates a t
3 min read