DEV Community

Nadim Chowdhury
Nadim Chowdhury

Posted on • Edited on

How to Build a Full-Stack Web App with the MERN Stack

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:

Step 1: Setting Up the Backend (Node.js & Express.js)

  1. Create a new project directory and navigate into it:
   mkdir mern-app
   cd mern-app
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a Node.js project:
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install required dependencies:
   npm install express mongoose cors dotenv jsonwebtoken bcryptjs passport passport-jwt
Enter fullscreen mode Exit fullscreen mode
  1. 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}`));
Enter fullscreen mode Exit fullscreen mode
  1. 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));
Enter fullscreen mode Exit fullscreen mode
  1. Set up a .env file for environment variables:
   MONGO_URI=your_mongodb_connection_string
   JWT_SECRET=your_jwt_secret
Enter fullscreen mode Exit fullscreen mode

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.

  1. 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);
Enter fullscreen mode Exit fullscreen mode
  1. 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;
Enter fullscreen mode Exit fullscreen mode

OAuth Authentication

OAuth allows users to log in using third-party services like Google or Facebook.

  1. Install required dependencies:
   npm install passport-google-oauth20
Enter fullscreen mode Exit fullscreen mode
  1. 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
   }));
Enter fullscreen mode Exit fullscreen mode
  1. 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'
   }));
Enter fullscreen mode Exit fullscreen mode

Step 3: Integrating Authentication in the Frontend

  1. Modify src/App.js to include login/logout functionality using JWT or OAuth.

Step 4: Deploying the MERN App

  1. Deploy the backend to platforms like Heroku, Render, or Railway.
  2. Deploy the frontend using Vercel or Netlify.
  3. 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.

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more