BackendMERN StackMongoDBReactNode.jsTutorial

MERN Stack Tutorial: Build a Full-Stack App from Scratch

Step-by-step guide to building a complete MERN stack application — MongoDB, Express, React, and Node.js — with authentication and deployment.

Abdur Razzak

Abdur Razzak

Full-Stack Web Developer

February 7, 2024 12 min read

What Is the MERN Stack?

MERN stands for MongoDB, Express.js, React, and Node.js. Together, these four technologies cover the entire web stack: MongoDB is the database (NoSQL, document-based), Express.js is the backend web framework, React handles the frontend UI, and Node.js is the server runtime. The beauty of MERN is that everything is JavaScript — one language for the full stack.

Setting Up the Backend (Node + Express + MongoDB)

Start by creating your Express server: npm init -y, then install express, mongoose, dotenv, cors, and bcryptjs. Create a server.js file, connect to MongoDB using mongoose.connect(), and define your routes. Use Mongoose schemas to model your data — they provide type validation, defaults, and pre/post save hooks. Keep your routes thin and move business logic into service files.

Designing Your MongoDB Schema

MongoDB stores data as JSON-like documents. Design your schema based on how your application queries the data, not how you would normalize a relational database. For blog posts, you might embed tags and author info directly in the document rather than using separate collections. For user-post relationships with large data sets, use references (ObjectId) to keep documents small.

Building the React Frontend

Create a React app with Vite (recommended) or Create React App. Set up React Router for navigation, React Query or Redux Toolkit Query for data fetching and caching, and Axios or the native fetch API for HTTP requests. Organize components by feature — a users folder with UserList, UserCard, and UserForm components. Keep API calls in a dedicated api/ folder to separate concerns.

JWT Authentication Flow

On login, the backend validates credentials and returns a JWT access token and a refresh token. Store the access token in memory (not localStorage) and the refresh token in an httpOnly cookie. Use an Axios interceptor to attach the access token to every request header. When the access token expires, automatically request a new one using the refresh token. This pattern is secure against XSS and CSRF attacks.

Deploying the MERN App

Deploy the Node/Express backend to Render or Railway — both offer free tiers with automatic deploys from GitHub. Use MongoDB Atlas for the database (free M0 tier available). Deploy the React frontend to Vercel or Netlify. Set environment variables (MONGODB_URI, JWT_SECRET, CORS_ORIGIN) in your hosting platform's dashboard, never commit them to Git.

Share this article

All posts
#MERN Stack#MongoDB#React#Node.js#Tutorial
Abdur Razzak — Full Stack Web Developer

Full-Stack Expert

MERN · React · Next.js · WordPress