Deploy Node API (Express Typescript) on Vercel
Tags: express, typescript, vercel, node
Published: 2022-11-16 14:12:21

A couple of weeks back, I developed an API in Node based on Typescript. I tried to deploy it on Heroku.

But the process was long and time-consuming. Also, I noticed that Heroku is terminating free accounts from 28 Nov'22. ☹️


![Heroku](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/655kqvp273f7483woars.png)

So I tried to experiment with various other platforms to deploy my Typescript-based Node API. Amon them free, robust, and versatile platform I found is VERCEL. Based on my experience, here are a few simple steps which you can follow and easily deploy Typescript-based Node API on Vercel. 🚀

<hr />

### 1) Express + Typescript Boilerplate App ✏️
Create express project with typescript. You can follow the below-mentioned steps to make a boilerplate for the project. (Github repo link is provided at end of article)

- Initialize node project
<br />

    ```bash
    npm init -y
    ```
<br />
- Install packages (you can use npm/yarn/pnpm)
<br />
    ```bash
    yarn add express
    yarn add -D typescript
    yarn add -D @types/node
    yarn add -D @types/express
    yarn add -D nodemon
    yarn add -D ts-node
    ```
<br />
- Create `tsconfig.json`
    To work with typescript we need to make tsconfig.json file which will help to compile and build Typescript files in plain JS. Execute below command
<br />
    ```bash
    npx tsc --init --rootDir src --outDir build --esModuleInterop --resolveJsonModule --lib es6 --module commonjs --allowJs true --noImplicitAny true
    ```
<br />
    Once the file is created you can keep it as is, or cleanup non necessary stuff. Replace content of `tsconfig.json` with following :
<br />
```json
    {
    "compilerOptions": {
        "module": "commonjs",
        "esModuleInterop": true,
        "allowSyntheticDefaultImports": true,
        "target": "es6",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": ["node_modules/*", "src/types/*"]
        }
    },
    "include": ["./src/**/*"]
    }
```
<br />
- Update `scripts` in `package.json`
<br />
    ```json
    "start": "nodemon src/index.ts",
    ```
<br />
- Write express server code : Create file : `src/index.ts` and paste following code in it
<br />
  ```typescript
  import express, { Request, Response } from 'express'

  const app = express()
  const port = process.env.PORT || 8080

  app.get('/', (_req: Request, res: Response) => {
  	return res.send('Express Typescript on Vercel')
  })

  app.get('/ping', (_req: Request, res: Response) => {
  	return res.send('pong 🏓')
  })

  app.listen(port, () => {
  	return console.log(`Server is listening on ${port}`)
  })
  ```
<br />
- Spin up server : Run `yarn start` or `npm run start` command in terminal to start express serve. You can open browser and go to `localhost:8080`. API will return response of `Express Typescript on Vercel`.

<hr />


### 2) Initialize git in our project. 📥

- Make a `.gitignore` file in the root of the folder. And add `node_modules` to it. If .gitignore file exists check that `node_modules` is added into it.
- Execute `git init` in the terminal (from root of project) or you can use VS Code's source control tab to initialize git repository.
- Connect local repo to remote (github/bitbucket). You can use any of the version control system to publish your repository.

<hr />

### 3) Create Vercel project 🗃️

- Go to vercel.com -> Login
- Login using the Version control platform you have kept your repository.
- From the dashboard -> Add new project -> Select your repository -> Deploy

- Afer deployment you will see something similar to this! 😟 


![Vercel Error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73euzi3stnat1mhc1wp3.png)
(ERROR 🚨)

- Don't worry... Just follow on steps to fix it. 👍

   <hr />

### 4) Add Vercel config in app ⚙️

- In the above step, after your fist deploy is completed, you can see that we're not getting `Express Typescript on Vercel` response from API.
- To work this as expected, we need to tell Vercel that is a API and you need to serve this as a serverless function.
- For this, simply we need to add `vercel.json` file in root of our project. Paste below code in file.
<br />
```json
{
	"version": 2,
	"builds": [
		{
			"src": "dist/index.js",
			"use": "@vercel/node",
			"config": { "includeFiles": ["dist/**"] }
		}
	],
	"routes": [
		{
			"src": "/(.*)",
			"dest": "dist/index.js"
		}
	]
}
```
<br />
**NOTE:** Check your tsconfig.json file. The value against `outDir` must be kept instead of `dist`. If your config file has any other value than `dist`, replace it at either of both places.

<hr />

### 5) Add a `pre-commit` hook 🏷️

- Vercel requires plain JS source files instead of Typescript. In order to do this, we need to build the project before committing and send compiled JS files so that Vercel can parse those files and serve the API.

- Install `pre-commit` and `rimraf` package :
<br />
  ```bash
  yarn add -D pre-commit
  yarn add -D rimraf
  ```
<br />
- Modify `scripts` field in `package.json` file as follows:
<br />
  ```json
  "scripts": {
  "start": "nodemon src/index.ts",
  "build": "rimraf dist && tsc",
  "ts.check": "tsc --project tsconfig.json",
  "add-build": "git add dist",
  "test": "echo \"Error: no test specified\" && exit 1"
  },
  ```
<br />
- Add new field `pre-commit` field in `package.json` :
<br />
  ```json
  "pre-commit": [
      "ts.check",
      "build",
      "add-build"
  ]
  ```
<br />
- What this will do? &#8594; Whenever you will commit, the commands written in pre-commit will be executed. It will check Typescript errors, build the project and add build folder to the staged changes. (If you opt for manual build, don't forget to run build command to start build.)

### 5) Re-Deploy and Re-Check API 🔁

- Commit the changes you have made and push the commit to GitHub. Check on vercel for the new deployment. Vercel will automatically trigger a new deployment on every push. Incase it is not started, you can manually start a deployment.

- Once new deployment is live, you can copy the deploy URL and run in browser. You will see `Express Typescript on Vercel` as a API response. Hurrah 😃


![API working](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c4q74fyx0yt39jo16igh.png)

- To assure that API is working perfectly, you can also hit `/ping` route which will return `pong 🏓` as the response.


![Ping Pong response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odazv7ld1icmq3gj793u.png)



### Closing comments 🙋‍♂️
- Thank you for following steps with me. Incase you find any issue in above mentioned steps, please ping in comment.
- Also a humble request you to write which topic you want in my next blog. I will include that in my target list. 🎯
- Github repo link for this project : [Express Typescript Code](https://github.com/tirth-2001/express-typescript-vercel-part2)

<br />
Tirth Patel, signing off! 🫡