Skip to content

🐛 BUG: fetch is unavailable until it isn’t #1106

@jonathantneal

Description

@jonathantneal

What package manager are you using?

npm

What operating system are you using?

Mac

Describe the Bug

Within the header of an .astro file, external .js files cannot usefetch().

Example

/src/pages/index.astro:

---
import { fetched_metadata } from '../fetched.js'

const metadata = await fetched_metadata
---
<html lang="en">

<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width" />
	<title>{metadata.siteTitle}</title>
</head>

<body>
	<h1>{metadata.siteTitle}</h1>
</body>

</html>

/src/fetched.js:

const fetched_metadata = fetch('http://localhost:3000/metadata.json').then(
	response => response.json()
)

export { fetched_metadata }

/public/metadata.json:

{
  "siteTitle": "Astro"
}

However, if I move the const fetched_metadata logic out of /src/fetched.js and into /src/pages/index.astro it will work.

And then, if I undo that change, it will keep working!

It’s as if using fetch is not allowed in external .js files, until it gets used in an .astro file, at which point it gets put into the global scope and becomes available to the .js files or something.

Steps to Reproduce

  1. Install astro, or create an astro project using npm init astro.
  2. Follow the steps outlined above.
  3. See the errors described above, and the work-around described above.

Link to Minimal Reproducible Example (Optional)

https://github.com/jonathantneal/astro-fetch-outside-astro-issue

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedPlease help with this issue!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions