Create and Deploy a MongoDB-powered Node.js API with Now

Learn how to create a serverless Node.js API with data powered by MongoDB then deploy it as a serverless application with ZEIT Now.

In this guide, we will walk you through creating and deploying a Node.js API powered by MongoDB, on ZEIT Now.

Step 1: Preparing Your Project

To start this example, you will need to have setup a MongoDB Atlas account and database.

Make sure that the cluster has whitelisted connections from anywhere, since Now does not support static IP addresses.

Get started by creating a project directory and cd into it:

mkdir my-mongodb-api && cd my-mongodb-api

Creating and entering into the my-mongodb-api directory.

Next, initialize the project:

yarn init

Initializing the project, this creates a package.json file.

Note: During the initializing process, Yarn will ask questions about your project. Answer these how you wish; there are no prerequisites for this example.

Next, install the MongoDB Node.js client, which you will use to connect to your MongoDB cluster and database:

yarn add mongodb

Adding the mongodb Node.js client as a dependency to the project.

To connect to MongoDB, you will need your MongoDB connection string.

You can get the connection string by clicking "Connect" on the Cluster Overview page within the MongoDB Atlas dashboard, then choosing "Connect your Application":

Getting the connection string from the MongoDB Atlas connection modal.

To use your MongoDB connection string without hard-coding it in your project, you can add your connection string to the project as a Now Secret using the Now CLI to keep them secure:

now secrets add my-mongodb-uri mongodb+srv://<user>:<password><database-name>?retryWrites=true

Adding a secret, using the MongoDB connection string, to the project.

Note: Make sure to use your own connection string and add your password to the string.

Finally, set up the now.json configuration file that will tell Now how to build and serve your project, both locally and in production:

  "name": "my-mongodb-api",
  "version": 2,
  "builds": [{ "src": "**/*.js", "use": "@now/node" }],
  "env": {
    "MONGODB_URI": "@my-mongodb-uri"

A now.json configuration file for development and deployment.

The above file tells Now the following:

  • The name of the project is "my-mongodb-api".
  • The platform version the project uses is Now 2.0.
  • All JavaScript files should be built by the @now/node Builder.
  • An Environment Variable, env, should be accessible in the app with the value of the secret you added in the first step.
Note: To use this environment variable in local development, you will need to use a .env file. Read more about local development and environment variables.

Step 2: Creating the API

Now that you have a MongoDB database, it's time to create the Node.js API endpoint that will be fetching data from it.

Note: If you don't have any data to insert into your database, you can load a sample dataset to start.

For this example, create a file called users.js in a new directory called api.

The users.js file will act as the endpoint for getting information from your database. The file should contain the following contents:

// Import Dependencies
const url = require('url')
const MongoClient = require('mongodb').MongoClient

// Create cached connection variable
let cachedDb = null

// A function for connecting to MongoDB,
// taking a single paramater of the connection string
async function connectToDatabase(uri) {
  // If the database connection is cached,
  // use it instead of creating a new connection
  if (cachedDb) {
    return cachedDb

  // If no connection is cached, create a new one
  const client = await MongoClient.connect(uri, { useNewUrlParser: true })

  // Select the database through the connection,
  // using the database path of the connection string
  const db = await client.db(url.parse(uri).pathname.substr(1))

  // Cache the database connection and return the connection
  cachedDb = db
  return db

// The main, exported, function of the endpoint,
// dealing with the request and subsequent response
module.exports = async (req, res) => {
  // Get a database connection, cached or otherwise,
  // using the connection string environment variable as the argument
  const db = await connectToDatabase(process.env.MONGODB_URI)

  // Select the "users" collection from the database
  const collection = await db.collection('users')

  // Select the users collection from the database
  const users = await collection.find({}).toArray()

  // Respond with a JSON string of all users in the collection
  res.status(200).json({ users })

A Node.js API Endpoint that retrieves data from a MongoDB database collection.

Hint: In the code snippet above, you probably noticed that we used res.status() and res.json() to send a response. These methods are automatically added for you when you use@now/node. Read more about this in the @now/node Builder documentation page.

Step 3: Local Development

Now that you have your MongoDB database, an API endpoint, and configuration all done, you can start to develop your API, and applications, locally.

Using Now CLI, you can start a development process from your terminal that mimics your production environment using the configuration you provided in your now.json file.

To start developing, create a .env file containing the MONGODB_URI environment variable and the connection string you want to use locally:


A .env file containing the MONGODB_URI environment variable and its value for local development.

This file allows the Now development process to use the environment variable with a value, since you are using a Now Secret in production which isn't accessible outside of the secure deployment environment.

Next, run the Now CLI development command from the terminal:

now dev

Starting Now CLI's dev process from the terminal.

Note: If you have don't have Now CLI, you can install it via Now Desktop, which is the easiest way to get started with Now.

After starting the development process, Now CLI will provide you with a localhost address for where your application is running. This is commonly http://localhost:3000 unless the port is taken.

Using the default port, you can find your new API endpoint at http://localhost:3000/api/users.js.

Step 4: Deploying

The next and final step is to deploy your application with a single command.

With Now, you can deploy your application to different environments, depending on what stage your application is at; either staging or production.

To deploy to a unique alias, use the following Now CLI command from your terminal:


Deploying with Now CLI in one command.

Hint: See more ways to deploy and alias from the Aliasing Documentation.

For production deployments, you can deploy to an alias of your choice. To do so, add an alias to your now.json file:

  "alias": "my-mongodb-api"

Extending a now.json file with an alias property.

Now, deploy your project to a production environment using the following command:

now --target production

Deploying to production with Now.

Note: For optimal performance, deploy your API to the closest region, or regions, of where your MongoDB cluster is located in. You can see the regions Now supports in the Regions and Providers documentation.

When complete, Now CLI will provide you with the URL your project has been deployed and aliased to. In the case above, the alias was set to

You can view the aliased deployment from this guide, using the API path, here:

Hint: Don't forget to exclude the node_modules folder from being uploaded to Now to enable faster deployment. To do that, add a .nowignore file to the root of the project directory and add node_modules to it.

Deploying Automatically with Git

Instead of deploying manually through your terminal, you can also get automatic deployments with each git push when you use Now for GitHub or Now for GitLab.

Push to any branch, pull, or merge request and get a fresh deployment to review. Merging into the default branch results in an automatic alias to production. Not extra work needed.

See more on ZEIT Git Integrations:


For more information on working with MongoDB, please refer to their documentation.

To configure Now further, please see these additional topics and guides:

Written By
Written by timothytimothy
on May 24th 2019