I will show you how to deploy your backend that uses Express and MongoDB on Vercel 👩🏼💻 (TypeScript)
First thing you need to know is that Vercel requires plain JS source files instead of TypeScript. So, you need to build the project and send the compiled JS files so that Vercel can parse them and serve the API.
- To initialize TypeScript configration file.
npx tsc --init- You need to update your scripts in package.json file, and add those lines
"ts-watch": "tsc -w",
"start": "nodemon dist/api/index.js",
"build": " dist && tsc",- Run
tsc -wcommand to initialize dist folder. The dist folder will hold all the compiled JS files. - Build the server and run it. I used ( nodemon ).
- Build your routers and controllers and connect them with mongoDB.
- You need to install dotenv. Create the .env file in the root directory and import it in the index.ts.
import 'dotenv/config'
- Inside the .env file, put your URI for MongoDB and make sure to name the environment variable
MONGODB_URI, because, mentioned in the MongoDB documentation,MONGODB_URIserves as the Atlas cluster's connection string for all Vercel projects that you link this cluster to.
- Do not forget to carete a .gitignore file. Ignore node_modules and .env files and DO NOT ignore ❗
dist❗ folder.
- Build the project to make sure the dist folder is updated, then run it in development mode to test your server. If everthing works fine ✅, we can move on to the next and most important steps.
🔸 You can use Postman to test the HTTP requests.
- Add
vercel.jsonfile in the root directory.
{
"version": 2,
"builds": [
{
"src": "dist/api/index.js",
"use": "@vercel/node",
"config": { "includeFiles": ["dist/api/**"] }
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/api/index.js"
}
]
}- Publish your project to GitHub.
- Create a Vercel project and import the repository.
- Add the environment variables and deploy.
- Go to the Vercel dashboard and select Integrations, then selcet MongoDB.
- Follow the steps from here Connect mongoDB to vercel & Partner integrations.
- Test the requests.
- Copy your backend URL and paste it in your frontend 🎉🎉
ℹ️ Notes
- Make sure when you import in your TypeScript files to do it like this:
import { home } from "../controllers/homeController.js";
with the .js extenstion and { }.However, in index.ts (the server file) use this: import homeRouter from '../src/routers/homeRouter.js';
without { }.
- Make sure that your
tsconfig.jsonfile includes"outDir": "./dist". - Sometimes you need to Reconnect with the database or Re-deploy in Vercel.
- You can deploy your project using Vercel commands Vercel deploy commands.
📁 You can check the files in the repo for more details.


