I’m using the excellent pg-promise
library inside a Next.js app to interface with a Postgres database deployed on AWS. Specifically, I’m using the API routes feature, where folders inside /pages/api
are mapped to corresponding endpoints. This has vastly simplified my code and allowed me to remove a custom server.js
file. The problem is that pg-promise
throws this warning:
WARNING: Creating a duplicate database object for the same connection.
The author has addressed this before, but despite following the advice, the warning persists.
I initialize the database connection only once, in database.js
:
const pgp = require('pg-promise')();
const connection = { ... };
const db = pgp(connection);
module.exports = db;
And then pass it along to my APIs in pages/api
, in this case, users.js
:
import db from ‘../database.js;
export default async function handler(req, res) {
try {
const users = await db.any('SELECT * FROM table);
res.json(users)
} catch (error) {
res.status(error.status || 500).end(error.message)
}
}
The data eventually makes its way to a getInitialProps
call.
What is causing the warning? Is there a pattern I'm missing or a design flaw in my handling of the connection object? I've experimented with various configs and middlewares, but the warning remains.