India-built AI & blockchain engineering since 2017 · Serving clients worldwide

blog

JWT Authentication in Node.js: A Step-by-Step Guide

JWT Authentication in Node.js: A Step-by-Step Guide

Jeevan

25 September, 2025

JWT Logo


JSON Web Tokens (JWT) are a widely-used method for securely transmitting information between parties as a JSON object. In Node.js applications, JWT is commonly used for user authentication and authorization. This guide will walk you through implementing JWT authentication in a Node.js application step by step.

Why JWT Authentication?

JWT allows you to create stateless authentication systems, meaning the server does not need to store session information. It’s secure, scalable, and works seamlessly with APIs. By using JWT, you can protect routes, verify users, and ensure secure communication between client and server.

Step-by-Step Guide to JWT Authentication in Node.js

1. Set Up Your Node.js Project

First, create a new project folder and initialize it:

mkdir jwt-auth-demo
cd jwt-auth-demo
npm init -y

Install the necessary packages:

npm install express jsonwebtoken bcryptjs body-parser

– express – For creating the server.
– jsonwebtoken – For generating and verifying JWTs.
– bcryptjs – For hashing passwords.
– body-parser – For parsing incoming request bodies.

2. Create a Basic Express Server

Create a file server.js:

const express = require('express');
const bodyParser = require('body-parser');

const app = express();
app.use(bodyParser.json());

app.get('/', (req, res) => {
  res.send('JWT Authentication Demo');
});

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

3. Implement User Registration

In a real application, you’d store users in a database. For simplicity, we’ll use an in-memory array:

const users = [];
const bcrypt = require('bcryptjs');

app.post('/register', async (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);
  users.push({ username, password: hashedPassword });
  res.send('User registered successfully!');
});

This hashes the user’s password before storing it, ensuring security.

4. Implement User Login with JWT

const jwt = require('jsonwebtoken');

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username);
  if (!user) return res.status(400).send('User not found');

  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) return res.status(400).send('Invalid credentials');

  const token = jwt.sign({ username: user.username }, 'your-secret-key', { expiresIn: '1h' });
  res.json({ token });
});

This generates a JWT token that expires in 1 hour.

5. Protect Routes Using JWT

const authenticate = (req, res, next) => {
  const token = req.header('Authorization')?.replace('Bearer ', '');
  if (!token) return res.status(401).send('Access denied');

  try {
    const verified = jwt.verify(token, 'your-secret-key');
    req.user = verified;
    next();
  } catch (err) {
    res.status(400).send('Invalid token');
  }
};

app.get('/protected', authenticate, (req, res) => {
  res.send('This is a protected route. Welcome ' + req.user.username);
});

Now, only users with a valid JWT can access the protected route.

How This Helps You

Implementing JWT authentication allows you to create secure, stateless authentication for your Node.js applications. This approach can be extended to APIs, microservices, and frontend-backend integrations, giving you full control over user access and authorization.

Conclusion

JWT authentication in Node.js is powerful and straightforward. By following these steps—setting up the project, registering users, generating tokens, and protecting routes—you can secure your application efficiently. Once comfortable, you can integrate databases, refresh tokens, and more advanced authentication features to build robust and scalable applications.

Share this article

Leave a Reply

Your email address will not be published. Required fields are marked *

Keep reading

Related articles

Have an AI idea or a product to build? Let’s talk.

Tell us what you are building. A solutions architect will respond within one business day with next steps and a no-obligation estimate.

  • Free 30-minute consultation
  • NDA on request, before we talk details
  • Estimate within 3–5 business days
WhatsAppTelegramCall

Tell us what you want to build

A solutions architect replies within one business day. NDA on request.

We reply within one business day. Your details stay confidential.