Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Follow publication

Effortlessly Deploy Your MERN App with a Single Port Configuration on Vercel

Effortlessly Deploy Your MERN App with a Single Port Configuration on Vercel
Effortlessly Deploy Your MERN App with a Single Port Configuration on Vercel

When you’re building a MERN stack application, it’s common to organize your project into two folders: “client” and “server.” The “client” folder contains your React app, which typically runs on port 3000 by default. Meanwhile, the “server” folder contains your Node/Express app, which usually runs on port 5000.

When you’re ready to deploy your app, you’ll typically use a server like Nginx to handle these ports via reverse proxying. But wouldn't it be much better if we could run both Apps on a single port? By doing so, you would only need to deploy a single app instead of two separate ones, which could save you time and effort.

Prerequisites:

The only prerequisite is that you should have Node, NPM, and Git installed in your system. Now without wasting any time let's get started by creating our App:

Initialize React App:

First, we are going to create our React App using the CRA template. For this purpose open your favorite terminal and write the following code:

npx create-react-app <app-name>

Here, replace <app-name> with the name of the app you want to create. After completion open the folder in VS Code or your favorite editor. If you want to open VS Code using the same terminal use the following commands:

cd <app-name>
code .

After opening your folder structure will look like this:

The Folder Structure of the React App
The Folder Structure of the React App

Now without any waiting, we will run our App. For this purpose write the following in the terminal which will start our React App:

npm start

For the sake of simplicity, we will continue with the default template which looks like this and is accessible on localhost:3000.

React App Default Template
React App Default Template

As the last step for this run the following script in the terminal to create a production version of the app:

npm run build

This will build the React app and will add a new folder build at the root of the project.

Initializing Backend:

Now to keep things simple we will create a folder named server, open the terminal in that folder, and run the following command:

npm init -y
npm install express

Now in this folder add an app.js file and also create a routes folder with an index.js file in that folder. At last copy the build folder into the server directory so that the folder structure of the server looks like this:

Folder Structure
Folder Structure

Tweak your package.json and add the following script:

"dev": "node ./app.js",

Your package.json will look somewhat like this:

Example package.json
Example package.json

Now we would write some code for the backend! Go to the app.js file and paste the following code:

// app.js

// to create our express app
const express = require("express");
// package to handle file paths
const path = require("path");
// our custom routes
const appRoutes = require("./routes");

// initialize the express app
const app = express();

// set the port (you could use any but usually it is 5000)
const port = process.env.PORT || 5000;

// next two lines tells parse requests of content-type
// which are application/x-www-form-urlencoded and json respectively
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// to make build folder static
app.use(express.static(path.join(__dirname, "build")));

// appRoutes are the routes your backend will use
// by convention we use /api before any backend routes
app.use("/api", appRoutes);

// ...

// If user hits the / route we will be
// shown our react frontend app as we are
// returning the content of build folder
app.use((_, res) => {
res.sendFile(path.join(__dirname, "build", "index.html"));
});

// If user hits the route that donot exist
// we will shoe not found message
app.use((_, res) => {
res.status(404).json({
success: false,
message: "Not found!",
});
});

// Launch app to listen to specified port
app.listen(port, () => {
console.log(`Your server is running on Port: ${port}`);
});

Now add the following code to routes/index.js which will tell our backend API routes:

// routes/index.js

const { Router } = require("express");

const router = Router();

// handle get reuest on route /api/name
router.get("/name", (_, res) => {
return res.status(200).json({ name: "Farasat Ali" });
});

// handle get reuest on route /api/greet
router.get("/greet", (_, res) => {
return res.status(200).json({ greet: "Hello there!!" });
});

module.exports = router;

Now we are near completion. To run the Express App write the following script in the terminal:

npm run dev

This will run your Express App which you can visit on localhost:5000. When you open this in the browser you will see your React App running. In order to access API routes you can follow this pattern: localhost:5000/api/<route-name>. Here, in <route-name> you can replace the route names we made in routes/index.js which in our case translates to localhost:5000/api/name and localhost:5000/api/greet.

Now, if you want to access any of the API routes you can directly access it by using the following pattern: “/api/<route-name>”

Deploying on Vercel:

Before deploying we have one more step. Create a file named “vercel.json” at the root of the project and paste the following code:

{
"version": 2,
"builds": [
{
"src": "app.js",
"use": "@now/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "app.js"
}
]
}

Vercel is one of the best platforms when it comes to deploying MERN Apps because it automatically handles the routing. To deploy your app first push your repo to GitHub.

If you do not have an account on GitHub account first sign up and follow the instructions:

  1. In the repositories tab click “New”:
Step 1 — Add New Repository
Step 1 — Add New Repository

2. Now name your repository and click “Create repository”

Step 2 — Configure the Repository
Step 2 — Configure the Repository

3. Run the following commands on the terminal:

git add .
git commit -m "my commit"
git branch -M main
git remote add origin https://github.com/<github-username>/<repo-name>.git
git push -u origin main

After the push is successful your repository will look like this:

Repository on GitHub
Repository on GitHub

Now, we are ready to deploy. Go to vercel.com/new and use GitHub to sign in. Once you sign in you will see all your repositories. Click the one you want to deploy which leads you to the deployment page. On the deployment page, find the “Root Directory” Section and click “Edit” and select “server” and then click Deploy:

Vercel Deployment Screen
Vercel Deployment Screen

This will deploy your App on Vercel and you can visit your Live App.

Sign up to discover human stories that deepen your understanding of the world.

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Written by Farasat Ali

Tech Savvy 💖 Blockchain, Web & Artificial Intelligence. Love to travel, explore culture & watch anime. Visit My Portfolio 👇 https://linktr.ee/faraasat

Responses (1)

Write a response

haha its not working

--