Next.js Discord

Discord Forum

mssql connection pool?

Unanswered
Satin Angora posted this in #help-forum
Open in Discord
Satin AngoraOP
This is my current attempt:
import "server-only"
import sql from "mssql"

const sqlConfig: sql.config = {
    user: process.env.DB_USER,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_NAME,
    server: process.env.DB_SERVER!,
    pool: {
        max: 10,
        min: 1,
        idleTimeoutMillis: 30000
    },
    options: {
        encrypt: true,
        trustServerCertificate: true
    }
}

declare global {
    var pool: sql.ConnectionPool | undefined | null;
}

const connectToDatabase = async () => {
    if (!globalThis.pool) {
        globalThis.pool = new sql.ConnectionPool(sqlConfig);
        console.log("Global not found - Created new global ConnectionPool."); // this is never logged
    }

    if (globalThis.pool.connected) {
        return globalThis.pool;
    }

    try {
        await globalThis.pool.connect();
        console.log("Connected to the database."); // this is logged 1x during the whole app lifecycle
        return globalThis.pool;
    } catch (error) {
        console.error("Error connecting to the database:", error); // this is never logged
        globalThis.pool = undefined;
    }
    return null;
};

export default connectToDatabase;


And this is how I use it:

const pool = await connectToDatabase();
const result = await pool!.request().input('employee', session.id).query('my query string')

//use data with result.recordset.... 


This is not going to run on vercel or whatever, the whole app should only run on a single server with nodejs
What i basically need is a connection pool thats available over the whole lifespan of the application, it is kinda working and I get no errors but for some reason during development my ram runs out after ~30 mins and vs code is taking up to 20gb of ram, till i shutdown the dev server. Does not happen on pages not requiring data from the database, so I assume it has something to do with my mssql thing.
This doesn't happen with prisma but I'm not allowed to use any orm like prisma.
Also that's the first time I'm using mssql and the first time not using prisma for my database handling
Any advice on how to solve my problem?

12 Replies

try not connecting to it each time you want to use, and just export the connection [see prisma example](https://www.prisma.io/docs/guides/other/troubleshooting-orm/help-articles/nextjs-prisma-client-dev-practices#solution) (i know you aren't using them, but their example should work similarly for you)
Satin AngoraOP
Wait, am I doing that? (The function name is a bit misleading xD )

    if (globalThis.pool.connected) {
        return globalThis.pool;
    }


Doesn't this return the pool if it's already connected so the try/catch below is not even executed? Need a way to check if it's still connected, else reconnect before returning or is it doing that automatically when trying to send a request? Because if it somehow loses connection, my whole app would break till a restart
i think it is better to export a const than to run a function (even if they both use globalthis)
ok maybe for mssql, you may need to restart it easier (idk what the relogin is for it) - but it kinda sounds like a bad thing for it to loose the connection...
This post is old but I'm trying to connect to mssql and can connect to sql using just node, but when I try with a new nextjs project I get:
⨯ ./node_modules/tedious/lib/connection.js:9:1
Module not found: Can't resolve 'tls'
What package are you using?
i had a similar problem to you, basically what i did was create a singleton pattern
and that kept the instance the same across the whole app
i.e
create a class with a static field of the instance
and then have like a getPool function that returns the instance
export class DBService {
  private static pool;

  public static getPool() {
    return this.pool;
  }

  public static register() {
    if (!pool) {
      // setup pool here
    }
  }
}
that may work