Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Home Community How do you handle authentication in a MERN stack app?

How do you handle authentication in a MERN stack app?

Coding Now Expert  •  Jun 13, 2026  •  248 views
The standard approach uses JWT (JSON Web Tokens):

**Flow:**
1. User logs in → sends email + password to Express
2. Express validates credentials against MongoDB
3. If valid → generates JWT and sends to React
4. React stores JWT (localStorage or httpOnly cookie)
5. React includes JWT in Authorization header for protected requests
6. Express middleware verifies JWT on each protected route

**Backend (Express):**
```javascript
// Login route
app.post('/api/login', async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if (!user || !bcrypt.compareSync(req.body.password, user.password))
return res.status(401).json({ error: 'Invalid credentials' });
const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '7d' });
res.json({ token });
});
```

**Security best practices:**
- Use httpOnly cookies (not localStorage) to prevent XSS
- Short expiry + refresh tokens
- Hash passwords with bcrypt (cost factor 12+)
- HTTPS only
0

0 Answers

Your Answer

Will not be displayed publicly
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →