How to Host Express App on Vercel

April 3, 2021

Open GitHub repository

Disclaimer: Vercel configuration file uses legacy builds and routes properties.

Last week I needed to host a simple Express app somewhere, and I decided to host it on Vercel because of the excellent Developer Experience.

Here are the steps that I needed to do to make it possible:

First, we need to create a project directory. I decided to name it vercel-express and then change the directory to a newly-created directory.

Terminal
1# create a directory
2mkdir vercel-express
3
4# change directory
5cd vercel-express

Then we will initialize git and add the node_modules directory to .gitignore.

Terminal
1# initialize git
2git init
3
4# add the `node_modules` directory to `.gitignore`
5echo node_modules >> .gitignore

Next, we need to set up a new package. We are using the -y flag to skip the questionnaire.

Terminal
1npm init -y

Then we will create an index.js file and populate it.

Terminal
1# create a new `index.js` file
2touch index.js
index.js
1// ./index.js
2const express = require('express')
3
4const app = express()
5const port = 3000
6
7app.get('/', (req, res) => {
8 res.send('Hello, Vercel!')
9})
10
11app.listen(port, () => {
12 console.log(`Express app hosted on Vercel listening at port ${port}`)
13})

To run an express app, we need to create a custom vercel.json config file.

Terminal
1touch vercel.json
index.json
1// ./vercel.json
2{
3 "version": 2,
4 "builds": [
5 {
6 "src": "./index.js",
7 "use": "@vercel/node"
8 }
9 ],
10 "routes": [
11 {
12 "src": "/(.*)",
13 "dest": "/"
14 }
15 ]
16}

After populating the index.js and vercel.json files, we can stage all of the files and commit them.

Terminal
1git add -A && git commit -m "Initial commit"

If you want to change the name for the main branch from master to main, simply run the git branch -m master main command.

For pushing code to the existing repository, follow the following code.

Terminal
1git remote add origin https://github.com/LukasPolak/vercel-express.git
2git branch -M main
3git push -u origin main

The Vercel config file includes legacy properties, but it works like a charm when writing this. Maybe in the future, I will update the tutorial with the recommended properties.

Share this post on Twitter