First, you need to install the official MongoDB package:
This package allows you to connect to a MongoDB database and perform CRUD operations.
Step 2: Create a MongoDB Connection File
Since Next.js uses both server-side and client-side code, it's good practice to manage your MongoDB connection in a separate file. This ensures the connection is reused and only set up on the server side.
Create a new file at lib/mongodb.js (or any other preferred folder structure).
Step 3: Set Up Environment Variables
Next.js stores environment variables in the .env.local file. Create a .env.local file in the root of your project and add your MongoDB connection string.
Make sure to replace username, password, and mydatabase with your actual MongoDB credentials.
Step 4: Fetch Data from MongoDB in a Next.js API Route
Next.js API routes are perfect for server-side database connections. Create a new API route that uses the MongoDB connection.
For example, create a file pages/api/collection.js:
This route connects to your MongoDB database and fetches all documents from the collection named mycollection.
Step 5: Fetch Data from MongoDB in a Next.js Page
You can also fetch MongoDB data using getServerSideProps to render the data on the server side for a specific page.
Example of a page (pages/index.js):
Step 6: Testing
You can run your Next.js app locally with:
Access the API route at http://localhost:3000/api/collection to see the data fetched from MongoDB, or visit the homepage to see server-side-rendered data.
Additional Notes
Make sure your MongoDB Atlas cluster allows connections from your IP or use a VPN if needed.
For production, set up environment variables using platforms like Vercel, Heroku, or others.
By following these steps, you’ll have your Next.js application successfully connected to MongoDB!