How to Host Nodejs on Vercel

How to Host Node.js on Vercel Node.js has become the backbone of modern web development, enabling developers to build fast, scalable server-side applications using JavaScript. While traditionally deployed on dedicated servers, cloud platforms like AWS, Heroku, or DigitalOcean, Vercel has emerged as a powerful alternative—especially for developers seeking seamless deployment, automatic scaling, and

Nov 10, 2025 - 12:43
Nov 10, 2025 - 12:43
 1

How to Host Node.js on Vercel

Node.js has become the backbone of modern web development, enabling developers to build fast, scalable server-side applications using JavaScript. While traditionally deployed on dedicated servers, cloud platforms like AWS, Heroku, or DigitalOcean, Vercel has emerged as a powerful alternativeespecially for developers seeking seamless deployment, automatic scaling, and global CDN delivery. But theres a common misconception: Vercel is only for frontend frameworks like React, Next.js, or Vue. The truth? Vercel now fully supports Node.js applications through its Serverless Functions and Edge Runtime, making it possible to host full-stack Node.js apps with minimal configuration.

This guide provides a comprehensive, step-by-step walkthrough on how to host Node.js applications on Vercelwhether youre running a simple API, a backend service, or a full-stack application with custom server logic. Well cover everything from project setup and configuration to optimization, debugging, and real-world use cases. By the end, youll understand why Vercel is not just an option, but a compelling choice for hosting Node.js in 2024 and beyond.

Step-by-Step Guide

Prerequisites

Before you begin, ensure you have the following tools installed and configured:

  • Node.js (v18 or higher recommended)
  • npm or yarn for package management
  • Git for version control
  • Vercel account (free tier available at vercel.com)
  • A code editor (VS Code, Sublime, or similar)

Youll also need a basic understanding of JavaScript, Express.js (or similar frameworks), and REST APIs. While not mandatory, familiarity with serverless architecture concepts will help you grasp the deployment model.

Step 1: Create a Basic Node.js Application

Start by initializing a new Node.js project in your terminal:

mkdir my-nodejs-app

cd my-nodejs-app

npm init -y

Install Express, a minimal and flexible Node.js web application framework:

npm install express

Create a file named server.js in the root directory:

const express = require('express');

const app = express();

const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {

res.json({ message: 'Hello from Node.js on Vercel!' });

});

app.get('/api/users', (req, res) => {

res.json([{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]);

});

app.listen(PORT, () => {

console.log(Server running on port ${PORT});

});

module.exports = app;

This is a minimal Express server with two endpoints: one for the root route and another for fetching users. Note that were using module.exports = appthis is critical for Vercel compatibility.

Step 2: Configure Vercel for Node.js

Vercel doesnt natively run traditional Node.js servers like Express in a persistent environment. Instead, it converts your application into serverless functions. To make this work, you need to tell Vercel how to handle your Node.js app.

Create a vercel.json file in the root of your project:

{

"version": 2,

"builds": [

{

"src": "server.js",

"use": "@vercel/node"

}

],

"routes": [

{

"src": "/(.*)",

"dest": "server.js"

}

]

}

Lets break this down:

  • "version": 2 Uses Vercels latest configuration schema.
  • "builds" Tells Vercel to treat server.js as a Node.js function using the @vercel/node builder. This builder wraps your Express app into a serverless function compatible with Vercels runtime.
  • "routes" Maps all incoming requests (/(.*)) to your server file. This ensures every route you define in Express is handled correctly.

Important: Do not use app.listen() in production on Vercel. Vercel handles the server lifecycle. Your app should export the Express instance, and Vercel will invoke it via HTTP requests.

Step 3: Update package.json Scripts

Add a start script to your package.json for local testing:

{

"name": "my-nodejs-app",

"version": "1.0.0",

"main": "server.js",

"scripts": {

"start": "node server.js",

"dev": "nodemon server.js"

},

"dependencies": {

"express": "^4.18.2"

}

}

If you want live reloading during development, install nodemon:

npm install --save-dev nodemon

Now test locally:

npm start

Visit http://localhost:3000 and http://localhost:3000/api/users to verify your API works.

Step 4: Initialize Git Repository

Vercel deploys directly from Git repositories. Initialize a Git repo and commit your files:

git init

git add .

git commit -m "Initial commit with Node.js server and Vercel config"

Step 5: Deploy to Vercel

Go to https://vercel.com/new and sign in with your GitHub, GitLab, or Bitbucket account.

Select the repository you just created. Vercel will automatically detect your vercel.json file and configure the build settings:

  • Framework Preset: Select Other (since this is a custom Node.js app)
  • Build Command: Leave blank (Vercel doesnt need to build anything)
  • Output Directory: Leave blank

Click Deploy. Vercel will:

  • Clone your repository
  • Install dependencies via npm install
  • Package your server.js as a serverless function
  • Deploy it to Vercels global edge network

Within seconds, youll see a live URL like https://my-nodejs-app-xyz.vercel.app. Visit it to confirm your API is live!

Step 6: Test and Debug

After deployment, test all endpoints:

To debug issues, go to your Vercel project dashboard, click on the deployment, and check the Logs tab. Youll see real-time output from your serverless function, including errors, console logs, and response times.

Step 7: Add Environment Variables

For secrets like API keys, database URLs, or JWT secrets, use Vercels environment variables.

In your Vercel dashboard, go to your project ? Settings ? Environment Variables. Add keys like:

  • DB_URL ? mongodb://localhost:27017/mydb
  • JWT_SECRET ? your-super-secret-key-here

In your server.js, access them using process.env.DB_URL:

const dbUrl = process.env.DB_URL || 'mongodb://localhost:27017/mydb';

// Use dbUrl in your MongoDB connection

Environment variables are encrypted and injected at build timenever commit them to your repository.

Step 8: Handle Static Files (Optional)

If your Node.js app serves static assets (e.g., HTML, CSS, images), place them in a folder like public/ and serve them using Express:

app.use(express.static('public'));

Ensure your vercel.json still routes everything to server.js. Vercel will serve static files directly via CDN when possible, falling back to your serverless function for dynamic routes.

Best Practices

Use Serverless Functions Efficiently

Vercels Node.js support is built on serverless functions, which have cold start delays and execution timeouts (up to 10 seconds on the free plan, 15 minutes on Pro). Optimize your code to:

  • Initialize database connections and heavy imports outside of request handlers
  • Avoid long-running processes or blocking operations
  • Use async/await properly to prevent blocking the event loop

Example of good practice:

const express = require('express');

const app = express();

// Initialize outside handler

const db = require('./db'); // Connect once on cold start

app.get('/users', async (req, res) => {

try {

const users = await db.getUsers(); // Async, non-blocking

res.json(users);

} catch (err) {

res.status(500).json({ error: err.message });

}

});

module.exports = app;

Optimize Dependencies

Every dependency in your package.json increases deployment size and cold start time. Remove unused packages. Use npm prune to clean up. Consider splitting large apps into multiple microservices (e.g., one for API, one for auth) to reduce bundle size per function.

Use Edge Functions for High-Performance APIs

For lightweight, low-latency endpoints (e.g., authentication checks, redirects, or simple data fetching), consider using Vercel Edge Functions instead of Node.js serverless functions. Edge Functions run on Vercels global edge network using Deno and have near-instant cold starts.

To use Edge Functions, create a file like api/auth.js with:

export default function (req) {

const token = req.headers.get('Authorization');

if (token === 'Bearer my-secret') {

return new Response('OK', { status: 200 });

}

return new Response('Unauthorized', { status: 401 });

}

Edge Functions are ideal for stateless logic. Reserve Node.js functions for complex business logic requiring NPM packages or databases.

Enable Caching Strategically

Use Vercels built-in caching for static assets and API responses. Add cache headers in your Express routes:

app.get('/api/users', (req, res) => {

res.set('Cache-Control', 'public, max-age=300'); // Cache for 5 minutes

res.json([{ id: 1, name: 'Alice' }]);

});

This reduces load on your serverless function and improves response times for returning users.

Monitor Performance and Errors

Vercel provides built-in monitoring under the Analytics tab. Track:

  • Deployment frequency
  • Request count and latency
  • Error rates
  • Function duration

Set up alerts for high error rates or slow functions. You can also integrate with third-party tools like Sentry for advanced error tracking:

npm install @sentry/node

Then initialize Sentry in your server:

const Sentry = require('@sentry/node');

Sentry.init({

dsn: process.env.SENTRY_DSN,

});

app.use(Sentry.Handlers.requestHandler());

Keep Your Code Modular

As your app grows, separate concerns:

  • routes/ Define API endpoints
  • controllers/ Business logic
  • models/ Database schemas
  • middleware/ Authentication, logging

Then import them in server.js:

const express = require('express');

const app = express();

const userRoutes = require('./routes/users');

const authMiddleware = require('./middleware/auth');

app.use('/api/users', authMiddleware, userRoutes);

module.exports = app;

Test Before Deploying

Always test locally with npm start and use tools like Postman or curl to validate endpoints. Vercels deployment logs are helpful, but catching bugs early saves time.

Tools and Resources

Essential Tools for Hosting Node.js on Vercel

  • Vercel Platform The deployment and hosting platform itself. Free tier includes unlimited deployments, 100 GB bandwidth, and 10 GB storage.
  • @vercel/node The official builder that converts Express apps into serverless functions.
  • Express.js The most popular Node.js web framework for building APIs.
  • MongoDB Atlas Fully managed cloud database. Use with environment variables for secure connections.
  • Postman Test your API endpoints before and after deployment.
  • Nodemon Auto-restarts your server during development when files change.
  • Sentry Real-time error monitoring and performance tracking.
  • dotenv Load environment variables from a .env file locally (do not commit this file).

Useful Vercel CLI Commands

Install the Vercel CLI globally for local development and deployment:

npm install -g vercel

Common commands:

  • vercel Deploy current directory interactively
  • vercel --prod Deploy to production
  • vercel dev Local development server that mimics Vercels environment
  • vercel env add Add environment variables locally
  • vercel ls List your deployments

Use vercel dev to test your vercel.json configuration locally before pushing to Git. It emulates Vercels build and routing behavior.

Documentation and Learning Resources

Templates and Starter Kits

Use these GitHub templates to jumpstart your project:

Real Examples

Example 1: REST API for a Todo App

A common use case is hosting a backend for a frontend application. Heres how a todo API might look:

server.js:

const express = require('express');

const app = express();

const PORT = process.env.PORT || 3000;

// In-memory storage (replace with DB in production)

let todos = [

{ id: 1, text: 'Learn Vercel', completed: false },

{ id: 2, text: 'Deploy Node.js', completed: true }

];

app.use(express.json());

app.get('/api/todos', (req, res) => {

res.json(todos);

});

app.post('/api/todos', (req, res) => {

const { text } = req.body;

if (!text) return res.status(400).json({ error: 'Text is required' });

const newTodo = { id: todos.length + 1, text, completed: false };

todos.push(newTodo);

res.status(201).json(newTodo);

});

app.put('/api/todos/:id', (req, res) => {

const id = parseInt(req.params.id);

const todo = todos.find(t => t.id === id);

if (!todo) return res.status(404).json({ error: 'Todo not found' });

todo.completed = !todo.completed;

res.json(todo);

});

app.delete('/api/todos/:id', (req, res) => {

const id = parseInt(req.params.id);

todos = todos.filter(t => t.id !== id);

res.status(204).send();

});

module.exports = app;

vercel.json remains the same as earlier.

Deploy it. Now your React, Vue, or Svelte frontend can fetch from https://your-app.vercel.app/api/todos with zero CORS issuesVercel handles it automatically.

Example 2: Authentication Server with JWT

Host a secure login endpoint:

server.js:

const express = require('express');

const jwt = require('jsonwebtoken');

const app = express();

const PORT = process.env.PORT || 3000;

app.use(express.json());

const JWT_SECRET = process.env.JWT_SECRET;

app.post('/api/login', (req, res) => {

const { username, password } = req.body;

// In production: validate against database

if (username === 'admin' && password === 'secret') {

const token = jwt.sign({ username }, JWT_SECRET, { expiresIn: '1h' });

res.json({ token });

} else {

res.status(401).json({ error: 'Invalid credentials' });

}

});

app.get('/api/protected', (req, res) => {

const authHeader = req.headers.authorization;

if (!authHeader) return res.status(401).json({ error: 'No token provided' });

const token = authHeader.split(' ')[1];

jwt.verify(token, JWT_SECRET, (err, user) => {

if (err) return res.status(403).json({ error: 'Invalid token' });

res.json({ message: 'Access granted', user });

});

});

module.exports = app;

Add JWT_SECRET as an environment variable in Vercel. Now your frontend can authenticate users and protect routes server-side.

Example 3: Webhook Receiver for External Services

Many SaaS platforms (Stripe, GitHub, Slack) send HTTP webhooks. Vercel is perfect for receiving them:

server.js:

const express = require('express');

const app = express();

const PORT = process.env.PORT || 3000;

app.use(express.json({ limit: '10mb' }));

app.post('/webhook/stripe', (req, res) => {

console.log('Stripe webhook received:', req.body);

// Process payment, update DB, send email

res.status(200).send('Received');

});

module.exports = app;

Set your Stripe dashboard to send webhooks to https://your-app.vercel.app/webhook/stripe. Vercel handles high-volume requests reliably and scales automatically.

FAQs

Can I host a full Node.js server with persistent connections on Vercel?

No. Vercel is designed for stateless serverless functions. Persistent connections like WebSockets, long-polling, or real-time chat servers are not supported. Use platforms like Render, Railway, or AWS for such use cases. For real-time features, integrate with third-party services like Pusher, Supabase, or Firebase.

Does Vercel support MongoDB or other databases?

Yes. You can connect to any external database (MongoDB Atlas, PostgreSQL on Supabase, Firebase, etc.) via environment variables. Vercel functions can make outbound HTTP or TCP connections. Just ensure your database allows connections from Vercels IP ranges (which are dynamic but generally permitted).

How do I handle file uploads on Vercel?

File uploads are limited by serverless function size (50MB max payload). For large files, use cloud storage services like AWS S3, Cloudinary, or Uploader. Accept the file upload in your Node.js endpoint, then forward it to the storage service. Never store files directly on Vercels filesystem.

Is there a limit to how many requests Vercel can handle?

Yes. Free tier allows 100 GB bandwidth/month and 10 million function invocations/month. Pro plan increases this significantly. Vercel automatically scales your functions across regions. If you exceed limits, youll be billed or rate-limited.

Can I use TypeScript with Node.js on Vercel?

Absolutely. Rename your file to server.ts and install typescript and @types/express. Vercel will automatically compile TypeScript on build. You dont need a separate build step.

Why is my deployment slow to load the first time?

This is a cold start. Vercel spins up your serverless function on-demand. Subsequent requests are faster. To reduce cold starts, upgrade to Pro plan, which uses warm containers. You can also use Vercels Preview Deployments to keep functions active during development.

Do I need a custom domain?

No. Vercel provides a free .vercel.app domain. You can connect a custom domain (e.g., api.yourcompany.com) in your project settings under Domains. SSL is automatic.

How do I rollback a deployment?

In your Vercel dashboard, go to the Deployments tab. Click on any previous deployment and select Promote to Production. This instantly reverts your live site to that version.

Can I use NestJS or other frameworks on Vercel?

Yes. NestJS, Fastify, Koa, and Hono all work with @vercel/node. The key is exporting the app instance and using the correct routing configuration. Some frameworks may require minor tweaks to work with serverless environments.

Conclusion

Hosting Node.js on Vercel is no longer a workaroundits a strategic advantage. By leveraging Vercels global edge network, automatic scaling, and seamless Git integration, developers can deploy full-stack Node.js applications with unprecedented speed and reliability. Whether youre building a REST API, a webhook receiver, or a backend for a modern frontend framework, Vercel offers a frictionless experience that outperforms traditional hosting in both developer experience and performance.

The key to success lies in understanding Vercels serverless model: stateless functions, cold starts, and environment-driven configuration. By following the best practices outlined in this guideoptimizing dependencies, using environment variables, monitoring performance, and structuring code modularlyyoull build scalable, maintainable Node.js applications that thrive in production.

As serverless architectures continue to dominate cloud development, Vercel stands at the forefrontnot just for frontend frameworks, but for full-stack JavaScript applications. The future of Node.js hosting is fast, global, and serverless. And with Vercel, youre already there.

Start small. Deploy your first API today. Then scale itwithout ever touching a server.