Skip to content

[FEATURE] Better way of caching db client on per request basis #630

New issue

Have a question 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
2 tasks done
willenigma opened this issue May 3, 2025 · 0 comments
Open
2 tasks done

[FEATURE] Better way of caching db client on per request basis #630

willenigma opened this issue May 3, 2025 · 0 comments
Labels
enhancement New feature or request triage

Comments

@willenigma
Copy link

Is your feature request related to a problem?

On this page: https://opennext.js.org/cloudflare/howtos/db

There is a guide on how to initialize a database client:

//lib/db.ts
import { drizzle } from "drizzle-orm/node-postgres";
// You can use cache from react to cache the client during the same request
// this is not mandatory and only has an effect for server components
import { cache } from "react";
import * as schema from "./schema/pg";
import { Pool } from "pg";
 
export const getDb = cache(() => {
  const pool = new Pool({
    connectionString: process.env.PG_URL,
    // You don't want to reuse the same connection for multiple requests
    maxUses: 1,
  });
  return drizzle({ client: pool, schema });
});

However, the comment notes that cache only works for server components—not for route handlers. In route handlers, we may need to call getDb() multiple times. If each call creates a new DB client, it can lead to significant performance issues.

Describe the solution you'd like

A better way to cache the DB client in route handlers.
Ideally, a universal approach that handles per-request DB client caching consistently across both server components and route handlers.

Describe alternatives you've considered

One workaround is to initialize the DB client at the beginning of the route handler and pass it manually to all functions that need it. However, this is cumbersome and requires a lot of refactoring when migrating from existing Next.js projects.

@opennextjs/cloudflare version

1.0.0-beta.4

Additional context

No response

Before submitting

  • I have checked that there isn't already a similar feature request
  • This is a single feature (not multiple features in one request)
@willenigma willenigma added enhancement New feature or request triage labels May 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request triage
Projects
None yet
Development

No branches or pull requests

1 participant