Authentication and JWT in Node.js
Authentication and JWT in Node.js – Complete Beginner Guide
Authentication and JWT in Node.js are essential for building secure backend applications. They help verify users and protect routes from unauthorized access. In this guide, you will learn how authentication works and how JSON Web Tokens (JWT) are used in Node.js.
What is Authentication in Node.js
Authentication in Node.js is the process of verifying the identity of a user. When a user logs in, the server checks the credentials like email and password. If the credentials are correct, the user is authenticated.
What is JWT (JSON Web Token)
JWT is a token-based authentication method. It allows secure data transfer between client and server. A JWT contains encoded information and is digitally signed.
A JWT has three parts.
Header contains algorithm and token type.
Payload contains user data.
Signature verifies the token.
Why Use JWT in Node.js
JWT is widely used in backend development because it is stateless and secure. It does not require session storage. It is fast and scalable for modern applications.
How JWT Authentication Works
User logs in with credentials.
Server verifies the user.
Server generates a JWT token.
Token is sent to client.
Client sends token in future requests.
Server verifies token and allows access.
Install Required Package
Generate JWT Token
const jwt = require(‘jsonwebtoken’);
const user = { id: 1, name: “Rahul” };
const token = jwt.sign(user, “secretKey”, { expiresIn: “1h” });
console.log(token);
Verify JWT Token
const jwt = require(‘jsonwebtoken’);
const token = “your_token_here”;
try {
const decoded = jwt.verify(token, “secretKey”);
console.log(decoded);
} catch (err) {
console.log(“Invalid token”);
}
Middleware for Authentication
const token = req.headers[‘authorization’];if (!token) {
return res.status(401).json({ message: “Access denied” });
}
try {
const verified = jwt.verify(token, “secretKey”);
req.user = verified;
next();
} catch (err) {
res.status(400).json({ message: “Invalid token” });
}
};
Using Middleware in Route
res.json({ message: “Welcome user”, user: req.user });
});
Best Practices for JWT Authentication
Use strong secret keys
Set token expiration time
Store token securely
Do not store sensitive data in payload
Use HTTPS for secure communication
Real-World Use Case
JWT is used in login systems, mobile apps, and APIs where secure access is required.
Internal Link
Click here for more free courses
FAQs
What is JWT in Node.js
JWT is a token used for secure authentication.
Is JWT better than sessions
JWT is stateless and scalable, making it suitable for modern apps.
Where to store JWT token
Store it in HTTP-only cookies or secure storage.
What happens when token expires
User needs to log in again or refresh token.



