How do you protect routes in a MERN application?

The Best Full Stack MERN Training Institute in Hyderabad with Live Internship Program

If you're looking to build a successful career in web development, Quality Thought is the top destination in Hyderabad for Full Stack MERN (MongoDB, Express.js, React, Node.js) training. Known for its industry-oriented curriculum and expert trainers, Quality Thought equips students with the skills needed to become job-ready full stack developers.

Our MERN Stack training program covers everything from front-end to back-end development. You'll start with MongoDB, a powerful NoSQL database, move on to Express.js and Node.js for back-end development, and master React for building dynamic and responsive user interfaces. The course structure is designed to offer a perfect blend of theory and hands-on practice, ensuring that students gain real-world coding experience.

What sets Quality Thought apart is our Live Internship Program, which allows students to work on real-time industry projects. This not only strengthens technical skills but also builds confidence to face real development challenges. Students get direct mentorship from industry experts, and experience the workflow of actual development environments, making them industry-ready.

We also provide complete placement assistance, resume building sessions, mock interviews, and soft skills training to help our students land high-paying jobs in top tech companies.

Join Quality Thought and transform yourself into a skilled MERN Stack Developer. Whether you're a fresher or a professional looking to upskill, this course is your gateway to exciting career opportunities in full stack development.

Enroll now and take the first step toward becoming a certified MERN stack professional with hands-on internship experience!

🔹 1. Protecting Routes on the Backend (Express)

The backend is the most important place to secure routes, since anyone can bypass the frontend.

✅ Middleware for JWT Authentication

// middleware/auth.js const jwt = require("jsonwebtoken"); function authenticateToken(req, res, next) { const authHeader = req.headers["authorization"]; const token = authHeader && authHeader.split(" ")[1]; // "Bearer <token>" if (!token) return res.status(401).json({ message: "Access Denied" }); jwt.verify(token, "secretKey", (err, user) => { if (err) return res.status(403).json({ message: "Invalid Token" }); req.user = user; // attach user info next(); }); } module.exports = authenticateToken;

✅ Protect a Route

// server.js const express = require("express"); const authenticateToken = require("./middleware/auth"); const app = express(); app.get("/api/protected", authenticateToken, (req, res) => { res.json({ message: "Welcome! You accessed a protected route.", user: req.user }); }); app.listen(5000, () => console.log("Server running on 5000"));

Now only requests with a valid JWT token can access /api/protected.

🔹 2. Protecting Routes on the Frontend (React)

✅ Store Token

After login, store the JWT in localStorage or a secure HTTP-only cookie.

localStorage.setItem("token", response.token);

✅ Create a ProtectedRoute Component

// ProtectedRoute.js import { Navigate } from "react-router-dom"; function ProtectedRoute({ children }) { const token = localStorage.getItem("token"); return token ? children : <Navigate to="/login" />; } export default ProtectedRoute;

✅ Use in React Router

// App.js import { BrowserRouter, Routes, Route } from "react-router-dom"; import ProtectedRoute from "./ProtectedRoute"; import Dashboard from "./Dashboard"; import Login from "./Login"; function App() { return ( <BrowserRouter> <Routes> <Route path="/login" element={<Login />} /> <Route path="/dashboard" element={ <ProtectedRoute> <Dashboard /> </ProtectedRoute> } /> </Routes> </BrowserRouter> ); } export default App;

🔹 3. Extra Security Enhancements

  • ✅ Use HTTP-only cookies for storing JWTs (safer than localStorage).

  • ✅ Add role-based authorization in middleware (e.g., admin-only routes).

  • ✅ Always use HTTPS in production.

  • ✅ Implement token expiry + refresh tokens.

🔑 Summary

  • Backend: Secure routes with JWT middleware in Express.

  • Frontend: Hide/protect UI routes with React Router ProtectedRoute.

  • Together: React prevents unauthorized navigation, Express ensures actual security.

Read More :

Visit  Quality Thought Training Institute in Hyderabad       

Comments

Popular posts from this blog

Describe a project you built using MERN stack.

What are mocks and spies in testing?

What is the difference between process.nextTick() and setImmediate()?