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.
You'll need bcrypt for password hashing and jsonwebtoken to generate and verify tokens.
npm install bcryptjs jsonwebtoken
// 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);
// 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 } }); };
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;
localStorage
or httpOnly
cookie (recommended for security)axios.interceptors
to attach token on each request// axios setup axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem("token")}`;
For high-security apps, implement refresh tokens stored in secure cookies, and access tokens with short expiry.
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.
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
At OrganicOpz, We Specialize In Crafting Tailored Strategies To Elevate Your Online Presence. Let's Collaborate To Achieve Your Digital Goals!
Share Your Idea Or Requirement — We’ll Respond With A Custom Plan.
Give Us A Call On Our Phone Number For Immediate Assistance Or To Discuss Your Requirements.
Feel Free To Reach Out To Us Via Email For Any Inquiries Or Assistance You May Need.
Our Standard Operating Hours Are From 4:00 To 16:00 Coordinated Universal Time (UTC).