Loading...

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.

RECENT POSTS

Choosing a Tech Partner Who Actually Understands Regulatory Compliance

A few months back, a fintech client came to us after a failed product launch. Their previous development partner had built a solid lending app — clean UI, fast performance, good UX. The problem? Nobody on that team had accounted for RBI’s Digital Lending Guidelines around data storage and third-party data sharing. The app went […]

How Automation Reduces Manual Errors in Banking Back-Office Work

A few months ago, we sat down with the operations head of a mid-sized NBFC who told us something that stuck with us: “My team isn’t lazy or careless. They’re just human, and humans reconciling 40,000 transactions a day will always slip somewhere.” That one sentence sums up why banking back offices keep bleeding money […]

Building Dashboards for Real-Time Transaction Monitoring: What Actually Works in BFSI

A few months back, one of our fintech clients — a Mumbai-based NBFC processing close to 40,000 UPI and card transactions a day — came to us with a problem that sounded simple on the surface: “Our fraud team is looking at data that’s 15 minutes old, and by the time they act, the money’s […]

Why a Dedicated PM Matters in Outsourced Software Projects (Especially for BFSI Teams)

A few months ago, a fintech client came to us at Speqto Technologies after a rough experience with a previous outsourcing vendor. The code wasn’t the problem — their developers were competent. The problem was that nobody owned the project end to end. Requirements got lost in Slack threads, QA found bugs three sprints too […]

What Startup India and MeitY Recognition Actually Means When You’re Evaluating a Tech Vendor

If you’re on the vendor onboarding side of a bank, NBFC, or fintech company, you’ve seen this drill a hundred times. A vendor sends over a slick deck, promises the moon on integration timelines, and then your compliance team spends three weeks trying to figure out if this company even legally exists in a form […]

POPULAR TAG

POPULAR CATEGORIES