Using one drizzle connection per request (Cloudflare + postgres)

When connecting to Drizzle postgres (Neon) through a cloudflare worker. I always get this error on first load.
Error: Cannot perform I/O on behalf of a different request. I/O objects (such as streams, request/response bodies, and others) created in the context of one request handler cannot be accessed from a different request's handler. This is a limitation of Cloudflare Workers which allows us to improve overall performance.
Error: Cannot perform I/O on behalf of a different request. I/O objects (such as streams, request/response bodies, and others) created in the context of one request handler cannot be accessed from a different request's handler. This is a limitation of Cloudflare Workers which allows us to improve overall performance.
I think it's due to the db being shared between requests.
export const db =
drizzle({
schema: { ...schema },
connection: {
url: process.env.DATABASE_URL,
ssl: true,
},
});
export const db =
drizzle({
schema: { ...schema },
connection: {
url: process.env.DATABASE_URL,
ssl: true,
},
});
What are some ideas to have one instance per worker? My workaround is exporting this, but this means every single call to db.xxxx() will call the drizzle function. Will this create a bunch of connections?
export const db = (() =>
drizzle({
schema: { ...schema },
connection: {
url: process.env.DATABASE_URL,
ssl: true,
},
}))();
export const db = (() =>
drizzle({
schema: { ...schema },
connection: {
url: process.env.DATABASE_URL,
ssl: true,
},
}))();
1 Reply
JustWayne
JustWayne3mo ago
This is how I'm setting up drizzle for my Cloudflare Pages project:
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
const client = neon(process.env.DATABASE_URL!);
export const mainDb = drizzle({ client });
import { neon } from '@neondatabase/serverless';
import { drizzle } from 'drizzle-orm/neon-http';
const client = neon(process.env.DATABASE_URL!);
export const mainDb = drizzle({ client });
I think you have to use the @neondatabase/serverless client so that your queries are transmitted over fetch.

Did you find this page helpful?