How to Deploy an Express App on Vercel with MongoDB

Shejan Mahamud
4 min readMay 1, 2024

--

Copyright: Collected

Are you ready to take your Express app to the next level? In this tutorial, I’ll guide you through the process of deploying an Express.js application on Vercel while using MongoDB as the database. By the end of this tutorial, you’ll have your app up and running in a scalable and efficient environment.

Step -1: Setup your expressJS app

First things first, make sure you have an Express.js application ready to go. If you haven’t built one yet, you can quickly set up a basic Express app using the following steps:

  1. Initialize a new Node.js project: npm init -y
  2. Install Express.js: npm i express cors mongodb dotenv
  3. Install nodemon for better experence npm i -g nodemon
  4. Create an index.js file and set up your Express app.
  5. create a .env file

Here’s a simple example to get you started:

const express = require('express');
const cors = require('cors');
require('dotenv').config();
const port = process.env.PORT || 3000;

//middlewares
app.use(express.json());
app.use(cors());

//app
const app = express();

app.get('/', (req, res) => {
res.send('Hello from Express!');
});

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

and .env file example:

PORT = 7438

Now open your command prompt CTRL+J and type:

nodemon index.js

now go to your browser and navigate to localhost:7438 (running port) and your express server is ready:

Copyright: Shejan Mahamud

Step 2: Connect MongoDB to Your Express App

Next, you’ll need to connect your Express app to MongoDB. We already installed mongodb. Now integrate MongoDB into your Express app. Here’s an example of how you can do this:

Import MongoDB:

const mongoURI = process.env.MONGO_URI;
const { MongoClient, ServerApiVersion } = require("mongodb");
//mongo URI
const client = new MongoClient(mongoURI, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

and add your secret MongoDB URI to your .env

PORT = 7438
MONGO_URI = "MONGO_URI_FROM_MONGO_ATLAS"

Here is a tutorial how to get MongoURI from MongoDB Atlas.

Now your index.js will look like this after import function and uri from MongoDB Atlas:

const express = require('express')
const cors = require('cors');
require('dotenv').config();
const port = process.env.PORT || 5844;
const mongoURI = process.env.MONGO_URI;
const { MongoClient, ServerApiVersion } = require("mongodb");

//app
const app = express();

//middlewares
app.use(express.json());
app.use(cors());

//mongo URI
const client = new MongoClient(mongoURI, {
serverApi: {
version: ServerApiVersion.v1,
strict: true,
deprecationErrors: true,
},
});

const run = async () => {
try{
await client.connect();

await client.db("admin").command({ ping: 1 });
console.log(
"Pinged your deployment. You successfully connected to MongoDB!"
);
}
finally{

}
}

run().catch(error => console.log)

app.get('/',(req,res)=>{
res.send('Car Junction Backend Server Running...')
})

app.listen(port,()=>{
console.log(console.log(`Server is running on port ${port}`))
})

Now run again your app using nodemon index.js

Copyright: Shejan Mahamud

Successfully your app connected to MongoDB database.

Step 3: Deploy Your Express App on Vercel

Now that your Express app is ready and connected to MongoDB, it’s time to deploy it on Vercel. Follow these steps:

  1. Sign up for a Vercel account if you haven’t already.
  2. Install the Vercel CLI: npm install -g vercel
  3. Now on your root project create a file and name it vercel.json
{
"version": 2,
"builds": [
{
"src": "./index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "/",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
}
]
}

Paste this json code on your vercel.json

4. Navigate to your project directory in the terminal.

5. Run vercel login to log in to your Vercel account.

After login successfully with vercel cli now run vercel . it will ask you some question answer them with Y/N.

Once the deployment process is complete, Vercel will provide you with a unique URL for your deployed app.

Step 4: Configure Environment Variables

To ensure that your Express app can connect to MongoDB on Vercel, you’ll need to set up environment variables. Head to your Vercel dashboard and navigate to your project’s settings. Add environment variables for your MongoDB connection URI and any other sensitive information.

Step 5: Test Your Deployed App

Congratulations! Your Express app is now deployed on Vercel with MongoDB as the database. Visit the URL provided by Vercel to test your app and make sure everything is working as expected.

Note: If you make changes anything just run the command Run vercel --prod and follow the prompts to deploy your updated app.

That’s it! You’ve successfully deployed an Express.js application on Vercel with MongoDB. Now you can scale your app with ease and focus on building awesome features.

Conclusion: Deploying your Express.js application on Vercel with MongoDB is a straightforward process that enables you to host your app efficiently and securely. By following the steps outlined in this tutorial, you can ensure that your app is accessible to users and can scale as needed. With Vercel’s platform and MongoDB’s database capabilities, you have a powerful combination for hosting and managing your Express.js projects. Happy deploying & coding!

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

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Shejan Mahamud
Shejan Mahamud

Written by Shejan Mahamud

Aspiring web developer passionate about MERN stack. Eager to create innovative and user-friendly web applications.

No responses yet

Write a response