`ReferenceError: XMLHttpRequest is not defined` crashes Next.js API
I've been experiencing inconsistent and sometimes hard-to-reproduce crashes in a fullstack Next.js application hosted on Cloudflare Pages (with @cloudflare/next-on-pages). Only 3 out of 30+ endpoints cause this: where the function runs fully and succeeds, and then every API call afterward will fail with 500 errors
ReferenceError: XMLHttpRequest is not defined. The API remains in a "crashed" state for a few minutes until (what I assume) the Worker restarts itself. The app's page routes load perfectly fine, but no API routes work at all during these few minutes.
The error message is indicative of a Node.js API support issue: a library I'm using seemingly references XMLHttpRequest under the hood which isn't supported in the Edge runtime. I've suspected it was supabase-js (despite using the custom fetch implementation) . I've since refactored the suspect endpoints to only use fetch and no other third-party libraries, yet the same issue happens.
It's also important to note that even though I have a few endpoints that consistently crash the API, there are many other endpoints (containing both read and write operations) that also use supabase-js and even axios that are called many times throughout the app with no crashing whatsoever. It only happenes with a few specific endpoints. The endpoints that begin failing with ReferenceError: XMLHttpRequest is not defined were previously working before the suspect endpoints were called.
After migrating to another hosting provider (with full Node.js support), my API works without crashing. But the team really want to host it on Cloudflare. Can I get any insight on this? Is this crashing+restart behavior common? Any help is much appreciated.1 Reply
Hey I am facing issue, so weird