Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
initialize mongodb in next js startup

hi every body i have question on connecting nextJs to mongodb on startup of server. as u know nextjs is fs framework and im migrationg from node/express to it but my problem is how to connect server to database at startup of server as i did in express? there is now where to put my initalizing code in nextjs?am i saying correct? i saw some code to to that but there were typescript codes that im not familiar with them

on the other hand i'm able to do that on serverside functions like getStaticProps or getServerSideProps this is my code dbinit.js

import mongoose from "mongoose";
export const dbStatus = () => mongoose.connection.readyState;
export default function dbConnect() {
  if (dbStatus == 1) return "database is connected";
  mongoose.connect(
    `mongodb://localhost:${process.env.DBPORT}/${process.env.DBNAME}`
  );
}

index.js

export async function getServerSideProps() {
  const result = await dbConnect();
  console.log(dbStatus());
  return {
    props: {},
  };
}

with this code im able to connect to mongodb but there are some problems and the most important is that mycode isnot cleancode

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

In NextJS, we can connect MongoDB as middleware. This is very similar to the Express middleware approach as shown below.

// middleware/database.js

import { MongoClient } from 'mongodb';
import nextConnect from 'next-connect';

const client = new MongoClient('{YOUR-MONGODB-CONNECTION-STRING}', {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

async function database(req, res, next) {
  if (!client.isConnected()) await client.connect();
  req.dbClient = client;
  req.db = client.db('MCT');
  return next();
}

const middleware = nextConnect();

middleware.use(database);

export default middleware;

For more details, you can refer to this official how-to doc for step-by-step guidance. Here is the example repository used.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!