DEV Community

loading...

Fix "too many connections" errors with database clients stacking in dev mode with Next.js

noclat profile image Nicolas Torres Updated on ・1 min read

Next.js constantly rebuilds your API routes in development mode, triggering each time the creation of new instances of databases and other third-party services your back-end relies on.

This is not a very well documented part, and I've spent many hours looking for a solution, both online and within the source code of Next.js, to finally find a very simple yet elegant one: using global.

Indeed the server itself does not reload, so global is preserved across incremental builds. So here's the helper I use to prevent the server from stacking Redis, PostgreSQL and other SDK clients:

/**
 * Register service.
 * @description Stores instances in `global` to prevent memory leaks in development.
 * @arg {string} name Service name.
 * @arg {function} initFn Function returning the service instance.
 * @return {*} Service instance.
 */
const registerService = (name, initFn) => {
  if (process.env.NODE_ENV === 'development') {
    if (!(name in global)) {
      global[name] = initFn();
    }
    return global[name];
  }
  return initFn();
};
Enter fullscreen mode Exit fullscreen mode

Yep, that's it. To use it, simply call:

import knex from 'knex';

export const db = registerService('db', () => knex({
  client: 'pg',
  connection: process.env.DATABASE_URL,
}));
Enter fullscreen mode Exit fullscreen mode

Now you won't have to restart Next.js server every 10 minutes to flush out residual clients.

Discussion (0)

pic
Editor guide