Nextjs mongodb connection setup
Next.js MongoDB Connection Setup
- Install Required Packages: Install the necessary packages using npm or yarn.
bash
npm install mongodb next-connect
- Create MongoDB Connection File:
Create a new file for handling the MongoDB connection, such as
mongodb.js
.
```javascript import { MongoClient } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, });
export async function connectToDatabase() { if (!client.isConnected()) await client.connect(); return client.db('your-database-name'); } ```
- Set Up API Route: Create an API route for making the database connection available to the Next.js application.
```javascript import nextConnect from 'next-connect'; import { connectToDatabase } from './mongodb';
const handler = nextConnect();
handler.use(async (req, res, next) => { if (!global.mongoClient) { global.mongoClient = await connectToDatabase(); } return next(); });
export default handler; ```
- Access Database in Pages or API Routes: You can now import the MongoDB connection and use it in your Next.js pages or API routes.
```javascript import { connectToDatabase } from '../path/to/mongodb';
export default async function handler(req, res) { const db = await connectToDatabase(); // Use the database connection } ```