How to Integrate JWT Authentication in Your MERN Stack App (With Postman)


Authentication is one of the most important elements to manage while developing web applications. Securing user data is essential whether you're creating an advanced platform or a tiny blog.
The implementation of JWT (JSON Web Token) authentication in your MERN stack application (MongoDB, Express, React, and Node.js) will be covered in this post, along with Postman testing. You'll have a functional authentication system and the resources to test it without a frontend at the end.
What is JWT?
Let's take a quick look at JWT's operation before we dive into the code.
A small, URL-safe token called JWT (JSON Web Token) is used to safely send data between two parties. Its simplicity and stateless nature make it a popular authentication method.
Three components make up a JWT:
Header:
Information about the token's signing method, such as HMAC SHA256, is contained in the header.Payload:
User data (such as roles or user IDs) is stored in the payload, which contains the claims.Signature:
Confirms that the token hasn't been tampered with.
No session data needs to be stored on the server when using JWT. Rather, all the data needed to confirm the user's identity is contained in the token itself.
Why Would a MERN Stack App Use JWT?
JWT authentication is an excellent choice for MERN stack applications for the following reasons:
Without a state:
Session data does not need to be kept on the server. The JWT has all the information you require encoded.Scalable:
Because session management is not an issue, it performs admirably in large applications with lots of users.Works Across Platforms:
JWT is a versatile solution for multi-platform projects because it can be utilized in both web and mobile applications.
Configuring the Backend (Express + Node.js)
Let's explore the backend now. For the server and database, we'll use Node.js, Express, and MongoDB. JWT will also be used to manage user authentication.
1. Set up dependencies
Installing the necessary packages—jsonwebtoken
, bcryptjs
(for hashing passwords), and dotenv
(for environment variables) is necessary before you can begin.
npm install jsonwebtoken bcryptjs dotenv
2. Create JWT Utility Functions
We’ll need a couple of utility functions: one to sign the JWT and another to verify it.
const jwt = require('jsonwebtoken');
// Generate token (to be called after registration or login)
const generateToken = (user) => {
return jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
};
3. Create Registration and Login Routes
Let's now configure the login and registration pathways. We will hash a user's password upon registration and provide a JWT in the response. The login route will return a JWT after verifying that the user's credentials are correct.
const bcrypt = require('bcryptjs');
// Registration route
app.post('/api/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
// Save user to the database
const user = { id: 1, username }; // Simulated database user creation
const token = generateToken(user);
res.json({ token });
});
For login, we’ll verify the user’s credentials and send the JWT if they’re valid.
// Login route
app.post('/api/login', async (req, res) => {
const { username, password } = req.body;
const user = { id: 1, username, password: 'hashedPassword' }; // Simulated database lookup
if (bcrypt.compareSync(password, user.password)) {
const token = generateToken(user);
res.json({ token });
} else {
res.status(401).send('Invalid credentials');
}
});
4. Protecting Routes with JWT Middleware
To protect routes that require authentication, we need a middleware that checks for a valid JWT.
const authenticate = (req, res, next) => {
const token = req.header('Authorization')?.split(' ')[1]; // Extract token from the Authorization header
if (!token) {
return res.status(401).send('Access denied');
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded; // Attach user info to the request
next();
} catch (err) {
res.status(400).send('Invalid token');
}
};
// Protect a route
app.get('/api/protected', authenticate, (req, res) => {
res.send('This is a protected route');
});
Using Postman to Test the Authentication
After configuring the backend, let's use Postman to test the authentication process.
1. Create an account
We must test the register endpoint first.
Approach: POST
Raw JSON body:
{ "username": "user1", "password": "password123" }
Once the user is registered, the server will respond with a JWT. Copy the token that’s returned in the response.
2. Log In and Get a JWT
Next, test the login endpoint.
Method: POST
Body (raw JSON):
{ "username": "user1", "password": "password123" }
You will receive a JWT back in the response if the credentials are accurate.
3. Take a Protected Path
Let's try gaining access to a protected route now that we have a JWT.
Approach: GET
Headers:
Authorization
:Bearer <your_jwt_token_here>
The protected route needs to respond to you if the token is valid. You'll get an error if the token is invalid or missing.
Protecting Your Application
Take into account these extra actions to improve the security of your application:
Use HTTPS:
Always use HTTPS to encrypt your data. This guarantees that the JWT is sent across the network securely.Set Token Expiration:
JWTs need to have a time limit. This guarantees that users won't remain logged in indefinitely.Refresh Tokens:
Use refresh tokens to automatically renew access tokens without requiring the user to log in again for increased security.
In Conclusion
An effective method of managing user sessions is to incorporate JWT authentication into your MERN stack application. You can use Postman to test your app's secure, stateless authentication by following the above steps. The best part is that you can get started without a frontend thanks to Postman, which allows you to test the complete process from protected routes to registration.
Congratulations if you followed the instructions and created your own JWT authentication! You've just given your app a crucial security boost. Please feel free to leave a comment below if you have any questions or encounter any problems!
This version should be helpful for developers working in a backend-focused environment because it is more hands-on with Postman and concentrates on testing JWT authentication without a frontend.
Subscribe to my newsletter
Read articles from Habibur Rahman directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Habibur Rahman
Habibur Rahman
Hi! I’m an aspiring Full-Stack Web Developer currently pursuing my Bachelor of Computer Applications (LPU). With a solid foundation in C++, Data Structures & Algorithms, and a growing skill set in web technologies.