The MERN stack (MongoDB, Express.js, React, and Node.js) is one of the most popular full-stack development frameworks for building modern web applications. In this blog post, we will go through the steps to build a full-stack web app using MERN.
Prerequisites
Before we begin, ensure you have the following installed on your system:
- Node.js (https://nodejs.org/)
- MongoDB (https://www.mongodb.com/)
- A code editor (e.g., VS Code)
- Basic knowledge of JavaScript and React
Step 1: Setting Up the Backend (Node.js & Express.js)
- Create a new project directory and navigate into it:
mkdir mern-app
cd mern-app
- Initialize a Node.js project:
npm init -y
- Install required dependencies:
npm install express mongoose cors dotenv jsonwebtoken bcryptjs passport passport-jwt
- Create a
server.js
file and set up a basic Express server:
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const passport = require('passport');
require('dotenv').config();
const app = express();
app.use(express.json());
app.use(cors());
app.get('/', (req, res) => {
res.send('API is running');
});
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
- Connect to MongoDB using Mongoose:
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => console.log('MongoDB Connected'))
.catch(err => console.error(err));
- Set up a
.env
file for environment variables:
MONGO_URI=your_mongodb_connection_string
JWT_SECRET=your_jwt_secret
Step 2: Implementing Authentication (JWT vs OAuth)
JSON Web Token (JWT) Authentication
JWT is a widely used authentication method where a token is issued upon successful login and stored on the client side.
- Create a
User
model:
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
});
module.exports = mongoose.model('User', UserSchema);
- Set up authentication routes in
routes/auth.js
:
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const router = express.Router();
router.post('/register', async (req, res) => {
const { name, email, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({ name, email, password: hashedPassword });
await newUser.save();
res.json({ message: 'User registered successfully' });
});
router.post('/login', async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email });
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ message: 'Invalid credentials' });
}
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token });
});
module.exports = router;
OAuth Authentication
OAuth allows users to log in using third-party services like Google or Facebook.
- Install required dependencies:
npm install passport-google-oauth20
- Configure Google OAuth in
config/passport.js
:
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: '/auth/google/callback',
}, (accessToken, refreshToken, profile, done) => {
// Handle user authentication and store user in the database
}));
- Set up OAuth routes in
routes/auth.js
:
router.get('/google', passport.authenticate('google', { scope: ['profile', 'email'] }));
router.get('/google/callback', passport.authenticate('google', {
successRedirect: '/',
failureRedirect: '/login'
}));
Step 3: Integrating Authentication in the Frontend
- Modify
src/App.js
to include login/logout functionality using JWT or OAuth.
Step 4: Deploying the MERN App
- Deploy the backend to platforms like Heroku, Render, or Railway.
- Deploy the frontend using Vercel or Netlify.
- Update API endpoints in the frontend to use the deployed backend URL.
Conclusion
You now have an understanding of how to implement authentication in a MERN stack application using JWT and OAuth. Choose the method that best suits your project’s needs.
Support My Work ❤️
If you enjoy my content and find it valuable, consider supporting me by buying me a coffee. Your support helps me continue creating and sharing useful resources. Thank you!
Connect with Me 🌍
Let’s stay connected! You can follow me or reach out on these platforms:
🔹 YouTube – Tutorials, insights & tech content
🔹 LinkedIn – Professional updates & networking
🔹 GitHub – My open-source projects & contributions
🔹 Instagram – Behind-the-scenes & personal updates
🔹 X (formerly Twitter) – Quick thoughts & tech discussions
I’d love to hear from you—whether it’s feedback, collaboration ideas, or just a friendly hello!
Disclaimer
This content has been generated with the assistance of AI. While I strive for accuracy and quality, please verify critical information independently.
Top comments (0)