DEV Community

Cover image for How to host Express app on Vercel
Lukas Polak
Lukas Polak

Posted on • Originally published at lukaspolak.com

How to host Express app on Vercel

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.

# create a directory
mkdir vercel-express

# change directory
cd vercel-express
Enter fullscreen mode Exit fullscreen mode

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

# initialize git
git init

# add the `node_modules` directory to `.gitignore`
echo node_modules >> .gitignore
Enter fullscreen mode Exit fullscreen mode

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

npm init -y
Enter fullscreen mode Exit fullscreen mode

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

# create a new `index.js` file
touch index.js
Enter fullscreen mode Exit fullscreen mode
// ./index.js
const express = require('express')

const app = express()
const port = 3000

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

app.listen(port, () => {
  console.log(`Express app hosted on Vercel listening at port ${port}`)
})
Enter fullscreen mode Exit fullscreen mode

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

touch vercel.json
Enter fullscreen mode Exit fullscreen mode
// ./vercel.json
{
  "version": 2,
  "builds": [
    {
      "src": "./index.js",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "/"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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

git add -A && git commit -m "Initial commit"
Enter fullscreen mode Exit fullscreen mode

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.

git remote add origin https://github.com/LukasPolak/vercel-express.git
git branch -M main
git push -u origin main
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)