
Deploy Your First MERN App on AWS: A Beginner-Friendly Guide
A step-by-step walkthrough for taking a MERN app from localhost to AWS using EC2, S3, and CloudFront, with the mistakes beginners commonly make and how to avoid them.
Your app works perfectly on
localhost:3000 . Then someone asks, "Can you send me the link?" Suddenly, you realize that building an application and deploying it are two completely different skills.As a full-stack developer, I've learned that getting an application to work locally is only one part of the journey. Making it accessible to other people introduces a new set of challenges: servers, databases, networking, security, and cloud costs.
When I started exploring AWS, I wanted a deployment guide that explained not just what to do, but why I was doing it.
This article is my attempt to create that guide.
We'll deploy a MERN application using a simple architecture, explain each component in beginner-friendly language, and cover the mistakes that can make deployment frustrating.
By the end, you'll understand how to:
- Host a React frontend using Amazon S3 and CloudFront.
- Run a Node.js and Express backend on Amazon EC2.
- Connect your backend to MongoDB Atlas.
- Configure HTTPS, CORS, and environment variables.
- Monitor your AWS spending and avoid unnecessary charges.
The architecture: What are we actually building?
Before opening the AWS Console, let's understand where each part of our application will live.
Application component | Service | Purpose |
|---|---|---|
React frontend | Amazon S3 | Stores the production build files |
Frontend delivery | Amazon CloudFront | Delivers content globally over HTTPS |
Node.js + Express backend | Amazon EC2 | Runs the application server |
MongoDB database | MongoDB Atlas | Stores application data |
Reverse proxy | Nginx | Forwards requests to Express |
Think of your application as a restaurant.
- S3 is the menu: It stores the static files customers need to see.
- EC2 is the kitchen: It processes requests and performs application logic.
- MongoDB Atlas is the pantry: It stores the data your application needs.
- CloudFront is the delivery network: It helps your frontend reach users efficiently.
<IMAGE_PLACEHOLDER: A clean AWS MERN architecture diagram showing Browser → CloudFront → Private S3 React Frontend; Browser → HTTPS → Nginx on EC2 → Node.js Express API → MongoDB Atlas. Include security boundaries and arrows.>
Step 0: Secure your AWS account before deploying
This is the step beginners often skip, but it should be the first one.
AWS provides powerful infrastructure. Misconfigured resources or exposed credentials can result in unexpected charges or security problems.
Before launching anything:
- Enable Multi-Factor Authentication (MFA) on your AWS root account.
- Avoid using the root account for everyday development.
- Prefer IAM Identity Center or an appropriately restricted IAM identity for daily access.
- Create an AWS Budget and configure email alerts.
- Never upload AWS credentials, private keys, or
.envfiles to GitHub.
For a beginner, I recommend setting a small budget alert, such as $5, as an early warning. Remember that a budget alert is a notification, not a hard spending limit.
AWS Free Tier eligibility and pricing can vary by account, service, and region. Check the current pricing before launching resources.
Step 1: Launch your backend on Amazon EC2
Amazon EC2 provides a virtual machine where we can run our Express server.
1. Create an EC2 instance
Open the AWS Console and navigate to:
EC2 → Instances → Launch instance
Choose:
- Name:
mern-backend
- Operating system: Ubuntu
- Instance type: A small instance eligible for your account's current pricing
- Key pair: Create a new key pair and download the
.pemfile
- Storage: Keep the default unless your application requires more
2. Configure the Security Group
A Security Group works like a firewall for your EC2 instance.
Configure the inbound rules carefully:
Type | Port | Source |
|---|---|---|
SSH | 22 | My IP |
HTTP | 80 | 0.0.0.0/0 |
HTTPS | 443 | 0.0.0.0/0 |
Do not expose SSH to the entire internet unless you have a specific reason and appropriate safeguards.
3. Connect to your instance
From a terminal on your computer:
chmod 400 your-key.pem
ssh -i your-key.pem ubuntu@YOUR_EC2_PUBLIC_IPReplace the placeholders with your actual key filename and EC2 public IP address.
4. Install Node.js
We'll use NVM to install and manage Node.js.
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
source ~/.bashrc
nvm install --lts
node -vnpm -v5. Clone your backend project
git clone https://github.com/your-username/your-backend.git
cd your-backend
npm installCreate your environment configuration:
nano .envExample:
PORT=5000MONGO_URI=your_mongodb_connection_stringJWT_SECRET=your_long_random_secretUse your actual secrets. Never commit this file to your repository.
At this point, your backend code is on the EC2 instance.
Step 2: Keep Express running using PM2
If you start your server using:
node server.jsand close your terminal, the process may stop.
PM2 is a process manager that helps keep your application running and restarts it if the process crashes.
Install PM2:
npm install -g pm2Start your backend:
pm2 start server.js --name my-apiConfigure PM2 to start automatically after a reboot:
pm2 startupRun the additional command PM2 prints, then:
pm2 saveCheck the application:
pm2 statusView logs:
pm2 logs my-apiThis is a simple way to manage an application on a small EC2 server. It does not guarantee uninterrupted uptime, but it helps with process recovery.
Step 3: Configure Nginx as a reverse proxy
Our Express application is running on port 5000.
However, users normally access websites through HTTP or HTTPS rather than directly through an application port.
Nginx acts as a reverse proxy. It receives incoming requests and forwards them to Express.
Install Nginx:
sudo apt update
sudo apt install nginx -yOpen the default configuration:
sudo nano /etc/nginx/sites-available/defaultInside the existing
server block, configure the location:location / { proxy_pass http://127.0.0.1:5000;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;}Test the configuration:
sudo nginx -tIf the configuration is valid:
sudo systemctl restart nginxNow visit:
http://YOUR_EC2_PUBLIC_IP/If your Express application has a route configured for
/ , you should receive its response.If your API does not have a root route, you may see a 404. That does not necessarily mean the deployment failed. Test an actual API endpoint such as
/api/health .Important: To serve your application securely over HTTPS, configure a domain name and TLS certificate. Do not leave your production API dependent on plain HTTP.
Step 4: Connect MongoDB Atlas
Instead of installing MongoDB directly on EC2, we'll use MongoDB Atlas.
Atlas manages the database infrastructure, allowing us to focus on application development.
Setup
- Create a MongoDB Atlas account.
- Create a cluster using an available plan.
- Create a database user with a strong password.
- Configure Network Access.
- Add your EC2 server's stable public IP address to the IP access list.
- Copy your MongoDB connection string.
Your
.env file should contain:MONGO_URI=mongodb+srv://username:password@cluster-url/databaseMake sure the username and password are URL-encoded if they contain special characters.
Restart your application:
pm2 restart my-apiCheck the logs:
pm2 logs my-apiIf the connection fails, check the MongoDB username, password, network access list, and connection string.
Avoid using
0.0.0.0/0 for MongoDB access unless you're intentionally accepting access from all IP addresses and have appropriate security controls.Step 5: Deploy React using Amazon S3 and CloudFront
Now let's deploy the frontend.
Amazon S3 stores the built React files. CloudFront distributes them to users and provides HTTPS.
1. Build your React application
On your local computer, open your frontend project.
npm install
npm run buildDepending on your React setup:
- Vite creates a
distdirectory.
- Create React App creates a
builddirectory.
These directories contain the production-ready frontend files.
2. Create an S3 bucket
Navigate to:
Amazon S3 → Create bucket
Choose a globally unique bucket name.
Keep Block Public Access enabled. We want the bucket to remain private.
Upload the contents of your production build folder.
Do not upload the entire project source code unnecessarily.
3. Create a CloudFront distribution
Navigate to:
Amazon CloudFront → Create distribution
Configure:
- Origin: Your S3 bucket
- Origin access: Origin Access Control (OAC)
- Viewer protocol policy: Redirect HTTP to HTTPS
- Default root object:
index.html
Configure the S3 bucket policy so that the CloudFront distribution is allowed to read the required objects.
This allows users to access your frontend through CloudFront without making the S3 bucket public.
4. Fix React Router refresh errors
This is one of the most common problems beginners face.
Suppose your React application contains:
/ /login /dashboard /profileYou open
/dashboard directly or refresh the page.S3 looks for an actual object at that path. Since the route is handled by React Router rather than a physical file, S3 may return a 403 or 404.
To handle this:
- Open your CloudFront distribution.
- Navigate to its error response configuration.
- Create custom error responses for 403 and 404.
- Set the response page path to
/index.html.
- Set the response code to 200.
- Save the configuration and wait for deployment.
This allows the React application to load and handle the route.
Be aware that this approach can also turn genuine missing-file errors into the frontend page, so test your asset URLs and routing after deployment.
5. Access your frontend
CloudFront provides a URL similar to:
https://d1234abcd.cloudfront.netYour frontend is now accessible over HTTPS.
Step 6: Connect the React frontend to the backend
Now comes the exciting part: connecting both sides of your application.
Your frontend might be hosted at:
https://d1234abcd.cloudfront.netYour backend might be hosted at:
https://api.yourdomain.comThe frontend needs to call the backend using the correct API URL.
For example, in your React application:
const API_URL = "https://api.yourdomain.com";
fetch(`${API_URL}/api/users`) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));Avoid hardcoding production URLs throughout your application. Use environment variables provided by your frontend build tool.
Fix CORS errors
CORS stands for Cross-Origin Resource Sharing.
If your frontend and backend use different origins, your Express backend must allow the frontend's origin.
Install CORS:
npm install corsConfigure it:
const cors = require("cors");
app.use(cors({ origin: "https://d1234abcd.cloudfront.net"}));Replace the example URL with your actual frontend domain.
For production, allow only the origins you need. If you're using cookies for authentication, additional configuration is required, including credentials and appropriate cookie settings.
Fix mixed-content errors
A browser may block an HTTPS frontend from calling an HTTP backend.
For example:
Frontend: HTTPSBackend: HTTPThe solution is to configure HTTPS on the backend as well.
You can use a domain name, Nginx, and a TLS certificate from Let's Encrypt, or choose another suitable AWS architecture.
Do not solve this by disabling browser security.
Step 7: Monitor your AWS costs
Deployment is not complete just because your application is working.
Cloud resources can continue generating charges even when you're not actively using them.
Here are a few things I recommend checking:
- AWS Budgets: Configure alerts for your expected spending.
- EC2: Check instance usage and storage.
- CloudFront: Monitor data transfer and requests.
- S3: Review storage usage.
- Elastic IP: Check whether allocated public IPv4 addresses are still needed.
- MongoDB Atlas: Review your selected plan and usage.
AWS charges for public IPv4 addresses, including addresses associated with running instances. Elastic IPs are not automatically free. Check current pricing before allocating one.
If you're experimenting with deployment, make a habit of reviewing your resources and deleting anything you no longer need.
Common beginner mistakes
Mistake | What to do instead |
|---|---|
Opening SSH to everyone | Restrict port 22 to your IP |
Committing .env files | Keep secrets outside Git |
Making S3 public | Use private S3 with CloudFront OAC |
Forgetting PM2 startup | Configure PM2 startup and save the process list |
Using HTTP for production APIs | Configure HTTPS |
Ignoring CORS | Allow the correct frontend origin |
Forgetting React Router refresh | Configure CloudFront SPA error responses |
Ignoring AWS bills | Configure budget alerts and review usage |
Debugging without logs | Use PM2 and Nginx logs |
When something goes wrong, don't randomly change settings.
Start by identifying which component is failing.
- Frontend issue? Check the browser console.
- API issue? Check PM2 logs.
- Nginx issue? Check the Nginx error log.
- Database issue? Check the Atlas connection settings.
- AWS permission issue? Review IAM and resource policies.
A systematic approach saves a lot of debugging time.
Where to go next
Once you successfully deploy your first MERN application, you can gradually improve your architecture.
Here are a few ideas:
- GitHub Actions: Automate frontend and backend deployments.
- Docker: Package your backend into a consistent environment.
- Amazon ECS: Explore container-based deployment.
- AWS Elastic Beanstalk: Simplify application deployment and management.
- Amazon CloudWatch: Monitor application logs and metrics.
- Route 53: Connect a custom domain to your application.
- AWS Secrets Manager: Manage sensitive application credentials more securely.
You don't need to learn everything at once. Start with one improvement and understand why it is useful.
Final thoughts
When I started working on full-stack applications, I thought the main challenge was writing the frontend and backend code.
But deployment taught me something different.
Writing an application is about making it work. Deploying an application is about making it accessible, secure, reliable, and maintainable.
AWS can initially feel overwhelming because it has so many services. However, once you understand the purpose of each component, the process becomes much easier to follow.
For a beginner, the most important thing is not to build the most advanced architecture on day one. It is to understand the fundamentals, deploy something small, and learn from the errors you encounter along the way.
I'm still learning and exploring cloud technologies as I continue my full-stack development journey. I hope this guide makes the first deployment a little less intimidating for someone else.
What was the most confusing part of your first deployment?
Was it configuring EC2, connecting the database, fixing CORS, or understanding AWS billing?
I'd love to hear your experience in the comments. Your answer might help another developer who is facing the same problem.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article