8000 DB connection not preserved for SSG pages in development (with-mongodb example) · Issue #44017 · vercel/next.js · GitHub
[go: up one dir, main page]

Skip to content

DB connection not preserved for SSG pages in development (with-mongodb example) #44017

New issue

Have a questio 8000 n about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
1 task done
howard36 opened this issue Dec 14, 2022 · 2 comments
Open
1 task done
Labels
examples Issue was opened via the examples template. stale The issue has not seen recent activity.

Comments

@howard36
Copy link
howard36 commented Dec 14, 2022

Verify canary release

  • I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
  Platform: linux
  Arch: x64
  Version: #1 SMP Thu, 08 Dec 2022 14:23:39 +0000
Binaries:
  Node: 19.2.0
  npm: 8.19.3
  Yarn: 1.22.19
  pnpm: N/A
Relevant packages:
  next: 13.0.7-canary.6
  eslint-config-next: N/A
  react: 18.2.0
  react-dom: 18.2.0

Which example does this report relate to?

with-mongodb

What browser are you using? (if relevant)

Firefox 108.0

How are you deploying your application? (if relevant)

next dev

Describe the Bug

When getStaticPaths and getStaticProps await clientPromise in development, a new client connection is established each time the page loads. This causes delays when loading pages and creates unnecessary open connections.

Expected Behavior

The same database connection is reused for subsequent requests.

To Reproduce

  1. Create the file pages/[slug].tsx with the following code:
import clientPromise from '../lib/mongodb'

export async function getStaticPaths() {
  const client = await clientPromise
  const db = client.db('myPosts')

  const data = await db
    .collection('posts')
    .find({})
    .project({ _id: 0, slug: 1 })
    .toArray()

  const paths = data.map((post) => ({
    params: { slug: post.slug },
  }))

  return { paths, fallback: false }
}

export async function getStaticProps({ params }) {
  const client = await clientPromise
  const db = client.db('myPosts')

  const data = await db
    .collection('posts')
    .findOne({ slug: params.slug }, { projection: { _id: 0 } })

  return {
    props: {
      post: data,
    },
  }
}

export default function Post({ post }) {
  console.log(`${post.title} rendered`)
  return (
    <div>
      <h1>{post.title}</h1>
      <p>{post.content}</p>
    </div>
  )
}
  1. Create a MongoDB database named myPosts, with a collection called posts. Each post should have a (unique) slug field, a title, and a content field.
  2. Add a console.log to line 17 of lib/mongodb.ts (to make the bug more clear)
import { MongoClient } from 'mongodb'

if (!process.env.MONGODB_URI) {
  throw new Error('Invalid/Missing environment variable: "MONGODB_URI"')
}

const uri = process.env.MONGODB_URI
const options = {}

let client
let clientPromise: Promise<MongoClient>

if (process.env.NODE_ENV === 'development') {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  if (!global._mongoClientPromise) {
    console.log('Creating new client') // <-- Add this line
    client = new MongoClient(uri, options)
    global._mongoClientPromise = client.connect()
  }
  clientPromise = global._mongoClientPromise
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options)
  clientPromise = client.connect()
}

// Export a module-scoped MongoClient promise. By doing this in a
// separate module, the client can be shared across functions.
export default clientPromise
  1. In .env.local, add MONGODB_URI and set NODE_ENV=development.
  2. Run yarn dev, and navigate to various post pages. You should see logs like this:
    Screenshot_20221214_024002
    There will also be a noticeable delay before each page loads, if your database is remote.
@howard36 howard36 added the examples Issue was opened via the examples template. label Dec 14, 2022
@nanzm
Copy link
nanzm commented Nov 29, 2023

#45483

@nextjs-bot
Copy link
Collaborator

This issue has been automatically marked as stale due to two years of inactivity. It will be closed in 7 days unless there’s further input. If you believe this issue is still relevant, please leave a comment or provide updated details. Thank you.

@nextjs-bot nextjs-bot added the stale The issue has not seen recent activity. label May 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
examples Issue was opened via the examples template. stale The issue has not seen recent activity.
Projects
None yet
Development

No branches or pull requests

307B
3 participants
0