DEV Community

Nicolas Torres
Nicolas Torres

Posted on • Updated on

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

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 (2)

Collapse
jdunk profile image
jdunk

Thank you!!!! This had been bothering me for weeks, and just now I also just spent hours trying to find any explanation for why Next.js (at least in dev mode) seems to be compiling and restarting on every single http request, even without any changes between requests. Finally, a solution! This really needs to be documented somewhere. Who knows how much time you just saved me. Muchas gracias!

Collapse
noclat profile image
Nicolas Torres Author

I'm glad it helped! Had a lot of trouble myself to find a solution.