neondatabase / serverless

Connect to Neon PostgreSQL from serverless/worker/edge functions
https://www.npmjs.com/package/@neondatabase/serverless
MIT License
334 stars 14 forks source link

Cloudflare Pages compatibility: XMLHttpRequest is not defined #98

Open LilaRest opened 1 week ago

LilaRest commented 1 week ago

Hey there!

I just spent 3 hours fixing an XMLHttpRequest is not defined error that occurred when running the serverless driver on edge runtime (CF Pages in this case).

The documentation recommends the following setup to work in a serverless environment:

import { Pool, neonConfig } from '@neondatabase/serverless';

import ws from 'ws';
neonConfig.webSocketConstructor = ws;

However, if you want to run your code on edge, you'll need to apply this config instead:

import { Pool, neonConfig } from '@neondatabase/serverless';

// no "ws" anymore
neonConfig.poolQueryViaFetch = true;
neonConfig.fetchFunction = fetch;

@jawj, I'm creating this issue for reference, but maybe it could even be documented in the README? What do you think?

Enjoy your day guys, And thanks for this awesome lib!

jawj commented 1 week ago

Thanks @LilaRest. Can you point me to which documentation recommended that? It's only necessary to provide a WebSocket library on Node and other WebSocket-less platforms.

It also should not be necessary to set fetch as the fetchFunction (that will be the default), and you only need poolQueryViaFetch to speed up one-shot queries or if WebSockets are not available and you still want to use the Pool object.

LilaRest commented 1 week ago

Update on this, I've been confused because some functions of the Clerk server library were producing the same error, once this solved, the only way I've managed to make the Neon serverless driver work on Cloudflare Pages is by not setting any neonConfig.* parameter.

My guess is that the ws package is not compatible with v8 runtime. I wonder what Websocket client the serverless driver is using if none is explicitely defined though.

The README could mention in a brief way that: "If you're trying to run this driver on edge runtimes (e.g., Cloudflare Pages, Vercel Edge Functions) you MUST NOT set the neonConfig.webSocketConstructor to ws"