Authentication in MERN Stack Using JWT
User authentication is a critical part of most web applications. In the MERN stack—MongoDB, Express.js, React, and Node.js—you can implement secure authentication using JSON Web Tokens (JWT). JWT provides a stateless, scalable way to manage user sessions without storing session data on the server.
User Registration
Begin by setting up a MongoDB collection for users. Each user document typically includes fields like username, email, and a hashed password. In your Express.js backend, create a POST /api/register endpoint. Before saving the user, hash the password using bcrypt for security.
User Login
Create a POST /api/login endpoint. When a user provides their credentials, verify the email and compare the submitted password with the hashed password stored in the database using bcrypt’s compare method. If the credentials are valid, generate a JWT using a secret key with the jsonwebtoken library. The payload typically includes the user’s ID or username.
Example:
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
Return this token to the client. The token will be stored in the client’s localStorage or a secure HTTP-only cookie.
Protecting Routes
To secure API endpoints, create Express middleware that checks for the presence of a valid JWT in the Authorization header (Bearer token). In your middleware, verify the token with jwt.verify. If the token is valid, allow the request to continue; otherwise, respond with a 401 Unauthorized error.
Example middleware:
function authenticateToken(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ message: 'Access denied' });
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) return res.status(403).json({ message: 'Invalid token' });
req.user = user;
next();
});
}
Frontend Integration
In your React app, send the JWT in the Authorization header with protected API requests:
axios.get('/api/protected', { headers: { Authorization: `Bearer ${token}` } });
Use React Router to redirect users based on authentication status, and manage the token in React context or global state.
JWT-based authentication in the MERN stack ensures secure, scalable, and stateless user management—perfect for modern web apps.
Learn MERN Stack Training Course
Read More:
Managing State in React with Context API
Deploying Your MERN App on Vercel
CRUD Operations Using MERN Stack
Building a To-Do App Using MERN Stack
Visit Quality Thought Training Institute
Comments
Post a Comment