Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
Set callbackWaitsForEmptyEventLoop in Nextjs API

I would like to set callbackWaitsForEmptyEventLoop to false in my Nextjs handler but it's signature is missing the context.

The goal is to properly configure nextjs, mongoDB, mongoose to avoid any performance issue when deployed on aws-lambda. I've been looking around and it looks like most option examples are outdated and doesn't apply to mongoose 6. Given that the connection are made inside aws-lambda and cached, is there still a need to close connections manually?

Current setup based on various recommendations:

// useDb options
export const useDbOptions = {
  useCache: true,
  noListener: true,
};

// Schema options
export const useSchemaOptions = {
  autoIndex: true,
  bufferCommands: false,
};

// Cached connection outside of handler
let conn: Promise<typeof mongoose> | null = null;

// Mongoose options
mongoose.connect(mongoDbUri, {
  bufferCommands: false,
})

Nextjs handler signature is missing context:

async function handler(req: NextApiRequest, res: NextApiResponse) {
  ...
}

Per recommendations from mongoose doc:

const mongoose = require('mongoose');

let conn = null;

const uri = 'YOUR CONNECTION STRING HERE';

exports.handler = async function(event, context) {
  // Make sure to add this so you can re-use `conn` between function calls.
  // See https://www.mongodb.com/blog/post/serverless-development-with-nodejs-aws-lambda-mongodb-atlas
  context.callbackWaitsForEmptyEventLoop = false;

  // Because `conn` is in the global scope, Lambda may retain it between
  // function calls thanks to `callbackWaitsForEmptyEventLoop`.
  // This means your Lambda function doesn't have to go through the
  // potentially expensive process of connecting to MongoDB every time.
  if (conn == null) {
    conn = mongoose.createConnection(uri, {
      // and tell the MongoDB driver to not wait more than 5 seconds
      // before erroring out if it isn't connected
      serverSelectionTimeoutMS: 5000
    });
    
    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn;
    conn.model('Test', new mongoose.Schema({ name: String }));
  }

  const M = conn.model('Test');

  const doc = await M.findOne();
  console.log(doc);

  return doc;
};

Yet callbackWaitsForEmptyEventLoop isn't configured in their helper example:

'use strict';

const mongoose = require('mongoose');

let conn = null;

const uri = 'YOUR CONNECTION STRING HERE';

exports.connect = async function() {
  if (conn == null) {
    conn = mongoose.createConnection(uri, {
      serverSelectionTimeoutMS: 5000
    });
    
    // `await`ing connection after assigning to the `conn` variable
    // to avoid multiple function calls creating new connections
    await conn;
  }

  return conn;
};

Package versions:

"mongodb": "^4.3.0",
"mongoose": "^6.1.6",
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda