NodeJs Middleware and Logins
When building a secure web application, handling user authentication is one of the most common tasks. With Node.js, you get full control over how authentication is handled, thanks to its flexible middleware architecture.
In this article, we’ll break down:
- What middleware is in Node.js.
- How to create custom middleware.
- Implementing login functionality with middleware.
- Protecting routes with authentication.
What is Middleware in Node.js?
In simple terms, middleware is a function that sits between the incoming request (req) and the outgoing response (res). It can modify, validate, or block requests before passing them along.
For example:
- Logging request details.
- Validating authentication tokens.
- Handling errors.
Basic Middleware Structure:
function myMiddleware(req, res, next) { console.log('Middleware executed!'); next(); // move to the next middleware or route}
Setting Up Express with Middleware
const express = require('express');const bodyParser = require('body-parser');
const app = express();app.use(bodyParser.json()); // Middleware for parsing JSON requests
// Custom middleware for logging requestsapp.use((req, res, next) => { console.log(`${req.method} ${req.url}`); next();});
app.get('/', (req, res) => { res.send('Hello, Node.js Middleware!');});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));
Creating a Simple Login System
We’ll create a basic login flow using bcrypt for password hashing and JWT (JSON Web Token) for authentication.
Step 1: User Registration (Hashing Passwords)
const bcrypt = require('bcryptjs');let users = []; // In-memory database for demo
app.post('/register', async (req, res) => { const { username, password } = req.body; const hashedPassword = await bcrypt.hash(password, 10); users.push({ username, password: hashedPassword }); res.json({ message: 'User registered successfully!' });});
Step 2: User Login (Generating JWT)
const jwt = require('jsonwebtoken');const SECRET_KEY = "mysecretkey"; // store securely in env file
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).json({ message: "User not found" });
const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) return res.status(400).json({ message: "Invalid credentials" });
const token = jwt.sign({ username: user.username }, SECRET_KEY, { expiresIn: '1h' }); res.json({ message: "Login successful", token });});
Step 3: Middleware to Protect Routes
We’ll create authMiddleware that verifies JWT before allowing access.
function authMiddleware(req, res, next) { const authHeader = req.headers['authorization']; if (!authHeader) return res.status(401).json({ message: "No token provided" });
const token = authHeader.split(' ')[1]; jwt.verify(token, SECRET_KEY, (err, decoded) => { if (err) return res.status(403).json({ message: "Invalid token" }); req.user = decoded; next(); });}
Step 4: Protected Route
Now let’s create a route accessible only to logged-in users.
app.get('/dashboard', authMiddleware, (req, res) => { res.json({ message: `Welcome, ${req.user.username}! This is your dashboard.` });});
---
Node.js middleware provides a powerful way to handle requests, and when combined with JWT authentication, it makes login systems secure and scalable.
- Middleware simplifies request handling.
- Passwords should always be hashed before storing.
- JWT ensures stateless authentication.
With this setup, you have a strong foundation for building secure apps with Node.js and Express.

