How to deploy your Express.js app at Vercel
Figuring out how to deploy a backend on Vercel was a bit tough, primarily when most blogs and posts cover only old versions. so to save you time and headache of searching, here is how you can deploy it step by step
1- Create your Vercel account
Create your account on vercel.com or log in if you already have one existing
2- Create your super fancy Express API
Create your API like normal with all endpoints and everything, and test it just make sure you use relative import, so no fancy import path, sadly with typescript
My app mainly used typescript and express
Now, after your app is ready and working fine let add a few tweaks to make it deployable in Vercel
3- Export your express app object on app.ts
this is mostly how your app may look like or a bit different depending on routes and your configuration
require("dotenv").config();
import express from "express";
import helmet from "helmet";
import cors from "cors";
import compression from "compression";
import ChatRoute from "./router/chat.route";
import StripeRoute from "./router/stripe.route";
const app = express();
app.use(helmet());
app.use(cors());
app.use(compression());
app.use("/stripe", StripeRoute);
app.use(express.json());
app.use("/chat", ChatRoute);
app.get("/", (req, res) => {
res.json({ message: "pong" });
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
So what we need to do here is to remove the port and listen part and export the app directly so it will look like this
require("dotenv").config();
import express from "express";
import helmet from "helmet";
import cors from "cors";
import compression from "compression";
import ChatRoute from "./router/chat.route";
import StripeRoute from "./router/stripe.route";
const app = express();
app.use(helmet());
app.use(cors());
app.use(compression());
app.use("/stripe", StripeRoute);
app.use(express.json());
app.use("/chat", ChatRoute);
app.get("/", (req, res) => {
res.json({ message: "pong" });
});
export default app;
4- Create a api/index.ts
Is content going to be as the following
import app from "../src/app";
export default app;
5- Create a public folder
Just leave it empty, but git won’t know the folder is needed, so to solve that, we are going to create a .gitkeep file inside the public folder
6- Create the versel.json file in your root project
{ "rewrites": [{ "source": "/(.*)", "destination": "/api" }] }
Basically, we tell Vercel that every request that comes to the server is given it to api folder, which contains our app
7- Now time to deploy our app 🎉
Now after our app is ready and published in our Git Provider (Github, Gitlab, …) whatever you prefer
- Create a new project in Versel and give it a name
- Connect your Versel account to your git provider
- Choose your project
- Now we wait for the deployment to finish
- Bingo, it’s deployed 🎉🎉