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",