Deploying Express Application to Vercel
Step 1: Create a folder for the project and deployment
mkdir deploy_expressjs_vercel
cd deploy_expressjs_vercel
Step 2: Initialized the express application and install express
npm init -y
npm i express
Project Structure
The updated dependencies in package.json file will look like :
"dependencies": {
"express": "^4.18.2"
}
Step 3: Create a folder structure similar to instructed and add the following files in respective directories.
JavaScript
// server.js const express = require( "express" ); const app = express(); // A simple get greet method app.get( "/greet" , (req, res) => { // get the passed query const { name } = req.query; res.send({ msg: `Welcome ${name}!` }); }); // export the app for vercel serverless functions module.exports = app; |
JavaScript
// /api/index.js const app = require( "../server.js" ); module.exports = app; |
JavaScript
// vercel.json { "rewrites" : [ { "source" : "/(.*)" , "destination" : "/api" } ] } |
HTML
<!-- public/index.html --> < html > < head > < title >Welcome</ title > </ head > < body > < h1 >This is a express app deployed in vercel</ h1 > </ body > </ html > |
Note:
- In Vercel, we don’t need to call the listen() of express to listen for incoming requests, everything will be internally run by Vercel serverless functions, so we just need to export our express.
- You don’t need to add the below line in the server.js to host the public files from express, vercel will take care of it.
app.use(express.static("public"))
- The vercel.json redirect every source request to “/api” serverless function where our express is actually exported.
Step 4: Install Vercel CLI & Login
npm install --global vercel
vercel login
vercel whoami
Step 5: Deploy Express App to Vercel by running the following command.
vercel
Incase you need to redeploy after making changes use the vercel command with prod flag.
vercel --prod
Output: Now run the deployed link on the browser.
How to Deploy an Express Application to Vercel ?
Vercel is a popular cloud platform that is known for its excellent support in building and deploying scalable Frontend infrastructure. In this article, we will look into how to deploy an Express.js web Application to Vercel. We will use the Serverless computing feature of Vercel to deploy our express.js application.