Skip to content

Consider clarifying data fetching page #7854

@Axelgustavschnurer

Description

@Axelgustavschnurer

📚 Subject area/topic

Data Fetching

📋 Page(s) affected (or suggested, for new content)

https://docs.astro.build/en/guides/data-fetching/

📋 Description of content that is out-of-date or incorrect

Data fetching page currently says:
"All Astro components have access to the global fetch() function in their component script to make HTTP requests to APIs using the full URL (e.g. https://example.com/api or Astro.url + "/api")."

This works as expected for external api's:

Code:

let response = await fetch(`https://full/api/path/data`)
let data: any = await response.json();

Build yields:

12:24:44 ▶ src/pages/page/index.astro
12:24:44   └─ /page/index.html (+761ms)
12:24:45 λ src/pages/data.json.ts
12:24:45   └─ /data.json (+775ms)

However this does not work when using prebuilt static endpoints or SSR endpoints generated at buildtime:

Code:

let response = await fetch(`${Astro.url.origin}/data.json`)
let data: any = await response.json();

OR:

let response = await fetch(`${Astro.url.origin}/api/data`)
let data: any = await response.json();

Build yields:

12:55:55 ▶ src/pages/page/index.astro
12:55:55   └─ /page/index.htmlfetch failed

As pages are not able to build when using neither statically built endpoints or server side endpoints i believe adding examples showing proper usage of or removing the mention of Astro.url + "/api" should be considered. Another issue is that Astro.url in itself is an object which cannot be concatenated with any string as is suggested in the documentation.

🖥️ Reproduction in StackBlitz (if reporting incorrect content or code samples)

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedIssues looking for someone to run with them!improve or update documentationEnhance / update existing documentation (e.g. add example, improve description, update for changes)

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions