# JSON-LD

> Reference for <Recipe.JsonLd>, which writes the recipe as schema.org Recipe JSON-LD for search engines' recipe results.

Source: https://recipe-book.siraj.page/reference/react/json-ld/

`<Recipe.JsonLd>` writes the recipe as [schema.org Recipe](https://schema.org/Recipe) JSON-LD in a `<script type="application/ld+json">`, for search engines' recipe results. It must be inside [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md). In Astro, put both in one React component, as the `seo-json-ld` example explains. It writes what [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) from `@recipe-book/react/core/schema-org` returns, and that function's reference lists each field.

## `JsonLd`

app/pancakes/page.tsx
```tsx title="app/pancakes/page.tsx"
import { parseRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  image: '/images/pancakes.jpg',
  servings: 4,
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
    { name: 'egg', plural: 'eggs', quantity: 2 },
    { name: 'maple syrup', note: 'to serve', optional: true },
  ],
  steps: ['Whisk the flour and eggs.', 'Cook ¼-cup portions on a hot griddle.'],
})
if (!result.success) throw result.error
const recipe = result.data

export default function Page() {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.JsonLd url="https://example.com/pancakes" />
    </Recipe.Root>
  )
}
```

This Next.js page renders:

```html
<script type="application/ld+json" data-recipe-json-ld="">{"@context":"https://schema.org","@type":"Recipe","name":"Buttermilk pancakes","image":"https://example.com/images/pancakes.jpg","recipeYield":["4","4 servings"],"recipeIngredient":["1 ½ cups (190 g) all-purpose flour","2 eggs","maple syrup, to serve (optional)"],"recipeInstructions":[{"@type":"HowToStep","text":"Whisk the flour and eggs.","url":"https://example.com/pancakes#buttermilk-pancakes-step-1"},{"@type":"HowToStep","text":"Cook ¼-cup portions on a hot griddle.","url":"https://example.com/pancakes#buttermilk-pancakes-step-2"}]}</script>
```

A relative image is [resolved against `url`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) when `url` is an absolute URL, and written as it is otherwise.

`<Recipe.JsonLd>` escapes every `<` in the script as `\u003c`, so recipe text can't end the script tag.

The props are the [`ToJsonLdOptions`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions) but `idPrefix`, passed to `toJsonLd` as they are. The Root gives `idPrefix`, as [Step IDs](https://recipe-book.siraj.page/reference/react/json-ld.md#step-ids) explains, but none of the props comes from it, so every visitor and every crawler gets the same JSON-LD, even when the page takes `servings` from its URL.

| Name       | Type                                                                                                                     | Description                                                                                                                                                                                                |
| ---------- | ------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `servings` | `number \| undefined`                                                                                                    | The servings to write the recipe at. Defaults to the recipe's own.                                                                                                                                         |
| `system`   | [`System`](https://recipe-book.siraj.page/reference/core/units.md#system) \| `undefined`                                 | The measurement system to write quantities in. Defaults to `recipe.system`, then `'metric'`.                                                                                                               |
| `url`      | `string \| undefined`                                                                                                    | The recipe page's URL. When it's empty or only whitespace, steps have no `url`. See [Step IDs](https://recipe-book.siraj.page/reference/react/json-ld.md#step-ids).                                        |
| `extra`    | [`ToJsonLdOptions['extra']`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions) \| `undefined` | schema.org fields the recipe doesn't model, such as `author`. For an [imported recipe](https://recipe-book.siraj.page/guides/import-recipes.md#store-the-recipe), take the source page's fields out first. |

Any other prop of the `<script>` passes through unchanged, such as `id`, and a `ref` reaches the `<script>` element. `type`, `children`, `dangerouslySetInnerHTML`, and `src` aren't props, because `<Recipe.JsonLd>` sets the type and the content itself. It always sets `data-recipe-json-ld`. `@recipe-book/react` exports the props type as `RecipeJsonLdProps`.

The JSON-LD is in English, whatever the Root's `locale` and `labels` are.

### Step IDs

A step's `url` ends with the `id` that [`<Recipe.Step>`](https://recipe-book.siraj.page/reference/react/steps.md#step) renders for it in the same Root: the Root's [`idPrefix`](https://recipe-book.siraj.page/reference/react/root.md#step-ids), then the step's `id`, percent-encoded.

Each step's fragment replaces any fragment in `url`, so step URLs can't keep a hash route. For a hash-routed page such as `https://example.com/#/pancakes`, the first step's `url` is `https://example.com/#buttermilk-pancakes-step-1`, which the app's router reads as a route, not as the step. Give such a page a path-routed URL, such as `https://example.com/pancakes`, for step URLs that reach their steps.

`idPrefix` defaults to the recipe's `id` and a hyphen, such as the `buttermilk-pancakes-` above. So a Root with only `<Recipe.JsonLd>`, such as one in the `<head>`, writes URLs that point at the steps of another Root with the same recipe. A recipe without an `id` of its own gets one from its name, so renaming it changes its step URLs. Write the recipe an `id`, or give the Root an `idPrefix`, for step URLs that last:

```tsx {3}
export default function Page() {
  return (
    <Recipe.Root recipe={recipe} idPrefix="pancakes-">
      <Recipe.JsonLd url="https://example.com/pancakes" />
      <h2>Method</h2>
      <Recipe.Steps />
    </Recipe.Root>
  )
}
```

Each step's `url` now points at its `<li>`:

```html {6-7}
<script type="application/ld+json" data-recipe-json-ld="">{"@context":"https://schema.org","@type":"Recipe","name":"Buttermilk pancakes","image":"https://example.com/images/pancakes.jpg","recipeYield":["4","4 servings"],"recipeIngredient":["1 ½ cups (190 g) all-purpose flour","2 eggs","maple syrup, to serve (optional)"],"recipeInstructions":[{"@type":"HowToStep","text":"Whisk the flour and eggs.","url":"https://example.com/pancakes#pancakes-step-1"},{"@type":"HowToStep","text":"Cook ¼-cup portions on a hot griddle.","url":"https://example.com/pancakes#pancakes-step-2"}]}</script>
<h2>Method</h2>
<div data-recipe-steps="">
  <div data-recipe-step-section="">
    <ol start="1" data-recipe-step-list="">
      <li id="pancakes-step-1" data-recipe-step=""><span data-recipe-step-text="">Whisk the flour and eggs.</span></li>
      <li id="pancakes-step-2" data-recipe-step=""><span data-recipe-step-text="">Cook ¼-cup portions on a hot griddle.</span></li>
    </ol>
  </div>
</div>
```

The steps and `<Recipe.JsonLd>` must be in one Root, or in Roots with the same `idPrefix`, for the URLs to match. To call [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) yourself next to a Root that keeps its default, pass it the same prefix, `` idPrefix: `${recipe.id}-` ``.

## Warnings

In development, `<Recipe.JsonLd>` logs to the browser console the warnings that `toJsonLd` returns, unless the previous render had the same ones in the same order, in one `console.warn` call: a summary, then the array of warnings. So an equal but new set logs nothing, and warnings that come back after other warnings or a clean render log again. For a recipe without an image, or with one that is empty or only whitespace, it logs [a summary](https://recipe-book.siraj.page/errors.md#react-development-warnings) and then a [`missing_field`](https://recipe-book.siraj.page/errors.md#issue-missing_field) issue at the path `image`. An `image` in `extra` counts, so pass one when the recipe has none. When the recipe's `image` is empty or only whitespace, an `image` in `extra` is written in its place. It resolves against `url` as the recipe's would, so this one is written as `'https://example.com/images/toast.jpg'`:

```tsx {9}
import type { ParsedRecipe } from '@recipe-book/react/core'
import * as Recipe from '@recipe-book/react'

export function ToastJsonLd({ recipe }: { recipe: ParsedRecipe }) {
  return (
    <Recipe.Root recipe={recipe}>
      <Recipe.JsonLd
        url="https://example.com/toast"
        extra={{ image: '/images/toast.jpg' }}
      />
    </Recipe.Root>
  )
}
```

`toJsonLd` lists [every warning](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) it returns. In production, `<Recipe.JsonLd>` logs nothing, and neither does one that renders only on the server, such as in an Astro page without a `client:` directive. There, call `toJsonLd` to read the warnings.

## Pages without a Root

A page that renders no Root, such as a server-only page, calls `toJsonLd` itself and escapes `<` the same way, as [`toJsonLd`'s reference](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) shows.

`extra` can't give an `ImageObject` or several images, because an `image` in it must be a URL string. For those, call `toJsonLd` yourself too, and spread `data` into a new object with your own `image`, as that reference also shows.

## Errors

Throws [`missing_parent`](https://recipe-book.siraj.page/errors/missing_parent.md) when it isn't inside `<Recipe.Root>`:

```txt
RecipeBookError: <Recipe.JsonLd> must be rendered inside <Recipe.Root>.
See https://recipe-book.siraj.page/errors/missing_parent/
```

For a recipe you build that [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) never returns, it can throw [`invalid_argument`](https://recipe-book.siraj.page/errors/invalid_argument.md), as below, or [`unknown_unit`](https://recipe-book.siraj.page/errors/unknown_unit.md) for an ingredient quantity whose unit isn't a unit ID, though it writes some quantities `parseRecipe` never returns, such as a range whose ends are equal or one with an extra key. Equivalents on an ingredient with no quantity aren't checked or written, so the cases below for an equivalent apply only when the ingredient has a quantity. [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md) still throws first for one that isn't an object or has no amount, or whose amount is neither a number nor an object. Either message names `toJsonLd`.

[`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md) checks only that `equipment` is an array, so a recipe you build with a `null` or `undefined` equipment item can throw a `TypeError`, not a `RecipeBookError`, and any other equipment item without a `name`, such as a string, is written as `null` in `tool`.

It throws `invalid_argument` for servings or a yield whose amount is a finite number greater than 0 and whose `max` isn't a finite number greater than it, at any `servings`. The exception is a `max` of `Infinity` on servings, or on the yield of a recipe without servings: it throws only when `servings` sets a scale within 1e-9 of 1. It also throws it for servings whose amount isn't a finite number greater than 0, at any `servings`, and for a yield like that: at any `servings` when the servings amount is valid, and otherwise only when `servings` sets a scale within 1e-9 of 1, as the recipe's own servings do.

It throws `invalid_argument` for an ingredient whose `name` isn't a string, or whose `plural` or `note` is set and isn't one, and for an ingredient's quantity, or one of its equivalents:

- With an amount, or either end of a range, that isn't a finite number greater than 0, with a range whose `min` is greater than its `max`, or with `max` set, as a yield has, at any `servings` and `system`. The message gives the quantity's path after `toJsonLd`. [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md) throws first for one with no amount, or an amount that's neither a number nor an object.
- With an amount that becomes `Infinity` or 0 at another `servings` or `system`, such as an amount of `1e308` at 2×. The message gives what it became.

For flour whose quantity is `{ amount: { min: 2, max: 1 }, unit: 'cup' }`:

```txt
RecipeBookError: toJsonLd: ingredients[0].items[0].quantity: range minimum (2) must not be greater than the maximum (1).
See https://recipe-book.siraj.page/errors/invalid_argument/
```

It throws `unknown_unit` for an ingredient's quantity, or one of its equivalents, whose unit isn't a unit ID, at any `servings` and `system`, unless it throws `invalid_argument` first, as for an amount of 0, or an amount of `1e308` at 2×. For flour whose quantity is `{ amount: 1.5, unit: 'cups' }`, not `'cup'`:

```txt
RecipeBookError: toJsonLd: unit must be a unit id such as "g", "ml", or "cup", received "cups". findUnit converts author text to ids; parseQuantity also suggests a fix for a misspelling.
See https://recipe-book.siraj.page/errors/unknown_unit/
```

## Named imports

To import `<Recipe.JsonLd>` by name, import `JsonLd`. If the name clashes with one of yours, alias it, as in `import { JsonLd as RecipeJsonLd } from '@recipe-book/react'`.
