OrganicOPZ Logo
MERN JWT Authentication

How to Use JWT for Secure User Authentication in MERN Stack

Protect your full-stack applications with JSON Web Tokens for scalable and stateless authentication

Securing your web application is non-negotiable. With MERN stack development services, JSON Web Tokens (JWT) provide a clean, stateless solution for authenticating users between the frontend and backend. In this post, we’ll show you how to implement JWT authentication using Node.js, Express, MongoDB, and React.

1. Install Dependencies on the Backend

You'll need bcrypt for password hashing and jsonwebtoken to generate and verify tokens.

npm install bcryptjs jsonwebtoken

2. Create a User Model with Mongoose

// models/User.js
import mongoose from "mongoose";
import bcrypt from "bcryptjs";

const UserSchema = new mongoose.Schema({
  name: String,
  email: { type: String, unique: true },
  password: String,
});

UserSchema.pre("save", async function (next) {
  if (!this.isModified("password")) return next();
  const salt = await bcrypt.genSalt(10);
  this.password = await bcrypt.hash(this.password, salt);
});

export default mongoose.model("User", UserSchema);

3. Generate a JWT Token on User Login

// routes/auth.js
import jwt from "jsonwebtoken";

const login = async (req, res) => {
  const { email, password } = req.body;
  const user = await User.findOne({ email });
  const isMatch = await bcrypt.compare(password, user.password);
  if (!isMatch) return res.status(401).json({ error: "Invalid credentials" });

  const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, {
    expiresIn: "1h",
  });

  res.json({ token, user: { name: user.name, email: user.email } });
};

4. Protect Backend Routes with Middleware

Use this middleware to decode and verify JWTs on protected routes.

// middleware/auth.js
import jwt from "jsonwebtoken";

const auth = (req, res, next) => {
  const token = req.headers.authorization?.split(" ")[1];
  if (!token) return res.status(401).json({ error: "No token provided" });

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch {
    return res.status(403).json({ error: "Invalid token" });
  }
};

export default auth;

5. Handle JWTs in React

  • Store token in localStorage or httpOnly cookie (recommended for security)
  • Use axios.interceptors to attach token on each request
  • Build context or Redux slice to handle auth state
// axios setup
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem("token")}`;

6. Implement Refresh Tokens (Optional)

For high-security apps, implement refresh tokens stored in secure cookies, and access tokens with short expiry.

  • Access Token: Short-lived, stored in memory or header
  • Refresh Token: Long-lived, stored in secure, httpOnly cookie
  • Use `/refresh-token` endpoint to renew access tokens

Conclusion

JWT-based authentication in MERN stack applications provides a scalable, stateless, and secure way to manage user sessions. With proper token management, middleware protection, and frontend integration, your app is well-guarded against unauthorized access. This pattern is ideal for SaaS apps, dashboards, and mobile API services powered by MERN stack development services.

OrganicOpz - Your One-Stop Solution

Offering a range of services to help your business grow

Whether you need video editing, web development, or more, we're here to help you achieve your goals. Reach out to us today!

Discover Custom Solutions

Get Personalized Assistance

At OrganicOpz, We Specialize In Crafting Tailored Strategies To Elevate Your Online Presence. Let's Collaborate To Achieve Your Digital Goals!

Get In Touch!

Share Your Idea Or Requirement — We’ll Respond With A Custom Plan.

+91-9201477886

Give Us A Call On Our Phone Number For Immediate Assistance Or To Discuss Your Requirements.

contact@organicopz.com

Feel Free To Reach Out To Us Via Email For Any Inquiries Or Assistance You May Need.

Working Hours

Our Standard Operating Hours Are From 4:00 To 16:00 Coordinated Universal Time (UTC).

Chat with Us