Can't issue HTTP Request server-side in Astro

For Workers & Pages, what is the name of the domain?

What is the error message?

Error: Disallowed operation called within global scope. Asynchronous I/O (ex: fetch() or connect()), setting a timeout, and generating random values are not allowed within global scope.

What is the issue or error you’re encountering

I have const data = await getData(); I’m a GET endpoint. Calling it from client-side gives an error.

What steps have you taken to resolve the issue?

I tried a custom API endpoint to call from client side.
I tried fetching the data with the initial page request.

What are the steps to reproduce the issue?

I have a Svelte component that has this:

const response = await fetch('/api/discord-summary');

And on that endpoint, I have something like this:

import { getData } from '../../lib/myDataSource';

export const GET: APIRoute = async ({ request, locals }) => {
  const data = await getData();
  return new Response(JSON.stringify(data), {
    status: 200,
    headers: {
      'Content-Type': 'application/json'
    }
  });
}

Cloudflare gives the error message after the page is loaded and attempting to fetch that data.

I think whatever is going wrong is happening inside the myDataSource module. Is it doing anything in global scope, outside any functions?

That is a good idea – I’ll try removing items from that library routine to figure out exactly what is causing the error.

Hmm… It’s working now!

I don’t know what exactly I changed that fixed it, but the algorithm is generally the same. The only thing I really changed was to fetch environment variables as described in the AstroJS Cloudflare integration docs: @astrojs/cloudflare | Docs.
Astro.locals.runtime.env.DB_PASSWORD
context.locals.runtime.env.DB_PASSWORD

Previously, I was fetching the env vars as described in the AstroJS docs themselves: Using environment variables | Docs.
import.meta.env.DB_PASSWORD

I also had to add a .dev.vars file so Wrangler can use it, and I had to remove the .env file I had. I also had to update the wrangler.toml file ensure the [vars] section was not present, otherwise it would not read the .dev.vars file.

I tried to reproduce the original error message by adding the AstroJS-style, but I wasn’t able to! If I can figure out how to reproduce it, I’ll post back here.