Search code examples
javascriptjsonbuildfetch-apiastrojs

What determines build order in Astro?


I am building a website using Astro in which i share database data in many different pages. I have a members.json.ts file in the project root from which i then fetch data as such:

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

I can't seem to find anything about build order in the Astro documentation. Is there any way i can ensure that my members.json.ts file has finished building when i fetch the data from each page? Or is there any other preferred way of doing this?


Solution

  • This is considered an anti-pattern. Instead of passing data through requests, you can abstract your members.json.ts API into a separate module and export a function (or whatever you want) for use inside other files, something like this:

    Create a common module:

    /src/members.ts
    export function getMembers() {
      return { // member data }
    }
    

    Using the module:

    /src/pages/members.json.ts
    import { getMembers } from '../../members'
    
    export async function GET() {
      return new Response(JSON.stringify(getMembers()))
    }
    
    /src/pages/index.astro
    ---
    import { getMembers } from '../members'
    
    const data = getMembers()
    ---