Embrace the Power of the Cloud: Deploying a MERN Stack Application with Vercel
Naveen Bantu
Posted on July 1, 2023
Introduction
Welcome to the dynamic realm of web development, where businesses strive to establish their digital presence. In this age of innovation, one stack has distinguished itself from the competition, captivating developers with its ability to produce robust web apps.
Say hello to the MERN stack!!!, the unbeatable combination of MongoDB, Express.js, React.js, and Node.js. This tech quartet empowers developers to craft feature-rich applications that seamlessly merge scalability and efficiency.
However, building a MERN stack application is only one part of the equation. Deploying it to a production environment can be a daunting task, requiring careful configuration and management.
Vercel to the rescue. Vercel is a cloud platform that simplifies the deployment and hosting process, making it an ideal choice for MERN stack applications.
In this blog post, we will explore the seamless experience of deploying a MERN stack application using Vercel. We'll discuss:
- Benefits of using Vercel
- Preparing MERN stack application for Deployment
- Walk through the deployment process step-by-step
Why Choose Vercel?
Vercel provides a comprehensive platform for deploying modern web applications effortlessly. Here are a few reasons why it has gained immense popularity among developers:
Easy Setup:
- Vercel offers a straightforward setup process, allowing developers to deploy their MERN stack applications with just a few clicks.
- It eliminates the need for manual configurations and reduces the time required to get your application up and running.
Continuous Deployment:
- By enabling automatic deployments with Vercel, you can be sure that every change you push to your repository results in a fresh deployment.
- This enables a seamless and continuous delivery process, keeping your application up-to-date.
Scalability:
- Vercel harnesses the power of serverless functions and edge caching.
- Enables effortless scalability for MERN stack applications.
- Ensures optimal performance even under high traffic volumes.
Global CDN:
- Vercel provides a global content delivery network (CDN) that ensures your application is delivered quickly to users worldwide.
- This optimizes the user experience by reducing latency and improving overall performance.
Serverless Functions:
- The use of serverless functions allows for efficient handling of dynamic data processing and offloading heavy computation tasks.
Preparing MERN stack application for Deployment
Before deploying our app, let's make sure we have the right configurations in place. The following configuration steps are needed:
Step 1:
The backend folder should be renamed to "api" and the main js file should be named "index.js"
Step 2:
Every controller should be having a connection to the database. This is because each controller will be deployed as a Serverless function.
-
Inside "api" folder, create a "config" folder add "db.js" file with the following code.
import mongoose from "mongoose"; const connectDB = async () => { try { const conn = await mongoose.connect(process.env.MONGO_URI); console.log(`MongoDB Connected: ${conn.connection.host}`); } catch (error) { console.error(`Error: ${error.message}`); process.exit(1); } }; export default connectDB;
-
Import and call the "connectDB" in all the controller functions.
export const getMocks = async (req, res, next) => { // Connecting to mongoDB connectDB(); try { //...code block fetching the mocks } catch (error) { //...handling errors }
Step 3:
Create a "vercel.json" and add the following configuration.
{
"buildCommand": "cd client && yarn install && ./node_modules/vite/bin/vite.js build",
"outputDirectory": "client/dist",
"framework": "vite",
"rewrites": [
{
"source": "/api/(.*)",
"destination": "/api/index.js"
},
{ "source": "/(.*)", "destination": "/index.html" }
]
}
Break down of each configuration option:
- buildCommand: This option specifies the command to build the client-side application. In this case, the build command is:
cd client && yarn install && ./node_modules/vite/bin/vite.js build
- Changes the directory to the client folder
- Installs the required dependencies using yarn install
- Builds the application using the Vite build command.
- outputDirectory: This option determines the directory where the built application will be stored. In this case, it is set to
client/dist
, indicating that the built files will be placed in the client/dist folder.- framework: This option specifies the framework used by the application. In this configuration, the framework is set to
vite
, indicating that the application is built using Vite.- rewrites: This option defines a list of URL rewrite rules for routing requests. The rules are processed in the order they appear. In this configuration, there are two rewrite rules:
- The first rewrite rule specifies that any requests starting with
/api/
should be rewritten to/api/index.js
. This is commonly used to redirect API requests to serverless functions.- The second rewrite rule states that for any other requests
(/(.*))
, the destination should be/index.html
. This is typically used for client-side routing, where the application's main index.html file is served for all routes to allow the client-side router to handle the routing within the application.
Deployment Process with Vercel:
Following is a step-by-step guide to deploy your MERN stack application with Vercel:
Step 1: Sign up for a Vercel account. Then Log in to Vercel dashboard, click on the “Add New…” button, and select the “Project” category.
Step 2: Connect your MERN stack application repository to Vercel. (Vercel supports various version control systems like Git, GitHub, and GitLab)
- Select your Git repository and choose the branch you want to deploy.
Step 3: Configure your deployment settings.
- The framework and build settings are already configured in the "vercel.json" for your MERN stack application.
- Add all the environment variables, both "client" and "api" related.
MONGO_URI=<your-mongo-URI>
PORT=5050
CLERK_SECRET_KEY=<your-clerk-secret-key>
VITE_REACT_APP_CLERK_PUBLISHABLE_KEY=<your-clerk-public-key>
Step 4: Review and CLICK on the Deploy button.
Step 5: After successfully deploying the MERN application, the FINAL step is to add the Deployed URL as environment variable for the Client API calls.
VITE_REACT_API_URL=https://mockmeet-vercel.vercel.app/api
For example: In Mockmeet, we are using an Environment variable "VITE_REACT_API_URL" to connect the frontend to the API endpoints.
After adding the deployed URL as an environment variable, re-deploy your application.
Congratulations!🎊 Your MERN stack application will be up and running within a few minutes after deployment.
Posted on July 1, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.