I'm currently running a SvelteKit application locally and on a server using PM2 and npm run dev
behind a nginx reverse proxy.
All of the above works but it's not perfect as it's not in production mode and I wanted to go the serverless route and try Cloudflare Pages.
Although my application works in both a.m. cases and successfully builds on Cloudflare Pages, it does not work on Cloudflare Pages. It instantly returns a 500 error when I access the URL and in the logs I get the following message
"SyntaxError: Unexpected token 'R', \"ReferenceE\"... is not valid JSON\n at JSON.parse (<anonymous>)\n at Proxy.<anonymous> (bundledWorker-0.9684693903267865.mjs:18147:25)\n at async load (bundledWorker-0.9684693903267865.mjs:778:27)\n at async load_data (bundledWorker-0.9684693903267865.mjs:18065:18)\n at async bundledWorker-0.9684693903267865.mjs:19314:18"
As I do not have access to the files I'm pretty lost on how to further debug this. Any hint what I should do from here as the application works without any problems using
npm run dev
and also npm run build
followed by a npm run preview
?
The application uses data that is fetched from a Strapi graphql endpoint which is what I currently expect not to work properly but the reference error sounds like something is missing that I cannot identify.
What I tried so far:
- Build locally using Node 16 (which I use on Cloudflare Pages) - works
- hardcoded the environment variables as I first thought it might be the problem but I was able to log the environment variables so I guess that's not it
npm run build
andnpm run preview
locally - works
Thanks in advance.
EDIT: Holy mother of Jesus. That took some doing. So...
I used wrangler dev .svelte-kit/cloudflare/_worker.js
to run the equivalent of the Cloudflare Worker locally and be able to debug properly. This gave me an idea where to look (it was the graphql request). After opening the data source (so the .json) in the browser I was able to see that the json did not return correctly but the whole error message was there: ReferenceError: XMLHttpRequest is not defined
.
This together with the debugging using wrangler led me to find that the graphql-request
npm package uses XMLHttpRequest by default (which does not seem to work with Cloudflare Pages) and I simply needed to add fetch
as a parameter to my GraphQLClient implementation (as per https://github.com/jasonkuhrt/graphql-request/issues/395#issuecomment-1279839103) and now it works on Cloudflare Pages as well.