How to create and deploy an Express.js app to Vercel?

Prerequisites

Creating an Express App

  • Run npm init -y to create a package.json file with default configuration.
  • Run git init to initialize a git repository.
  • Create a .gitignore file and write node_modules/ in it.
  • Install the express package using npm or yarn.
npm i express
  • Create an index.js file in the root folder.
  • Inside the index.js file add the following to create an express app.
const express = require('express');
const app = express();

app.listen(process.env.PORT || 3000);
  • Create a public folder and create an index.html file inside it.
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express.js on Vercel</title>
</head>
<body>
<h1>Express App Responded</h1>
</body>
</html>
app.use(express.static('public'))
  • Now, we will create a GET request handler and send the html file as a response.
//index.js
app.get('/', (req, res) => {
res.sendFile('index.html', {root: path.join(__dirname, 'public')});
})
  • Export the app for it to be run as a serverless function.
// index.js
module.exports = app
  • Add a start script to package.json file in order to run the application locally.
"start": "node index.js"
  • Run the application using the command npm start The application should be live at http://localhost:3000.
  • You should get an output similar to the following:
  • You just created your Express App 🎉

Deploying to Vercel

  • Create a vercel.json file in the root folder of your application. This is a configuration file for Vercel.
{
"builds": [
{
"src": "index.js",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "index.js"
}
]
}
  • Create a git repository on GitHub and add your code to it.
  • Create a new project on Vercel and import the git repository that you just made.
  • Deploy the application. That’s it. Your application should now be live!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store