DEV Community

Ethern Myth
Ethern Myth

Posted on

Node.Js Express Typescript Deployment on Vercel

Just came across the web and tried to find good documentation on deploying Node.js Express Typescript to Vercel. It was not clear at all with my findings. Important instructions were missing, but I have customized some changes and got it to work in few minutes.

Create a vercel.json in the project root of your project if not existing already.

Add this code and change the src path according to your project setup.

{
"version": 2,
"builds": [
{
"src": "src/api/index.ts",
"use": "@vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "src/api/index.ts"
}
]
}

I had my project setup with src folder and added the api folder to the src folder.

Inside the api folder, I create an index.ts file.

The index.ts file has this code:

import cors from "cors";
import dotenv from "dotenv";
import bodyParser from "body-parser";
import compression from "compression";
import helmet from "helmet";
import express from "express";
import router from "../routes/prisma";

dotenv.config();

const app = express();
/*
Configurations
/
app.use(
cors({
origin: "
",
})
);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(compression());
app.use(helmet.crossOriginResourcePolicy({ policy: "cross-origin" }));
app.use("/api", router);
/*
Routes
/
app.all("
", (req, res) => {
res.status(400).json({ error: Route ${req.originalUrl} not found });
});

export default app;

The most import code here is to

export default app;

That way this becomes serverless just like Vercel Serverless functions.

The router defines the all routes for the api itself.

Since I am using Prisma and with addition of mongo backup, I structured the folders for every ORM the project support.

Last thing was to add this precious line to the package.json:

"vercel-build": "yarn generate",

This line, gets prisma to initialize the client and be of use to the whole project.

The "vercel-build" works for any build you wish to have when using node.

I hope this was clear in a way to help with deploying node express to Vercel as serverless.

Leave a comment for any information you need from this.

Great๐ŸŽ‰

Top comments (0)