Call endpoints from the server

Endpoints can be used to serve many kinds of data. This recipe calls a server endpoint from a page’s component script to display a greeting, without requiring an additional fetch request.

  • A project with SSR (output: ‘server’) enabled
  1. Create an endpoint in a new file src/pages/api/hello.ts that returns some data:

    src/pages/api/hello.ts
    import type { APIRoute } from 'astro'
    export const get: APIRoute = () => {
    return new Response(
    JSON.stringify({
    greeting: 'Hello',
    }),
    )
    }
  2. On any Astro page, import the get() method from the endpoint. Call it with the Astro global to provide the request context, and use the response on the page:

    src/pages/index.astro
    ---
    import { get } from './api/hello.ts'
    let response = await get(Astro)
    const data = await response.json()
    ---
    <h1>{data.greeting} world!</h1>

More recipes