DEV Community

Cover image for Deploying a Node.js + Express Server to Vercel Using the CLI
Anik Deb Nath
Anik Deb Nath

Posted on

Deploying a Node.js + Express Server to Vercel Using the CLI

Deploying your Node.js, Express, and MongoDB backend to Vercel is an excellent way to make your application accessible to users worldwide. Vercel offers a simple, serverless, and high-performance deployment platform that integrates seamlessly with the Node.js ecosystem.

In this blog, you'll learn how to deploy your backend server to Vercel using the command line, step-by-step.

Prerequisites

  • Node.js and npm installed on your machine.
  • A Vercel account. Sign up here.
  • Vercel CLI installed globally on your system.
  • A MongoDB instance, either locally or on a cloud provider like MongoDB Atlas.

Step 1: Install Vercel CLI

First, install the Vercel CLI globally:

npm install -g vercel
Enter fullscreen mode Exit fullscreen mode

Verify the installation:

vercel --version
Enter fullscreen mode Exit fullscreen mode

Step 2: Prepare Your Node.js Application

Folder structure

  • app.js: Defines your Express app.
  • server.js: Handles the server setup.
  • .env: Contains sensitive information like your MongoDB connection string

Step 3: Configure Your vercel.json File

Create a vercel.json file in the root of your project(where package.json file in include) to configure your deployment.

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

Enter fullscreen mode Exit fullscreen mode
  • builds: Specifies which file to use for the build.
  • routes: Redirects all traffic to the server.js file.

Step 4: Build Your Application First

Build your application without any error. If any kind of error is occured , remove it then build your application.

npm run build
Enter fullscreen mode Exit fullscreen mode

Step 5: Deploy Your Application

vercel
Enter fullscreen mode Exit fullscreen mode

During deployment Vercel detects your server.js file as the entry point. Environment variables like MONGO_URI are injected automatically.

Step 6: Verify Your Deployment

After the deployment is complete, you'll get a URL like:
Domain: https://your-project-name.vercel.app

Step 7: Update Your Code

To redeploy updated code:

vercel --prod
Enter fullscreen mode Exit fullscreen mode

Conclusion

You've successfully deployed your Node.js + Express + MongoDB server to Vercel using the command line! Vercel makes it incredibly simple to host backend applications, thanks to its serverless capabilities and ease of use.

If you encounter any issues, consult the Vercel documentation or leave a comment below. Happy coding! 🚀

[Anik Deb Nath]

Top comments (0)