Skip to main content

Astro

A recipe list rendered by Astro. The page fetches the recipes in its frontmatter and passes the dehydrated response to a React island, so the HTML already contains the list and the island's hooks start with the same data. Ingredients load in the browser when you open a recipe.

intermediateastrossruseFetchcache
import { Hydrate, type HydrateProps, useFetch } from "@hyper-fetch/react";
import { useState } from "react";

import { client, getRecipe, popularRecipes } from "../lib/api";

const Ingredients = ({ recipeId }: { recipeId: number }) => {
// Not part of the server render: this request starts in the browser when you open a recipe.
const { data, error, loading } = useFetch(
// `select` is a dummyjson query param: the API returns only these fields.
getRecipe.setParams({ recipeId }).setQueryParams({ select: "ingredients" }),
);

if (loading && !data) return <p aria-busy="true">Loading ingredients in the browser...</p>;
if (error || !data) return <p className="error">Could not load the ingredients.</p>;
return <p className="muted">{data.ingredients.join(", ")}</p>;
};

const RecipeList = () => {
const [opened, setOpened] = useState<number | null>(null);
// The first render already has the server data: no loading state and, while it is fresh, no request.
const { data, error, loading, refetch } = useFetch(popularRecipes, {
revalidate: false,
});

if (loading && !data) return <p aria-busy="true">Loading recipes...</p>;
if (error || !data) return <p className="error">Could not load recipes.</p>;

return (
<>
<header className="toolbar muted">
<span>{data.recipes.length} recipes, rendered by Astro</span>
<button type="button" className="outline secondary" onClick={refetch} disabled={loading}>
Refetch in the browser
</button>
</header>
{data.recipes.map((recipe) => (
<article key={recipe.id}>
<strong>{recipe.name}</strong>
<br />
<small className="muted">
{recipe.cuisine} · {recipe.difficulty} · {recipe.prepTimeMinutes} min
</small>
<details open={opened === recipe.id} onToggle={(event) => event.currentTarget.open && setOpened(recipe.id)}>
<summary>Ingredients</summary>
{opened === recipe.id && <Ingredients recipeId={recipe.id} />}
</details>
</article>
))}
</>
);
};

/** The island: `Hydrate` writes the response from the Astro page into the client cache before the hooks mount. */
export const Recipes = ({ hydration }: { hydration: HydrateProps["data"] }) => (
<Hydrate client={client} data={hydration}>
<RecipeList />
</Hydrate>
);
Run locallynpx tiged BetterTyped/hyper-fetch/examples/astro/ssr hyper-fetch-astro-ssr && cd hyper-fetch-astro-ssr && npm install && npm run dev
What it shows
  1. Astro frontmatter sends the request with send() on the server and packs it with dehydrate().
  2. An island prop carries the dehydrated response into the browser. Astro serializes it into the HTML.
  3. Hydrate puts the response into the client cache before the island's hooks mount.
  4. Client-only requests still work as usual inside the island.

How it works​

  1. src/lib/api.ts creates one client and exports popularRecipes, a request with its query params set. The Astro page and the island import the same request, so they build the same cache key.

  2. src/pages/index.astro awaits the request in the frontmatter and renders the island with client:load:

    ---
    const response = await popularRecipes.send();
    const hydration = response.success ? [popularRecipes.dehydrate({ response })] : [];
    ---
    <Recipes client:load hydration={hydration} />

    A failed response is left out, and the island fetches the recipes in the browser instead.

  3. astro.config.mjs adds the React integration. Astro renders Recipes to HTML on the server and hydrates it in the browser with the same props.

  4. Recipes wraps the list in <Hydrate client={client} data={hydration}>. RecipeList calls useFetch(popularRecipes, { revalidate: false }), renders the recipes on its first render and sends no request. "Refetch in the browser" shows that the hook is live after hydration.

  5. Ingredients is not part of the server render. Opening a recipe mounts it, and its useFetch fetches the ingredients in the browser.

  6. The frontmatter runs on every request in astro dev. astro build renders the page once and fetches at build time. To fetch on every request in production, add a server adapter such as @astrojs/node and set output: "server"; the page code stays the same.

When to use it
  • Content sites built with Astro that have a few interactive React parts reading API data.
  • Pages that must ship the data in the HTML, while the island keeps caching and refetching in the browser.

Summary

The Astro page sends the request and passes dehydrate() to a React island as a prop. Hydrate unpacks it into the client cache, so the island renders the server data at once and keeps working like any HyperFetch app.