Building a React App with a MongoDB Backend on AWS

Building a portable, scalable React web application with a MongoDB backend on AWS

In this tutorial, we will cover the steps to build a React app with a MongoDB backend on Amazon Web Services (AWS). We will use AWS services like Amazon EC2 and Amazon MongoDB Atlas to host the backend, and will deploy the React app to AWS Amplify.

Step 1: Setting up AWS EC2 instance

  1. Go to the AWS EC2 Console and create a new instance.
  2. Choose an Amazon Linux AMI.
  3. Select the instance type and configure the necessary settings.
  4. Create a new key pair to access the instance and launch the instance.

Step 2: Installing and Configuring MongoDB

  1. Connect to the AWS EC2 instance using ssh.
  2. Install MongoDB by running the following command: sudo yum install -y mongodb-org
  3. Start the MongoDB service: sudo service mongod start
  4. Connect to the MongoDB shell: mongo
  5. Create a database and a collection:
		​use mydb
​db.createCollection("mycollection")


Step 3: Connecting the React App to MongoDB Backend

  1. Create a new React app using npx create-react-app myapp
  2. Install the necessary dependencies: npm install axios mongodb
  3. Update the React code to connect to the MongoDB backend and display the data from the collection.
import React, { useState, useEffect } from "react";
import axios from "axios";

function App() {
const [data, setData] = useState([]);

useEffect(() => {
axios
.get("http://<aws_ec2_instance_public_dns>:27017/mydb/mycollection")
.then((res) => setData(res.data))
.catch((err) => console.log(err));
}, []);

return (
<div>
{data.map((item) => (
<p key={item._id}>{item.name}</p>
))}
</div>
);
}

export default App;


Step 4: Deploying the React App to AWS Amplify

  1. Install the AWS Amplify CLI: npm install -g @aws-amplify/cli
  2. Initialize the Amplify project: amplify init
  3. Add a new web app: amplify add hosting
  4. Deploy the app: amplify publish
  5. Access the app using the URL provided by Amplify.

Note: This tutorial is a basic example to get started with building a React app with a MongoDB backend on AWS. There are many other AWS services that can be used to improve the security, scalability, and performance of the app. You can easily get up and running with MongoDB, and mongo-express administration with 1-click on AWS.


Launch Mongo-Express on AWS Now

# AWS
Sign in to leave a comment
Setting up an AWS Application Load Balancer with EC2 and enabling SSL on a Web Server
Running a highly scalable web server on AWS with SSL