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:
Creating and entering into the my-mongodb-api
directory.
Next, initialize the project:
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:
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:
Adding a secret, using the MongoDB connection string, to the project.
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.
.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 }) }
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@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:
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 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:
Starting Now CLI's dev process from the terminal.
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.
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:
Deploying to production with Now.
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
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:
Resources
For more information on working with MongoDB, please refer to their documentation.
To configure Now further, please see these additional topics and guides: