I have a Next.js 13 project with the app directory which connects successfully to a postgres database.
What I want to do is to connect to Postgres once, and then export the connection across my app so I will be able to perform queries from server components.
in order to do that I create a file, index.ts
:
import { VercelPoolClient, db } from '@vercel/postgres';
let client: VercelPoolClient | null = null
export async function connectToDB() {
try {
const establishClient = await db.connect();
console.log('Connection to Postgres has established');
client = establishClient
return client
} catch (e) {
console.log('ERROR! Could not connect to Postgres');
console.log(e);
}
}
connectToDB()
export default function dbClient(): VercelPoolClient | null{
if (!client) {
throw new Error('you must connect before trying to use client')
}
return client
}
The problem seems that the connection to the Postgres database only occurs after my server components are already rendered, because I get an error from dbClient()
but slightly afterwards, I do see the message from console.log('Connection to Postgres has established');
.
I tried moving this file in and out of my app directory but the result is the same. If anyone knows how can I ensure a connection has been established before the server components, that would be great.