jeremydaly / serverless-mysql

A module for managing MySQL connections at SERVERLESS scale
MIT License
1.21k stars 83 forks source link

Next.js hot reload and MySQL Error “Too many connections” #136

Closed danidev closed 1 year ago

danidev commented 2 years ago

Hello, I am using serverless-mysql in a Next.js environment and during development I found out that on hot reload the open connections were lost, causing the MySQL Error “Too many connections”.

This is the way I fixed it, following this issue: https://github.com/vercel/next.js/issues/7811 The mySqlClient is stored as a global variable, so it is not instantiated on every Next.js hot reload.

import mysql from 'serverless-mysql';

var mySqlClient;

if (process.env.NODE_ENV === "development") {
  global.mySqlClient =
    global.mySqlClient ||
    mysql({
      config: {
        host: process.env.MYSQL_HOST,
        //port: process.env.MYSQL_PORT,
        database: process.env.MYSQL_DATABASE,
        user: process.env.MYSQL_USER,
        password: process.env.MYSQL_PASSWORD
      }
    });

  mySqlClient = global.mySqlClient;
} else {
  mySqlClient = mysql({
    config: {
      host: process.env.MYSQL_HOST,
      //port: process.env.MYSQL_PORT,
      database: process.env.MYSQL_DATABASE,
      user: process.env.MYSQL_USER,
      password: process.env.MYSQL_PASSWORD
    }
  });
}

I'd like to know what you think about this solution and if can be improved (for instance calling mySqlClient.quit() if the client is already a global variable)

naorpeled commented 1 year ago

Hey @danidev, this solution looks good to me.

As you said, you could use mySqlClient.quit to make sure the connection is properly cleaned up but re-use is preferable than re-instantiating a new connection imo.