MongoDB: NextJS Setup
Configurig your NextJS app for MongoDB
Connecting to MongoDB
To connect to MongoDB, you’ll need to do the following. (Note: if you want to have separate databases for development, qa and production, there are additional instructions after these simple ones).
- Define
MONGODB_URI
in your.env
file - In your
next.config.js
file, where you see:AUTH0_DOMAIN: process.env.AUTH0_DOMAIN,
Add a line into that same structure like this one:
MONGODB_URI: process.env.MONGODB_URI,
- Add a line like this into
utils/config.js
, but only in the part for settings exposed to the server. LEAVE THIS OUT of the part for settings exposed to the client, otherwise you’ll have a security leak.MONGODB_URI: process.env.MONGODB_URI,
- In
utils/mongodb.js
, the file has a hardcoded value ofdatabase
, which assumes the name of your database isdatabase
(literally). If it already exists under a different name, then change this line, changingdatabase
to the correct name.return client.db("database");
If you don’t have a file
utils/mongodb.js
, you can get it fromproject-idea-reviewer-nextjs
Multiple Databases (for dev/prod/qa)
To use different databases for dev/prod/qa)
- In
.env
create three different variables as follows, and put in the mongodb URIs for the three databases:MONGODB_URI=mongodb+srv://adminuser (put in full URI of dev database here) MONGODB_URI_STAGING=mongodb+srv://adminuser... (put in full URI of qa database here) MONGODB_URI_PRODUCTION=mongodb+srv://adminuser... (put in full URI of production database here)
-
Change the code in
next.config.js
to match this code:Before the
module exports = {
line, paste in this function definition. This chooses a value for the MongoDB URI from among the three provided, based on the value of another environment value, namely the value ofNODE_ENV
:function mongodb_uri() { if (process.env.NODE_ENV === "production") { return process.env.MONGODB_URI_PRODUCTION; } else if (process.env.NODE_ENV === "staging") { return process.env.MONGODB_URI_STAGING; } return process.env.MONGODB_URI; }
Then change:
MONGODB_URI: process.env.MONGODB_URI,
to:
MONGODB_URI: mongodb_uri(),
-
Use
npx heroku-dotenv push --app your-heroku-app
for both prod and dev - Manually set the following variable on the Heroku settings config vars:
- Set
NODE_ENV
toproduction
for the production site - Set
NODE_ENV
tostaging
for the QA site
- Set
Related topics:
- MongoDB: Cloud Atlas Setup—Setting up MongoDB Cloud Atlas (for new users)
- MongoDB: Cloud Atlas Sharing—Sharing a Cloud Atlas Setup
- MongoDB: Mlab—A cloud provider of MongoDB databases with a free tier
- MongoDB: NextJS Guide—How database operations in NextJS differ from examples in standard node
- MongoDB: NextJS Setup—Configurig your NextJS app for MongoDB
- MongoDB: Spring Properties—How to set properties for connecting to MongoDB when using Spring