In an Express.js application, you can use JWT (JSON Web Token) to implement user authentication by doing the following:
1. Install Required Packages
You'll need express, jsonwebtoken, bcryptjs (for password hashing), and dotenv for environment variables.
npm install express jsonwebtoken bcryptjs dotenv
2. Set Up Environment Variables
Create a .env file to store your secret key and other sensitive details:
JWT_SECRET=your-secret-key
JWT_EXPIRATION=1h
3. Code Example
Here's how you can implement user authentication:
// Load environment variables
require('dotenv').config();
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const dotenv = require('dotenv');
// Initialize Express app
const app = express();
app.use(express.json()); // For parsing JSON requests
// Mock User Data (For demonstration, you should use a database)
const users = [
{ id: 1, username: 'Sita', password: '$2a$10$Qc7HvZfFHKIjs98MNQ6Fe6bNXUpEJd3oU5Rj0YdiO0zSM0X.5NK7G' } // Password: 'hellothere123'
];
// Login Route
app.post('/login', async (req, res) => {
const { username, password } = req.body;
// Find user by username
const user = users.find(u => u.username === username);
if (!user) {
return res.status(400).send('User not found');
}
// Compare password
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
return res.status(400).send('Invalid password');
}
// Create JWT
const token = jwt.sign(
{ id: user.id, username: user.username },
process.env.JWT_SECRET,
{ expiresIn: process.env.JWT_EXPIRATION }
);
// Send token
res.json({ token });
});
// Middleware to verify JWT
const authenticate = (req, res, next) => {
const token = req.header('Authorization')?.replace('Bearer ', '');
if (!token) {
return res.status(403).send('Access denied');
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(400).send('Invalid token');
}
};
// Protected Route Example
app.get('/protected', authenticate, (req, res) => {
res.send(`Hi, ${req.user.username}`);
});
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});