Create and Deploy a MongoDB-Powered Node.js API with Vercel
Create a serverless Node.js API with data powered by MongoDB then deploy it as a serverless app with Vercel.
In this guide, we will walk you through creating and deploying a Node.js API powered by MongoDB, on Vercel.
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 allowlisted connections from anywhere, since Vercel 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:
npm init
Initializing the project, this creates a package.json
file.
Next, install the MongoDB Node.js client, which you will use to connect to your MongoDB cluster and database:
npm i 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 Secret using the Vercel CLI to keep them secure:
vercel secrets add my-mongodb-uri mongodb+srv://<user>:<password>@my-cluster-uf345.mongodb.net/<database-name>?retryWrites=true
Adding a secret, using the MongoDB connection string, to the project.
Finally, set up the vercel.json
configuration file that instructs Vercel to make available the Secret you defined:
{ "name": "my-mongodb-api", "version": 2, "env": { "MONGODB_URI": "@my-mongodb-uri" } }
A vercel.json
configuration file for development and deployment.
The above file tells Vercel the following:
- The name of the project is "my-mongodb-api"
- An Environment Variable,
env
, should be accessible in the app with the value of the secret you added in the first step
.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.
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 parameter 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.
res.status()
and res.json()
to send a response. These methods are automatically added for you when you use@vercel/node
. Read more about this in the @vercel/node
Runtime 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 apps, locally.
Using Vercel CLI, you can start a development process from your terminal that mimics your production environment using the configuration you provided in your vercel.json
file.
To start developing, create a .env
file containing the MONGODB_URI
environment variable and the connection string you want to use locally:
MONGODB_URI=mongodb+srv://<user>:<password>@my-cluster-uf345.mongodb.net/<database-name>?retryWrites=true
A .env
file containing the MONGODB_URI
environment variable and its value for local development.
This file allows the Vercel development process to use the environment variable with a value, since you are using a Secret in production which isn't accessible outside of the secure deployment environment.
Next, run the Vercel CLI development command from the terminal:
vercel dev
Starting Vercel CLI's dev process from the terminal.
After starting the development process, Vercel CLI will provide you with a localhost address for where your app 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
To deploy your MongoDB API with a Vercel for Git, make sure it has been pushed to a Git repository.
Import the project into Vercel using your Git of choice:
After your project has been imported, all subsequent pushes to branches will generate Preview Deployments, and all changes made to the Production Branch (commonly "main") will result in a Production Deployment.
You can view the deployment from this guide, using the API path, here: https://my-mongodb-api.now.sh/api/users.js