0
0
NextjsHow-ToBeginner · 4 min read

How to Connect to Database in Next.js: Simple Guide

In Next.js, connect to a database by creating API routes inside the pages/api folder and using a database client like Prisma or MongoDB. Use environment variables in a .env.local file to keep your database credentials safe and access them with process.env.
📐

Syntax

To connect to a database in Next.js, you typically create an API route file inside pages/api. Inside this file, you import your database client, connect using credentials stored in environment variables, and export a handler function to process requests.

Key parts:

  • import dbClient from 'your-db-client': Import your database client.
  • const handler = async (req, res) => { ... }: Define an async function to handle API requests.
  • await dbClient.connect(): Connect to the database.
  • res.status(200).json(data): Send back data as JSON.
  • export default handler: Export the handler as default.
javascript
import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);

export default async function handler(req, res) {
  await client.connect();
  const database = client.db('mydatabase');
  const collection = database.collection('mycollection');
  const data = await collection.find({}).toArray();
  res.status(200).json(data);
}
💻

Example

This example shows how to connect to a MongoDB database in a Next.js API route. It fetches all documents from a collection and returns them as JSON.

Make sure to add your MongoDB connection string to a .env.local file as MONGODB_URI.

javascript
import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);

export default async function handler(req, res) {
  try {
    await client.connect();
    const database = client.db('testdb');
    const collection = database.collection('users');
    const users = await collection.find({}).toArray();
    res.status(200).json(users);
  } catch (error) {
    res.status(500).json({ error: 'Failed to connect to database' });
  } finally {
    await client.close();
  }
}
Output
[{"_id":"someid1","name":"Alice"},{"_id":"someid2","name":"Bob"}]
⚠️

Common Pitfalls

  • Not using environment variables: Hardcoding credentials risks security and makes deployment harder.
  • Connecting on every request: Opening a new database connection on each API call can slow down your app. Use connection pooling or reuse clients.
  • Not closing connections: Forgetting to close connections can exhaust database resources.
  • Using database code in client components: Database code must run on the server side, such as in API routes or server components.
javascript
/* Wrong: Connecting inside React component (runs on client) */

import { MongoClient } from 'mongodb';

const uri = process.env.MONGODB_URI;
const client = new MongoClient(uri);

export default function Page() {
  // This will fail because MongoClient can't run in the browser
  // client.connect(); // This should not be called here
  return <div>Users</div>;
}

/* Right: Connect inside API route */

export default async function handler(req, res) {
  await client.connect();
  // ...fetch data
  res.status(200).json({});
}
📊

Quick Reference

  • Store database URLs in .env.local and access with process.env.
  • Use API routes in pages/api to run server-side code.
  • Use async/await to handle database calls.
  • Close database connections when done or reuse clients.
  • Never run database code in client-side components.

Key Takeaways

Use API routes in Next.js to connect to databases securely on the server side.
Keep database credentials in environment variables, never hardcode them.
Reuse database connections or clients to improve performance.
Avoid running database code in client-side components to prevent errors.
Handle errors gracefully and close connections properly.