Database Connection in Next.js (with TypeScript)


Prerequisites
Next.js (Next.js edge network pe run karta hai - multiple servers like India, USA, etc.).
Edge ka matlab hai distributed servers.
Next.js ka behavior serverless hota hai, so different requests alag-alag edges pe handle ho sakti hain.
Mongoose for database connection.
TypeScript for strong typing.
Step 1: Install Next.js
Open VS Code.
Run this command to set up a Next.js project:
npx create-next-app@latest my-app --typescript
Step 2: Create a Utility Folder (lib
)
Next.js me, database connection ke liye hum ek utility folder banate hain.
2(a): Create the lib
directory
lib
folder iskoutil
yautility
bhi kaha jata hai.
2(b): Create a file named db.ts
This file will manage the MongoDB connection using Mongoose.
Install Mongoose:
npm install mongoose
Step 3: Writing the db.ts
File
Step 4: TypeScript Setup for Global Variables
Since Next.js runs in a serverless environment, global variables are often reset. To avoid TypeScript errors related to mongoose
, we define global types.
4(a): Create types.d.ts
file
File location: Root directory (outside any folder).
File content:
import { Connection } from "mongoose";
declare global {
var mongoose: {
conn: Connection | null;
promise: Promise<Connection> | null;
};
}
export {};
Step 5: Environment Variables SetupCreate a .env file in the root of your project and add your MongoDB connection string:MONGODB_URI=mongodb+srv://<username>:<password>@cluster.mongodb.net/<dbname>
Replace <username>, <password>, and <dbname> with your database credentials.
Important Notes:
bufferCommands
in Mongoose:- Yeh option temporarily database commands ko store karta hai jab tak connection establish nahi hota.
maxPoolSize
:- Ek samay me kitne active connections maintain honge, iska control deti hai.
Final Thoughts
Next.js ka edge-based architecture aur serverless model ko dhyan me rakhte hue cached connection kaafi important hoti hai.
Aapke database connections efficient banane ke liye
global
variable aur Mongoose options ka sahi use zaroori hai.
Subscribe to my newsletter
Read articles from shubham kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

shubham kumar
shubham kumar
Hello! I am leveraging my Software Engineering and Web Development expertise to explore new technologies through various online resources. As a final year BTech student in Computer Science from the Netaji Subhas Institute of Technology, I am enthusiastic about applying my knowledge and experience to advance my career in Software Engineering.