Recipe Book0.6.0

2.8Guides

Server-render a recipe

Parse a recipe on the server in Next.js, React Router, Astro, or your own server, render it with <Recipe.Root>, see what hydration changes, and save the reader's choices with a form action.

§ 2.810 min readView as Markdown

Parse the recipe input on the server, and pass only the parsed recipe to <Recipe.Root>. The server renders the parts to HTML, React hydrates them in the browser, and a production build keeps the parser out of the browser’s JavaScript. Why parse on the server explains the rule.

Next.js App Router

An App Router page is a Server Component, so it parses the recipe input itself and passes result.data to <Recipe.Root>. Render a recipe in React builds that page as app/recipes/[slug]/page.tsx, and the nextjs-app-router example parses the sample recipe the same way in its app/page.tsx.

Next.js Pages Router

A Pages Router page parses the recipe input in getStaticProps, which runs only on the server, and gets the recipe as a prop. This page builds /recipes/pancakes from the Next.js example’s app/recipe.ts, which Render a recipe in React shows, saved as recipe.ts in your app’s root folder:

pages/recipes/[slug].tsx
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import type { GetStaticPropsContext, InferGetStaticPropsType } from 'next'
import { pancakes } from '../../recipe'

const recipes: Record<string, unknown> = { pancakes }

export function getStaticPaths() {
  return {
    paths: Object.keys(recipes).map((slug) => ({ params: { slug } })),
    fallback: false,
  }
}

export function getStaticProps({
  params,
}: GetStaticPropsContext<{ slug: string }>) {
  const result = parseRecipe(recipes[params!.slug])
  if (!result.success) throw result.error
  return { props: { recipe: result.data } }
}

export default function Page({
  recipe,
}: InferGetStaticPropsType<typeof getStaticProps>) {
  return (
    <Recipe.Root recipe={recipe}>
      <h1>{recipe.name}</h1>
      <Recipe.ServingsSelect />
      <Recipe.SystemToggle />
      <h2>Ingredients</h2>
      <Recipe.Ingredients />
      <h2>Steps</h2>
      <Recipe.Steps />
    </Recipe.Root>
  )
}

next build keeps the parser out of the page’s JavaScript with webpack and, from Next.js 15.3, with Turbopack, even when the page’s component imports other functions from @recipe-book/react/core. In a project with no app directory, as here, next dev serves the parser in the page’s JavaScript with webpack, its default before Next.js 16. It doesn’t with Turbopack, or once the project has an app directory, even one with no routes. A recipe that doesn’t parse fails next build with the invalid_recipe error. The error’s message lists the first 10 issues and how many more there are, and error.issues has them all. To parse on each request instead, replace getStaticPaths and getStaticProps with getServerSideProps, type the page’s props with InferGetServerSidePropsType<typeof getServerSideProps>, and return { notFound: true } for a slug that has no recipe.

React Router

In framework mode, a React Router route parses the recipe input in its loader, which runs on the server, and gets the recipe as loaderData. React Router 8 needs React 19.2.7 or newer. @recipe-book/react supports earlier React versions too, back to React 18.2, so before React 19.2.7, use React Router 7 in framework mode: the route is the same. The react-router-ssr example serves this route at /. Its recipe input in app/recipe.ts and its image in public/pancakes.svg are the Next.js example’s, which Render a recipe in React shows:

app/routes/pancakes.tsx
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { pancakes } from '../recipe'
import type { Route } from './+types/pancakes'

export function loader() {
  const result = parseRecipe(pancakes)
  if (!result.success) throw result.error
  return result.data
}

export default function Pancakes({ loaderData }: Route.ComponentProps) {
  return (
    <main>
      <Recipe.Root recipe={loaderData}>
        <Recipe.JsonLd url="https://example.com/" />
        <Recipe.Image alt="" width={600} height={400} />
        <h1>{loaderData.name}</h1>
        <Recipe.ServingsSelect />
        <Recipe.SystemToggle />
        <h2>Ingredients</h2>
        <Recipe.Ingredients />
        <h2>Steps</h2>
        <Recipe.Steps />
      </Recipe.Root>
    </main>
  )
}

Register the route in app/routes.ts, as the example does with index('routes/pancakes.tsx'), or with route('pancakes', 'routes/pancakes.tsx') to serve it at /pancakes. react-router dev and react-router typegen write the route’s ./+types/pancakes types, but only for a route registered there, so until then tsc can’t find ./+types/pancakes. The production build’s browser JavaScript doesn’t include the parser. Because the loader runs on each request, a recipe that doesn’t parse doesn’t fail react-router build. Instead, the loader throws the invalid_recipe error, and the page responds with a 500 status. In development, React Router’s error page shows the error. In production, the page hides the error, and the server logs it.

To show the recipe in another language, return the language code from the loader, not a label pack, which can’t go through loaderData.

Astro

An Astro page parses the recipe input in its frontmatter, which runs on the server. In a static page, Astro’s default, the frontmatter runs once, when astro build renders the page. Astro renders React components only with its React integration, so add it with npx astro add react, which installs @astrojs/react and adds it to your Astro config. The astro-island example builds this page. Its recipe input in src/recipe.ts and its image in public/pancakes.svg are the Next.js example’s, which Render a recipe in React shows:

src/pages/index.astro
---
import { parseRecipe } from '@recipe-book/react/core'
import { pancakes } from '../recipe'
import { RecipeCard } from '../recipe-card'
import { StructuredData } from '../structured-data'
import '../styles.css'

const result = parseRecipe(pancakes)
if (!result.success) throw result.error

const recipe = result.data
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" href="data:," />
    <title>{recipe.name}</title>
    <StructuredData
      recipe={recipe}
      url={Astro.site && new URL(Astro.url.pathname, Astro.site).href}
    />
  </head>
  <body>
    <main>
      <img src={recipe.image} alt="" width="600" height="400" />
      <h1>{recipe.name}</h1>
      <RecipeCard client:load recipe={recipe} />
    </main>
  </body>
</html>

The page imports src/styles.css, which keeps the image inside the page, makes the servings select and the measurement system options at least 24 pixels tall, and bolds the checked measurement system:

src/styles.css
img {
  max-width: 100%;
  height: auto;
}

[data-recipe-servings-select],
[data-recipe-system-option] {
  min-height: 24px;
}

[data-recipe-system-option][data-state='checked'] {
  font-weight: bold;
}

Astro renders each React component on the page to HTML, unless it has client:only. Only a component with a client: directive is an island, which React hydrates in the browser, or renders there with client:only. RecipeCard has client:load, so React hydrates it when the page loads:

src/recipe-card.tsx
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function RecipeCard({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.ServingsSelect />
      <Recipe.SystemToggle />
      <h2>Ingredients</h2>
      <Recipe.Ingredients />
      <h2>Steps</h2>
      <Recipe.Steps />
    </Recipe.Root>
  )
}

Astro serializes an island’s props into the page. A parsed recipe is plain JSON data, so the card hydrates with the recipe that the frontmatter parsed. Without client:load, the built page loads no JavaScript, and the card stays as HTML: choosing a number of servings doesn’t rescale the ingredients, and the units toggle doesn’t respond. The seo-json-ld example renders the ingredients and steps in the .astro file instead, and its built page loads no JavaScript either.

Astro renders each React component in an .astro file as its own tree, and renders the children you pass it on their own. So a <Recipe.JsonLd> placed inside <Recipe.Root> in the .astro file can’t find its Root, and the build fails with the missing_parent error. Each island is its own tree too, so a part in one island can’t read a Root in another, and two islands that each have their own Root keep their own servings and measurement system. Put <Recipe.JsonLd> and its Root in one React component, which the page renders in <head> with no client: directive:

src/structured-data.tsx
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function StructuredData({
  recipe,
  url,
}: {
  recipe: ParsedRecipe
  url: string | undefined
}) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.JsonLd url={url} />
    </Recipe.Root>
  )
}

The page passes the component its URL for <Recipe.JsonLd url>, so the JSON-LD writes the recipe’s image as an absolute URL, which Google requires, and each step’s url points at that step in the card: both Roots give the steps the same ids. The page makes the URL from site in your Astro config and the page’s path, so set site to your site’s address, as the example sets https://example.com. Astro makes Astro.url from site only when astro build renders a static page. On a page that sets export const prerender = false, which renders on each request, Astro.url comes from the request instead. With the Node adapter, it names localhost, even with site set, unless security.allowedDomains in your Astro config lists the request’s host. The URL the page makes names your site either way. Without site, the page passes no url, and the JSON-LD writes the image as the recipe gives it.

A recipe that doesn’t parse fails astro build with the invalid_recipe error. In development, the page responds with a 500 status, and Astro’s error overlay shows the error. A page that sets export const prerender = false runs its frontmatter on each request, so astro build passes once you add a server adapter, such as with npx astro add node. The built server then responds with a 500 status when the recipe doesn’t parse, but with a 200 status and a page that ends in “Internal server error” when a component throws, such as a part outside its Root. It logs both errors.

Your own server

Without a framework, render the page with renderToString from react-dom/server on the server, and hydrate it with hydrateRoot from react-dom/client in the browser. Both render the same component:

src/recipe-page.tsx
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function RecipePage({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <h1>{recipe.name}</h1>
      <Recipe.ServingsSelect />
      <Recipe.SystemToggle />
      <h2>Ingredients</h2>
      <Recipe.Ingredients />
      <h2>Steps</h2>
      <Recipe.Steps />
    </Recipe.Root>
  )
}

The server entry parses the quickstart’s sample recipe input, saved as src/recipe.ts. It returns the page’s HTML and the parsed recipe as JSON:

src/entry-server.tsx
import { parseRecipe } from '@recipe-book/react/core'
import { renderToString } from 'react-dom/server'
import { pancakes } from './recipe'
import { RecipePage } from './recipe-page'

export function render() {
  const result = parseRecipe(pancakes)
  if (!result.success) throw result.error
  return {
    html: renderToString(<RecipePage recipe={result.data} />),
    json: JSON.stringify(result.data).replace(/</g, '\\u003c'),
  }
}

A parsed recipe is plain JSON data, so JSON.stringify keeps all of it. Escape every < as \u003c, so recipe text can’t end the script tag that holds the JSON. Otherwise, a step whose text has </script><script> in it runs that script, and the page doesn’t hydrate.

The browser entry reads the recipe back and hydrates the page:

src/entry-client.tsx
import type { Recipe } from '@recipe-book/react/core'
import { hydrateRoot } from 'react-dom/client'
import { RecipePage } from './recipe-page'

const recipe: Recipe = JSON.parse(
  document.getElementById('recipe')!.textContent!,
)
hydrateRoot(document.getElementById('root')!, <RecipePage recipe={recipe} />)

The relative imports leave out file extensions, as Vite allows. To type-check them with tsc, set "module": "ESNext" and "moduleResolution": "Bundler" in your tsconfig.json, as the Vite example’s tsconfig.json does.

Your server puts html inside the page’s <div id="root"> and json in a <script type="application/json" id="recipe">. To fill placeholders in an HTML template with replace, pass each value as a function, as in template.replace('<!--app-json-->', () => json). A replacement string reads $& and $' as patterns, so a step whose text has them in it pastes parts of the template into the page, and the page doesn’t hydrate. If you use Vite, its server-side rendering guide sets up that server for development and production. Build the browser entry with vite build --outDir dist/client and the server entry with vite build --outDir dist/server --ssr src/entry-server.tsx. Set "type": "module" in your package.json, or Vite names the server build entry-server.mjs instead of the entry-server.js that the guide’s server imports. The server build imports @recipe-book/react and @recipe-book/react/core from node_modules, and Node runs both without a bundler. If the recipe input doesn’t parse, render throws the invalid_recipe error, so catch it in your server and respond with an error status.

What changes after hydration

The server renders the recipe at the Root’s starting servings and measurement system, and React hydrates the same HTML. Four things can change after that:

  • When no ingredient can convert, <Recipe.SystemToggle> renders disabled on the server. If a <Recipe.StepText> or <Recipe.ConvertedStepText> in the Root shows a temperature, or a <Recipe.ConvertedStepText> shows a mass or volume that one of the systems would convert, the toggle enables once React hydrates the page, because each counts once it mounts in the browser. <Recipe.Steps> shows each step’s text through a <Recipe.StepText>, so on this page, a step with a temperature is enough.
  • <Recipe.CookMode> renders disabled on the server, because the server can’t tell whether the reader’s browser can keep the screen on. Once React hydrates the page, it’s enabled, or gone in a browser without the Screen Wake Lock API.
  • A measurement system the reader saved in localStorage applies only after hydration. To render it on the server, keep it in a cookie and read it with readRecipeView, as Remember the reader’s choice shows. Share servings in a link does the same for servings in the URL.
  • Ticks saved in localStorage apply only after hydration too. The server renders a <Recipe.Checklist> with its default ticks, and the example in Remember the ticks ticks the saved ones once React hydrates the page.

Save the reader’s choices with a form action

On React 19, a form’s action can be a function, such as a Server Action in the Next.js App Router, and useActionState keeps what that function returns. This Server Action reads the servings and the ticked steps from the form, and returns them, or an error:

app/recipes/[slug]/actions.ts
'use server'

export type Choices = { servings?: number; steps?: string[]; error?: string }

export async function saveChoices(
  previous: Choices,
  form: FormData,
): Promise<Choices> {
  const steps = form.getAll('steps').map(String)
  const servings = Number(form.get('servings'))
  if (!(servings > 0)) return { steps, error: 'Enter a number of servings.' }
  return { servings, steps }
}

SavedRecipe puts the form inside the Root, names the servings input and each step’s checkbox, and starts the Root and the Checklist from the saved choices. In the page from Render a recipe in React, render <SavedRecipe recipe={result.data} /> in place of <Recipe.Root>:

app/recipes/[slug]/saved-recipe.tsx
'use client'

import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'
import { useActionState } from 'react'
import { saveChoices } from './actions'

export function SavedRecipe({ recipe }: { recipe: ParsedRecipe }) {
  const [saved, formAction, pending] = useActionState(saveChoices, {})

  return (
    <Recipe.Root recipe={recipe} defaultServings={saved.servings}>
      <form action={formAction}>
        <Recipe.ServingsInput name="servings" />
        <Recipe.Checklist defaultCheckedSteps={saved.steps}>
          <Recipe.StepList>
            {(step) => (
              <Recipe.Step item={step}>
                <label>
                  <Recipe.StepCheckbox name="steps" value={step.id} />{' '}
                  <Recipe.StepText />
                </label>
              </Recipe.Step>
            )}
          </Recipe.StepList>
        </Recipe.Checklist>
        {saved.error && <p role="alert">{saved.error}</p>}
        <button disabled={pending}>Save</button>
      </form>
    </Recipe.Root>
  )
}

Once React has hydrated the page, a submit doesn’t reload it, so the Root and the Checklist keep the reader’s choices. Before then, or with JavaScript off, the browser posts the form itself, and Next.js runs the action and responds with the page rendered from the state the action returned. defaultServings and defaultCheckedSteps start that page’s Root and Checklist from the saved choices. Without them, the page starts over at the recipe’s servings, with no steps ticked.

Return an error in the state instead of throwing it, as saveChoices does when servings isn’t a number above 0, and the page shows it with the Root still there. When the action throws, React shows the nearest error boundary above the component that calls useActionState, as React’s useActionState reference describes. For SavedRecipe, that boundary is above the Root, such as the route’s error.tsx or Next.js’s error page, so the Root and the reader’s choices are gone.

React 18 doesn’t take a function as action: it leaves the attribute out, and in development it logs a warning. On React 18, handle the form’s onSubmit instead.

Next steps

Contents