MERN Stack - create & deploy the project on MDB GO

How to deploy & host MERN app - tutorial & free hosting

After reading this tutorial you will know how to create full-stack apps using MERN stack.


What does MERN stand for?

MERN is an acronym for web development tech stack consisting of these four technologies:

  • MongoDB
  • Express.js
  • React
  • Node.js

Let's quickly recall what are these.

MERN recap

Here's a quick recap what are the main technologies used in the MERN stack:

  • MongoDB is a document-oriented NoSQL database mernt to store non-tabular data. If you want to learn more about it check out a separate tutorial.
  • Express.js is a web framework built for Node.js that allows you to create web servers in a very convenient way. Learn more about it here.
  • React is a JavaScript framework that allows you to create very advanced single-page apps. You can check out how to create an React project in another tutorial.
  • Node.js is a multi-platform JavaScript runtime built on V8 engine. It's used as a backend side of web apps. Read more about it here.

We won't dive deep into details about how to get started with these technologies using MDB GO. Go ahead and check the linked tutorials and once you learn a few things get back here.

If you have enough knowledge to get started, let's do this.

Building the MERN app

Our example app will be a TODO list. It's a very popular use-case so let's simply get things done one at a time. We will go through the following steps:

  • Create a MongoDB database named todo_app
  • Create Node.js API with Express and Mongoose
  • Connect our frontend app to the Node.js API.

Let's go!

Creating MongoDB database

In order to create a new database you need to run the following command:


            $ mdb database init -db mongodb
          

Now you need to provide your user data and then the database details. Please provide the values of your choice. For example:

? Enter username tony
? Enter password Stark_12
? Repeat password Stark_12
? Enter database name todo_app
? Enter description Database for the TODO app

Note: the password must contain at least one uppercase letter, one lowercase letter, one number, one special symbol and have minimum length of 8.

Hit Enter and it's done.

Please notice that in the command output the username and database name slightly differs from what you provided earlier. Don't worry - it's OK. A few random characters have been added to these values to randomize them and improve security of your database credentials.

Important: Do not close your terminal window until you save your credentials somewhere. This is the only time we will show you your database password. If you won't save it you'll loose it.

That's pretty much it. You can now see how to connect with this database from the Node.js API.

Note: in MongoDB you don't need to create collections before they are used. MongoDB will create a collection when it's first time accessed.

Creating Node.js API with Express and Mongoose

In case you don't know, Mongoose is a MongoDB object modeling tool. It helps managing MongoDB access and models. You can initialize a MDB GO starter that already has configured Mongoose. Simply run the following command:


            $ mdb backend init
          

and choose Express.js + MongoDB API starter from the list that shows up.

After initialization just go to the newly created project directory and open the .env file. After that edit the DB_CONNECTION_STRING value. You should paste the connection string that's been shown to you in the previous step. In my case the updated value looks like this:

DB_CONNECTION_STRING=mongodb://tonye9c88223:Stark_12@mongo.db.mdbgo.com:8604/todo_appbd2f70e0

Save the file and close it.

The starter project is ready to use. You don't have to change anything to run the example app for the sake of this tutorial. Simply publish it using the following command:


            $ mdb publish -p node12
          

After your files get uploaded you can access your app under the address shown in the output.

Note: You may want to check the tutorial where we explain in detail what can go wrong here and how to deal with it.

Note: Since we need to install dependencies and run your app, it may take a few moments until it will be available under the provided URL.

When you open the app URL you will see the default view on the / endpoint but when you'll visit /tasks you will see an empty array indicating that the tasks collection has been created and is empty. There are also other endpoints defined like this:

  • GET /tasks/:id
  • POST /tasks
  • PUT /tasks/:id
  • DELETE /tasks/:id

These are self-explanatory but if you don't know how to operate on that go and check the tutorial where it is explained.

Alright, only one step left for the fully-working TODO app - React frontend. Let's create it.

Connecting to the API via React app

We won't show how to create the whole React app here. Instead, you'll learn how to connect to the API assuming you already have a working app.

It's actually pretty easy. All we need to use if JavaScript Fetch API. Let's jump right into it.

First, let's create our state. We are assuming you have the App.js file where you want to put API communication logic. Open this file and add the following state definition:


                import React, { Component } from 'react';

                class App extends Component {

                  state = {
                    tasks: []
                  }
                  // ...
                }
            

It's also wise to add apiUrl field in our class so that we don't have to repeat it every time:


                apiUrl = 'http://express-mongoose-starter.mdbgo.io'; // in your case it will be different
            

In order to read data from the server we need to make a GET /tasks request. You can do it like this:


                componentDidMount() {
                    fetch(`${this.apiUrl}/tasks`)
                        .then(res => res.json())
                        .then((data) => {
                          this.setState({ tasks: data })
                        })
                        .catch(console.log)
                }
            

We are utilizing the fetch function to read tasks from our API and then setting the state. Creating, updating and deleting tasks is just as easy:


                createTask() {
                  const data = { name: 'Wash the dishes', desc: 'will take a while' };
                  fetch(`${this.apiUrl}/tasks`, {
                      method: 'POST',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify(data);
                  })
                      .then((res) => res.json())
                      .then((task) => {
                          this.setState({ tasks: this.state.tasks.push(task) });
                      })
                      .catch(console.log);
                }

                updateTask() {
                  const currentTaskId = 1;
                  const data = { name: 'Wash the dishes', desc: 'will take a while' };
                  fetch(`${this.apiUrl}/tasks/${currentTaskId}`, {
                      method: 'PUT',
                      headers: { 'Content-Type': 'application/json' },
                      body: JSON.stringify(data);
                  })
                      .then((res) => res.json())
                      .then((task) => {
                          const oldTask = this.state.tasks.find((t => t.id === currentTaskId));
                          oldTask.id = updatedTask.id;
                          oldTask.name = updatedTask.name;
                          oldTask.desc = updatedTask.desc;
                      })
                      .catch(console.log);
                }

                deleteTask() {
                  const currentTaskId = 1;
                  fetch(`${this.apiUrl}/tasks/${currentTaskId}`, { method: 'DELETE' })
                      .then((res) => res.json())
                      .then(() => {
                          const tasks = this.state.tasks.splice(idx, 1);
                          this.setState({ tasks });
                      })
                      .catch(console.log);
                }
            

And that's how you communicate with your API from the React app.