Guide to JWT Authentication with Express.js
Guide to JWT Authentication with Express.js
Nowadays, web applications are becoming increasingly complex in managing user authentication processes. In this context, JSON Web Tokens (JWT) is a widely used standard for validating user identity. In this article, we will thoroughly examine the authentication process with JWT using the Express.js framework.
What is JWT and Why is it Used?
JWT (JSON Web Token) is a security standard used to validate user identity. Basically, when a user logs in, they receive a token generated by the server. This token includes user information and a signature that validates that it is valid for a certain period of time. JWT offers a more scalable solution than traditional session-based authentication methods while ensuring secure information exchange between client and server.
JWT Implementation in an Express.js Project
Setup
First, we need to install the necessary packages in our Express.js project. Create your project and install the required packages by running the following commands in the terminal:
mkdir jwt-demo
cd jwt-demo
npm init -y
npm install express jsonwebtoken dotenv
Creating and Verifying JWT
To create and validate JWT, we can use the following sample code. This code will create a token when users log in and check the validity of the incoming token.
const express = require('express');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
dotenv.config();
const app = express();
app.use(express.json());
// Simple user data (in a real application, a database should be used)
const users = [{ id: 1, username: 'user', password: 'password' }];
// Login endpoint
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);
if (user) {
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
return res.json({ token });
}
res.status(401).send('Username or password is incorrect.');
});
// Protected route
app.get('/protected', (req, res) => {
const token = req.headers['authorization']?.split(' ')[1];
if (!token) return res.status(403).send('Token is required.');
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.status(403).send('Invalid token.');
res.send('Protected data: ' + user.id);
});
});
app.listen(3000, () => {
console.log('Server is running on port 3000.');
});
Conclusion
Authentication using JWT is an important part of modern web applications. When integrated with Express.js, this process both enhances user experience and increases the security of your application. With the basic steps we have discussed in this article, you can quickly and effectively set up your own authentication system using JWT.

Yorum Gönder