Skip to content

Latest commit

 

History

History
44 lines (33 loc) · 1.23 KB

call-endpoints.mdx

File metadata and controls

44 lines (33 loc) · 1.23 KB
title Call endpoints from the server
description Learn how to call endpoints from the server in Astro.
i18nReady true
type recipe

import { Steps } from '@astrojs/starlight/components';

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.

Prerequisites

  • A project with SSR (output: 'server') enabled

Recipe

1. Create an endpoint in a new file `src/pages/api/hello.ts` that returns some data:
```ts title="src/pages/api/hello.ts"
import type { APIRoute } from 'astro'

export const GET: APIRoute = () => {
  return new Response(
    JSON.stringify({
      greeting: 'Hello',
    }),
  )
}
```
  1. 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:

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