How to Set Up JWT Authentication in Express.js

JWT (JSON Web Tokens) is a popular method to handle authentication in web applications.

It provides a secure way to verify users and authorize access to resources. Here’s a step-by-step guide to set up JWT authentication in an Express.js application.

Step 1: Install Dependencies

To get started, you’ll need the following npm packages:

Bash
npm install express jsonwebtoken bcryptjs body-parser

  • express: Framework to build the server.
  • jsonwebtoken: For creating and verifying JWTs.
  • bcryptjs: To hash passwords for secure storage.

Step 2: Create an Express App

Set up a simple Express app:

JavaScript
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');

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

const users = [];  // Placeholder for user storage
const secretKey = 'yourSecretKey';  // Secret key for signing the JWT
Expand

Step 3: User Registration Route

Create a route to register users, where passwords are hashed using bcryptjs:

Advertisements
JavaScript
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!' });
});
Expand

Step 4: User Login Route

JavaScript
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 isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
        return res.status(400).json({ message: 'Invalid password' });
    }
    
    const token = jwt.sign({ username: user.username }, secretKey, { expiresIn: '1h' });
    res.json({ token });
});
Expand

Step 5: Protect Routes with JWT

To protect routes, you can create a middleware that checks the validity of the token:

JavaScript
const authenticateToken = (req, res, next) => {
    const token = req.header('Authorization')?.split(' ')[1];
    
    if (!token) {
        return res.status(401).json({ message: 'Access Denied' });
    }
    
    jwt.verify(token, secretKey, (err, user) => {
        if (err) {
            return res.status(403).json({ message: 'Invalid Token' });
        }
        req.user = user;
        next();
    });
};
Expand

Use this middleware to protect any routes:

JavaScript
app.get('/protected', authenticateToken, (req, res) => {
    res.json({ message: `Hello, ${req.user.username}!` });
});
Expand

Step 6: Start the Server

Finally, start the server:

JavaScript
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
Expand

Conclusion

With this setup, you now have a working authentication system using JWT in Express.js.

You can extend this by connecting to a database for persistent user storage and enhancing token expiration or refresh mechanisms.

Leave a Comment

Scroll to Top