How to Setup a MERN App Locally - MongoDB, Express, React, NodeJS - Part 1
Introduction
In this multi-part tutorial we’ll show you how to setup a basic MERN application on your locally. The MERN stack is composed MongoDB, Express, React, and NodeJS. MongoDB is the database technology, Express is a Javascript framework that assists in easily creating routes, React is the front-end framework, and NodeJS allows you to run JavaScript on your backend server. This is an increasingly common stack and we hope this tutorial can get you started with a simple app that you can build learn from or build into the app you’re envisioning.
Prerequisites
- You should have NodeJS installed. Node comes with the node package manager (npm) which we’ll also need to install our packages.
- You should have MongoDB installed and running. Articles about the install process are easy to follow and after it’s installed you can typically start MongoDB with the
mongod
command which runs the Mongo Daemon. - Some command line experience is recommended.
Setup a MERN App Locally Part 1
Initializing the Project
First you’ll want to create a new directory for your new application. We’ll put our new app in a directory called 313-Demo-MERN
.
1 | mkdir 313-Demo-MERN |
Now we’ll initialize the project with the node package manager which will manage our dependencies (all the helper libraries we install).
1 | npm init |
It will prompt you with a few questions, but you can accept most of the defaults by just pressing enter. The only default we changed was to change the entry point to server.js. Below is what our terminal screen looked like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. See `npm help json` for definitive documentation on these fields and exactly what they do. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (313-demo-mern) version: (1.0.0) description: entry point: (index.js) server.js test command: git repository: keywords: author: license: (ISC) About to write to /Users/alexthompson/Google Drive/(OR01) Object Rocket - MASTER/300-399/313-Demo-MERN/package.json: { "name": "313-demo-mern", "version": "1.0.0", "description": "", "main": "server.js\t", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "author": "", "license": "ISC" } Is this OK? (yes) yes |
Install dependencies
Now we’ll install some of the dependencies we’ll be using with npm. We’ll be installing body-parser, express, mongoose, and concurrently. We’ll detail what each of these packages do after we show the command to install them.
1 | npm install body-parser concurrently express mongoose |
- The body-parser package is a middleware that parses request bodies.
- The express package allows us to create routes in an extremely simple way.
- The mongoose library lets us interact with MongoDB.
- The concurrently library lets us run our backend and frontend on different ports without having to open two terminals and run them separately.
You should receive a response indicating success something similar to below:
1 2 3 4 5 6 7 | ... + body-parser@1.19.0 + concurrently@4.1.0 + express@4.16.4 + mongoose@5.5.7 added 144 packages from 90 contributors and audited 2531 packages in 6.093s found 0 vulnerabilities |
Install nodemon as a Dev Dependency
Next we’ll install the nodemon package which will monitor our files for changes and restart our server when we make any changes. This will make our development process much easier, otherwise after every change you’d have to stop and restart the server.
1 | npm install nodemon --save-dev |
You should see some response indicating a successful install.
1 2 3 4 | ... + nodemon@1.19.0 added 291 packages from 145 contributors and audited 2236 packages in 9.052s found 0 vulnerabilities |
At this point your package.json should resemble the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | { "name": "313-demo-mern", "version": "1.0.0", "description": "", "main": "server.js\t", "scripts": { "test": "echo "Error: no test specified" && exit 1" }, "author": "", "license": "ISC", "devDependencies": { "nodemon": "^1.19.0" }, "dependencies": { "body-parser": "^1.19.0", "concurrently": "^4.1.0", "express": "^4.16.4", "mongoose": "^5.5.7" } } |
Start MongoDB
If you don’t already have MongoDB running you’ll need to run it by using the following command in the Terminal:
1 | mongod |
You should see a response indicating that MongoDB is waiting for connections on the default port of 27017:
1 2 3 4 5 | ✘ alexthompson@Matts-MBP ~/Google Drive/(OR01) Object Rocket - MASTER/300-399/313-Demo-MERN mongod ... 2019-05-12T19:55:33.880-0500 I CONTROL [initandlisten] 2019-05-12T19:55:34.063-0500 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data' 2019-05-12T19:55:34.067-0500 I NETWORK [initandlisten] waiting for connections on port 27017 |
Setup your Server with Express
Our next task is to finally start working on our server which is our entry point, server.js
. Let’s take a look at the code and then dissect what it does later.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | const express = require("express"); const mongoose = require("mongoose"); const bodyParser = require("body-parser"); // Setup express app const app = express(); app.use( bodyParser.urlencoded({ extended: false }) ); app.use(bodyParser.json()); // Configure Mongo const db = ""mongodb://localhost/313-demo-mern-db"; // Connect to Mongo with Mongoose mongoose .connect( db, { useNewUrlParser: true } ) .then(() => console.log("Mongo connected")) .catch(err => console.log(err)); // Specify the Port where the backend server can be accessed and start listening on that port const port = process.env.PORT || 5000; app.listen(port, () => console.log(`Server up and running on port ${port}.`)); |
- First we require all the libraries that we will be using.
- Then we setup an app through express and assign it to the
app
variable. - Next, we configure the app to accept json requests.
- Then we specify the uri where we can connect to find mongo
mongodb://localhost/313-demo-mern-db
. Notice we’ve tacked on what we want to our database name to be. When we connect to Mongo it will create the database once we’ve inserted data. - Next we use Mongoose to connect to Mongo passing in the uri.
- Lastly we set the port and start listening for requests on that port. For now since we are running
server.js
locally the port will be 5000. If you decide to push to a service like Heroku it will use whatever port is in theprocess.env.PORT
variable.
These steps are very common for most apps that are built using Express.
Let’s test that we can start our server using the following command. ( You should be in the same folder as the server.js
file)
1 | node server.js |
You should see the following console logs in your terminal if everything is successful:
1 2 | Server up and running on port 5000. Mongo connected |
Continued in Part 2
We still have some work to do setting up some routes and actually writing data to MongoDB but we’ll leave that for Part 2 of this tutorial. In this first part of the tutorial we have gone through how to setup your project folder, install the packages we need with npm, setup MongoDB, and start your server running. Please continue on to Part 2 of this tutorial where we’ll create routes that will create and retreive data from our database. If you have any questions so far please don’t hesitate to reach out to us.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started