Error: Cannot perform I/O on behalf of a different request with postgresql + kysely
Answered
Anay-208 | Ping on replies posted this in #help-forum
I've setup a postgresql db and using kysely to interact with it.
-# db/index.ts
-# page.tsx
Now, For the first request towards the deployment on Cloudflare pages, it works completely fine, however, I get this error:
I also noticed this blog, but I already tried not to reuse db connection the code:
https://community.cloudflare.com/t/error-cannot-perform-i-o-on-behalf-of-a-different-request/617112
-# db/index.ts
import { Kysely, PostgresDialect, Transaction } from "kysely";
import { type DB } from "./schema.js";
import { Pool, types } from "@neondatabase/serverless"
if (!process.env.DATABASE_URL) {
throw new Error("DATABASE_URL is not defined");
}
types.setTypeParser(types.builtins.NUMERIC, (val : string) => {
return parseFloat(val);
})
// I used getDb as an attempt to fix this bug
export function getDb() : Kysely<DB> {
const pool = new Pool({
connectionString: process.env.DATABASE_URL
});
return new Kysely<DB>({
dialect: new PostgresDialect({ pool })
})
}
export { sql } from "kysely";
export type TransactionDB = Transaction<DB>;
export type KyselyDB = Kysely<DB>;
-# page.tsx
const db = getDb()
export default async function Page() {
// imported from clerk
const { userId, redirectToSignIn} = await auth();
if(!userId){
redirectToSignIn()
}
const data = await db
.selectFrom("users")
.where("id", "=", userId)
.executeTakeFirst();
// do something
Now, For the first request towards the deployment on Cloudflare pages, it works completely fine, however, I get this error:
X [ERROR] 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/O type: Native)
X [ERROR] Error: The script will never generate a response.
I also noticed this blog, but I already tried not to reuse db connection the code:
https://community.cloudflare.com/t/error-cannot-perform-i-o-on-behalf-of-a-different-request/617112
Answered by Anay-208 | Ping on replies
So to fix, I needed to:
- initialise db on the funciton
- Destroy db after use on the same function
- initialise db on the funciton
- Destroy db after use on the same function
1 Reply
So to fix, I needed to:
- initialise db on the funciton
- Destroy db after use on the same function
- initialise db on the funciton
- Destroy db after use on the same function
Answer