5 Simple Steps for Authentication and Authorization in MERN Stack
Before we begin, Your support by clapping and leaving comments greatly influences my work. Additionally, if you’re interested in receiving a complimentary Full Stack Career consultation session every weekend, you can extend your support through PATREON.
Prerequisites
Before we dive into the implementation, make sure you have the following prerequisites in place:
- A MERN stack application with MongoDB, Express.js, React, and Node.js set up.
- Basic knowledge of user authentication concepts, such as JWT (JSON Web Tokens) and password hashing.
Authentication
1. User Registration
To allow users to create accounts in your MERN application, create an API endpoint that handles user registration. When a user signs up, their password should be securely hashed before storing it in the database.
Here's an example of a registration route in Express.js:
javascriptCopy code
// routes/auth.js
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const bcrypt = require('bcrypt');
// Registration endpoint
router.post('/register', async (req, res) => {
try {
const { username, email, password } = req.body;
// Hash the password before saving it
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, email, password: hashedPassword });
await user.save();
res.status(201).json({ message: 'Registration successful' });
} catch (error) {
res.status(500).json({ error: 'Registration failed' });
}
});
2. User Login
Implement a login endpoint that checks the user's credentials and generates a JWT token upon successful login.
javascriptCopy code
// routes/auth.js
const jwt = require('jsonwebtoken');
const secretKey = 'your-secret-key';
// Login endpoint
router.post('/login', async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user) {
return res.status(401).json({ error: 'Authentication failed' });
}
const passwordMatch = await bcrypt.compare(password, user.password);
if (!passwordMatch) {
return res.status(401).json({ error: 'Authentication failed' });
}
// Create a JWT token
const token = jwt.sign({ userId: user._id, email: user.email }, secretKey, {
expiresIn: '1h',
});
res.status(200).json({ token, userId: user._id });
} catch (error) {
res.status(500).json({ error: 'Authentication failed' });
}
});
Authorization
1. Protecting Routes
To secure routes in your MERN application, use middleware to verify the JWT token in incoming requests. Here's an example middleware for protecting routes:
javascriptCopy code
// middleware/check-auth.js
const jwt = require('jsonwebtoken');
const secretKey = 'your-secret-key';
module.exports = (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
const decodedToken = jwt.verify(token, secretKey);
req.userData = { userId: decodedToken.userId, email: decodedToken.email };
next();
} catch (error) {
return res.status(401).json({ error: 'Authentication failed' });
}
};
2. Using Protected Routes
Apply the check-auth
middleware to routes that require authentication. For example:
javascriptCopy code
// routes/protected.js
const express = require('express');
const router = express.Router();
const checkAuth = require('../middleware/check-auth');
// A protected route
router.get('/profile', checkAuth, (req, res) => {
// Access user data through req.userData
res.json({ message: 'You are authenticated' });
});
module.exports = router;
if you have any questions or suggestions just do let me know on my Instagram or at codeculturepro@gmail.com