- Express.js Basics
- Express.js HOME
- Express.js Introduction
- Express.js Installation
- Express.js Basic App
- Express.js Routing
- Basics Routing
- Route Parameters
- Handling Query Strings
- Router Middleware
- Middleware
- What is Middleware?
- Application-Level Middleware
- Router-Level Middleware
- Built-In Middleware
- Error-Handling Middleware
- Third-Party Middleware
- Express.js HTTP
- Handling GET Requests
- Handling POST Requests
- Handling PUT Requests
- Handling DELETE Requests
- Templating Engines
- Using Templating Engines
- Setting Up EJS
- Setting Up Handlebars
- Setting Up Pug
- Request/Response
- Request Object
- Response Object
- Handling JSON Data
- Handling Form Data
- Static Files
- Serving Static Files
- Setting Up Static Folders
- Managing Assets
- Express.js Advanced
- Middleware Stack
- CORS in Express.js
- JWT Authentication
- Session Handling
- File Uploads
- Error Handling
- Databases
- Express.js with MongoDB
- MongoDB CRUD Operations
- Express.js with MySQL
- MySQL CRUD Operations
- Deployment
- Deploying Express.js Apps to Heroku
- Deploying Express.js Apps to AWS
- Deploying Express.js Apps to Vercel
Express.js JWT Authentication
JSON Web Token (JWT) is a compact, URL-safe way of representing claims between two parties. In Express.js, JWT is commonly used for securing APIs and implementing authentication mechanisms.
Key Features of JWT Authentication
- Token-Based Authentication: Ensures secure communication between client and server using tokens.
- Stateless: JWT eliminates the need to store session data on the server.
- Compact and Secure: Contains encoded payload, making it efficient for transmission.
- Easy to Verify: The server can validate the token using a secret key.
Steps to Implement JWT Authentication
Install Required Packages
Use jsonwebtoken
for signing and verifying tokens and bcryptjs
for hashing passwords.
npm install jsonwebtoken bcryptjs
Create a Token
Generate a JWT after validating the user’s credentials.
Example:
const jwt = require('jsonwebtoken');
const payload = { id: user.id, username: user.username };
const secret = 'your_secret_key';
const token = jwt.sign(payload, secret, { expiresIn: '1h' });
res.json({ token });
Verify a Token
Protect routes by verifying tokens using middleware.
Example:
const authenticateToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(401).send('Access Denied');
jwt.verify(token, 'your_secret_key', (err, user) => {
if (err) return res.status(403).send('Invalid Token');
req.user = user;
next();
});
};
app.get('/protected', authenticateToken, (req, res) => {
res.send('This is a protected route');
});
Hash Passwords with Bcrypt
Use bcryptjs
to securely hash user passwords before saving them in the database.
Example:
const bcrypt = require('bcryptjs');
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password, salt);
Compare Passwords
Compare user input with hashed passwords during login.
Example:
const isValid = bcrypt.compareSync(password, hashedPassword);
if (!isValid) return res.status(400).send('Invalid Credentials');
Complete Example of JWT Authentication
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
app.use(express.json());
const users = []; // In-memory user store (for demo)
const secret = 'your_secret_key';
// Register User
app.post('/register', (req, res) => {
const { username, password } = req.body;
const hashedPassword = bcrypt.hashSync(password, 10);
users.push({ id: users.length + 1, username, password: hashedPassword });
res.send('User registered successfully');
});
// Login User
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !bcrypt.compareSync(password, user.password)) {
return res.status(400).send('Invalid Credentials');
}
const token = jwt.sign({ id: user.id, username: user.username }, secret, { expiresIn: '1h' });
res.json({ token });
});
// Protected Route
app.get('/protected', (req, res) => {
const token = req.headers['authorization'];
if (!token) return res.status(401).send('Access Denied');
jwt.verify(token, secret, (err, user) => {
if (err) return res.status(403).send('Invalid Token');
res.send(`Hello ${user.username}, welcome to the protected route.`);
});
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Summary
JWT Authentication in Express.js provides a secure, stateless way to authenticate users. By generating, signing, and verifying tokens, applications can protect routes and manage access effectively. Integrating libraries like jsonwebtoken
and bcryptjs
ensures robust security for API communication.