DEV Community

Cover image for Deploying Node.js with TypeScript + MongoDB App on Vercel as a Serverless Function
Harish Soni
Harish Soni

Posted on

Deploying Node.js with TypeScript + MongoDB App on Vercel as a Serverless Function

Hello Devs,

We all have faced a situation where we need an end point API, which will perform as per our need but we were not able to find what we wanted.

So, here is one of many solutions I have used

Let's Deploy a Node.js Application on Vercel for free

Introduction

Security is a critical aspect of modern web applications. In this blog, we will walk through building a secure Node.js application using TypeScript, MongoDB, and JSON Web Token (JWT) authentication.

Prerequisites

  • Before we start, make sure you have the following installed:
  • Node.js (v18 or later)
  • MongoDB (local or cloud-based, e.g., MongoDB Atlas)
  • TypeScript
  • A code editor (VS Code recommended)

Project Setup:

mkdir node-app && node-app
npm init -y
npm install typescript ts-node @types/node --save-dev
npx tsc --init
Enter fullscreen mode Exit fullscreen mode

Modify the tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true
  },
  "include": ["./**"],
  "exclude": ["node_modules"]
} 
Enter fullscreen mode Exit fullscreen mode

Install the required packages:

npm install express mongoose jsonwebtoken bcryptjs dotenv cors
npm install --save-dev @types/express @types/jsonwebtoken @types/bcryptjs @types/cors
npm i -g nodemon
Enter fullscreen mode Exit fullscreen mode

From here we will go and create two routes for our app, and then we will deploy our app to vercel:

here is my index.ts file:

import express, { Express, Request, Response } from 'express';
import * as dotenv from 'dotenv';
import cors from 'cors';
import mongoose from "mongoose";


// Load environment variables from .env file
dotenv.config();

const app: Express = express();
const PORT= Number(process.env.PORT) || 3000;

// Connect to MongoDB

mongoose.connect(process.env.MONGO_URI as string)
    .then(() => console.log("MongoDB connected"))
    .catch(err => console.error("MongoDB connection error:", err));

// Middleware to parse JSON bodies
app.use(express.json());

// CORS configuration
app.use(cors());

// Basic route
app.get('/', (req: Request, res: Response) => {
  res.json({ message: 'Hello from TypeScript Express!' });
});

app.get('/health', (req: Request, res: Response) => {
  res.json({ message: 'Application Running' });
});

console.log(process.env);

// Start server
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

Create a .env file

PORT=5000
MONGO_URI=your_mongodb_connection_string
Enter fullscreen mode Exit fullscreen mode

Now on local run the following command:

nodemon index.ts
Enter fullscreen mode Exit fullscreen mode

It should result in

Server is running on port ${PORT}
Enter fullscreen mode Exit fullscreen mode

Let's Get to the interesting part now, deploying the application on Vercel

If you don't have any Vercel Account, login with Github then.

The main thing is to create the vercel config which will tell vercel how our application should behave:

  • Add vercel.json file in the root for the application:
{
  "version": 2,
  "builds": [
    {
      "src": "src/index.ts",
      "use": "@vercel/node"
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "src/index.ts"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode
  • Let's Create and deploy the app using our terminal:

vercel --prod

Once deployed you can connect your Vercel app to your Github Repo and deploy the code on each push on your desired branch.

Open your application Logs on vercel.com/{your_username}/{app_name}/logs
I have added more on my Github Repository for this here:

GIT: https://github.com/harish9312/node-vercel

BASE_URL: https://node-vercel-ts-mongo.vercel.app/

Open for corrections/suggestion do comment and share your feedbacks

Top comments (0)