Create and Deploy a MongoDB-Powered Node.js API with ZEIT Now
Create a serverless Node.js API with data powered by MongoDB then deploy it as a serverless app 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
Next, initialize the project:
npm init
Next, install the MongoDB Node.js client, which you will use to connect to your MongoDB cluster and database:
npm i mongodb
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":
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>@my-cluster-uf345.mongodb.net/<database-name>?retryWrites=true
Finally, set up the now.json
configuration file that instructs Now to make available the Secret you defined:
{ "name": "my-mongodb-api", "version": 2, "env": { "MONGODB_URI": "@my-mongodb-uri" } }
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
- 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 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 }) }
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 apps, 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:
MONGODB_URI=mongodb+srv://<user>:<password>@my-cluster-uf345.mongodb.net/<database-name>?retryWrites=true
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
After starting the development process, Now 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
The next and final step is to deploy your app with a single command.
With Now, you can deploy your app to different environments, depending on what stage your app is at; either staging or production.
To deploy to a unique alias, use the following Now CLI command from your terminal:
now
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" ... }
Now, deploy your project to a production environment using the following command:
now --prod
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 my-mongodb-api.now.sh
.
You can view the aliased deployment from this guide, using the API path, here: https://my-mongodb-api.now.sh/api/users.js
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. No extra work needed.