# Author recipes

> Write recipe input with quantities, equivalents, ingredient lines, regional decimals and units, sections, times, notes, equipment, links, nutrition, and IDs, and catch mistakes as you type.

Source: https://recipe-book.siraj.page/guides/author-recipes/

Write each recipe as recipe input: a plain object that TypeScript checks with `satisfies` [`RecipeInput`](https://recipe-book.siraj.page/reference/core/types.md#recipeinput). [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) then turns it into a [`Recipe`](https://recipe-book.siraj.page/reference/core/types.md#recipe) that your code can read in one shape. Only `name` is required: a recipe without `ingredients` or `steps` still parses, with an [`empty_list`](https://recipe-book.siraj.page/errors.md#issue-empty_list) warning for each. Most fields take the short form you'd write on a recipe card. In a React app, replace `@recipe-book/core` with `@recipe-book/react/core` in this page's imports.

examples/node-script/src/recipe.ts
```ts title="examples/node-script/src/recipe.ts"
import type { RecipeInput } from '@recipe-book/core'

export const pancakes = {
  name: 'Buttermilk pancakes',
  servings: 4,
  times: { prep: 10, cook: 15 },
  ingredients: [
    { name: 'all-purpose flour', quantity: '1 ½ cups', equivalents: ['190 g'] },
    { name: 'sugar', quantity: '2 tbsp', equivalents: ['25 g'] },
    { name: 'baking powder', quantity: '2 tsp' },
    { name: 'buttermilk', quantity: '1 ¼ cups' },
    { name: 'egg', plural: 'eggs', quantity: 2 },
    {
      name: 'butter',
      quantity: '3 tbsp',
      note: 'melted',
      equivalents: ['42 g'],
    },
    { name: 'maple syrup', note: 'to serve' },
  ],
  steps: [
    'Whisk the dry ingredients in a large bowl.',
    'Whisk the buttermilk, eggs, and butter, then fold into the dry ingredients.',
    'Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.',
  ],
} satisfies RecipeInput
```

`satisfies` checks the recipe input without widening its type. Parse it to get the recipe:

```ts
import { parseRecipe } from '@recipe-book/core'
import { pancakes } from './recipe.ts'

const result = parseRecipe(pancakes)

if (!result.success) {
  throw result.error
}

result.data.ingredients[0]?.items[0] // { id: 'all-purpose-flour', name: 'all-purpose flour', quantity: { amount: 1.5, unit: 'cup' }, equivalents: [{ amount: 190, unit: 'g' }], optional: false }
result.data.system // 'us'
```

Recipe input is plain data, so it can also come from a JSON file, a YAML file, a CMS, or an API. `satisfies` can't check data that arrives at runtime, but `parseRecipe` does, and [Validate recipes](https://recipe-book.siraj.page/guides/validate-recipes.md#read-issues) shows how to read its issues.

`servings` is how many servings the recipe makes. For a batch, write `yield` with a unit, such as `'24 cookies'`. [`ServingsInput`](https://recipe-book.siraj.page/reference/core/types.md#servingsinput) and [`YieldInput`](https://recipe-book.siraj.page/reference/core/types.md#yieldinput) list the forms each takes. Write one of them so readers can choose how much to make, such as 4 servings or 48 cookies. A recipe with neither scales only by a multiplier, so [`<Recipe.ServingsSelect>`](https://recipe-book.siraj.page/reference/react/servings.md#servingsselect) offers 1×, 2×, and 3×, as [Scale a recipe](https://recipe-book.siraj.page/guides/scale-a-recipe.md#servings-and-yield) explains.

A recipe has no field for its author, cuisine, category, keywords, rating, video, diet, difficulty, or allergens. `satisfies RecipeInput` rejects one, and `parseRecipe` ignores it with an [`unknown_field`](https://recipe-book.siraj.page/errors.md#issue-unknown_field) warning, so keep them in your own data next to the recipe. To publish one in the recipe's JSON-LD, pass it to [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonldoptions) or [`<Recipe.JsonLd>`](https://recipe-book.siraj.page/reference/react/json-ld.md#jsonld) in `extra` under its schema.org name, if it has one, such as `recipeCuisine` for a cuisine or `suitableForDiet` for a diet. Write tips and substitutions as [notes](https://recipe-book.siraj.page/guides/author-recipes.md#add-notes-equipment-and-links).

## Write quantities

Write a quantity as text, as a number for a count, or as an object:

| Recipe input                                   | Quantity                                       |
| ---------------------------------------------- | ---------------------------------------------- |
| `'1 ½ cups'`, `'1 1/2 cups'`, or `'1.5 cups'`  | `{ amount: 1.5, unit: 'cup' }`                 |
| `'2-3 tbsp'`, `'2–3 tbsp'`, or `'2 to 3 tbsp'` | `{ amount: { min: 2, max: 3 }, unit: 'tbsp' }` |
| `'a pinch'`                                    | `{ amount: 1, unit: 'pinch' }`                 |
| `'250g'` or `'250 g'`                          | `{ amount: 250, unit: 'g' }`                   |
| `2` or `'2'`                                   | `{ amount: 2 }`                                |
| `{ amount: { min: 2, max: 3 }, unit: 'tbsp' }` | `{ amount: { min: 2, max: 3 }, unit: 'tbsp' }` |

A count has no unit, so give the ingredient a `plural`, as the pancakes recipe does for eggs. Leave `quantity` out for an ingredient you don't measure, such as maple syrup to serve, and set `optional: true` on one the recipe works without. [Units](https://recipe-book.siraj.page/reference/core/units.md#units) lists every unit and its aliases. The list is fixed, so instead of a custom unit for a measure it doesn't have, such as a knob, write a count and move the word into the name: `{ name: 'knob of butter', plural: 'knobs of butter', quantity: 2 }`.

The units also decide which measurement system the recipe is written in, `result.data.system`: the one with more ingredients whose `quantity` has a unit of only that system, such as cups for US or grams for metric. Equivalents don't count, and neither do counts or units of both systems, such as tbsp and pinch. A recipe measured only in those has no system, so [`<Recipe.Root>`](https://recipe-book.siraj.page/reference/react/root.md) falls back to metric, and [`<Recipe.StepText>`](https://recipe-book.siraj.page/reference/react/steps.md#steptext) shows a baking step's `375°F` as `190 °C`. Set `system: 'us'` or `system: 'metric'` to say which you wrote it in. [`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) says how it breaks a tie.

### Catch typos as you type

`satisfies RecipeInput` checks that each quantity ends in a known unit alias, so a misspelled unit fails to compile:

src/recipe.ts
```ts title="src/recipe.ts" {5}
import type { RecipeInput } from '@recipe-book/core'

export const pancakes = {
  name: 'Buttermilk pancakes',
  ingredients: [{ name: 'buttermilk', quantity: '2 cupz' }],
} satisfies RecipeInput
```

```text
src/recipe.ts(5,39): error TS2322: Type '"2 cupz"' is not assignable to type 'QuantityInput | undefined'.
```

The type checks only the ending, except that a unit with no space before it needs a plain number: `'250g'` type-checks, but `'½g'` doesn't, although `parseRecipe` reads both. `parseRecipe` checks the amount at runtime, so `'0 cups'` type-checks but doesn't parse. [`QuantityString`](https://recipe-book.siraj.page/reference/core/types.md#quantitystring) lists the forms the type accepts.

## Add equivalents

An equivalent is an alternative quantity that you've measured yourself, such as `190 g` for `1 ½ cups` of flour. List equivalents in order of preference, and check a single ingredient with [`IngredientInput`](https://recipe-book.siraj.page/reference/core/types.md#ingredientinput):

```ts
import type { IngredientInput } from '@recipe-book/core'

export const flour = {
  name: 'all-purpose flour',
  quantity: '1 ½ cups',
  equivalents: ['190 g', '6.7 oz'],
} satisfies IngredientInput
```

An ingredient with equivalents needs a `quantity`. [`resolveIngredient`](https://recipe-book.siraj.page/reference/core/resolving.md#resolveingredient) lists which of them a measurement system shows.

## Write ingredients as text

An ingredient can also be a line of text, such as `'1 ½ cups flour, sifted'`. Pass [`parseIngredientLine`](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline) to `parseRecipe` to read each line into a quantity, a name, and a note. Mix lines with objects:

```ts {7,13}
import { parseIngredientLine, parseRecipe } from '@recipe-book/core'

const result = parseRecipe(
  {
    name: 'Buttermilk pancakes',
    ingredients: [
      '1 ½ cups flour, sifted',
      '2 large eggs',
      { name: 'maple syrup', note: 'to serve' },
    ],
    steps: ['Whisk the batter.', 'Cook on a buttered griddle.'],
  },
  { parseIngredientLine },
)

if (!result.success) {
  throw result.error
}

result.data.ingredients[0]?.items[0] // { id: 'flour', name: 'flour', quantity: { amount: 1.5, unit: 'cup' }, equivalents: [], note: 'sifted', optional: false }
result.data.ingredients[0]?.items[1] // { id: 'large-egg', name: 'large egg', plural: 'large eggs', quantity: { amount: 2 }, equivalents: [], optional: false }
```

Write each line as you would on a recipe card: the quantity, then the name, then a comma and any note or `optional`. Put an equivalent in parentheses after the quantity, as in `'1 ½ cups (190 g) flour, sifted'`. A quantity after a comma is part of the note, so the 2 cups in `'flour, 2 cups'` don't scale or convert, and there's no warning. [The parts of a line](https://recipe-book.siraj.page/reference/core/parsing.md#parseingredientline) lists every form each one takes.

A line it can't read, such as `'2 or 3 eggs'`, keeps the whole line as the name, and `result.warnings` gets an issue that says how to fix it. A sign, `NaN`, or `Infinity` at the start isn't an amount, so `'-2 eggs'` keeps the whole line as the name with no warning, as `'salt'` does. It reads a misspelled unit as the start of the name, so `'2 cupz flour'` is 2 of an ingredient named `cupz flour`. Check the spelling of each unit. That line's warning is an [`unknown_unit`](https://recipe-book.siraj.page/errors.md#issue-unknown_unit) issue whose `suggestion` is `'cups'`.

Check recipe input that has lines with `satisfies RecipeInput<string>`. It doesn't check a line's text, so use an object when you want a misspelled unit to fail to compile.

## Read regional recipes

Pass `decimal: ','` for a recipe that writes decimals with a comma. A comma between digits that can only be a decimal, as in `'0,5 l'`, reads with no option, but a number such as `'1,500'` could be 1500 or 1.5, so it's an issue without the option:

```ts {9}
import { parseIngredientLine, parseRecipe } from '@recipe-book/core'

const result = parseRecipe(
  {
    name: 'Brot',
    ingredients: ['1,500 kg Mehl', '0,5 l Wasser'],
    steps: ['Den Teig kneten.'],
  },
  { parseIngredientLine, decimal: ',' },
)

if (!result.success) {
  throw result.error
}

result.data.ingredients[0]?.items.map((item) => item.quantity) // [{ amount: 1.5, unit: 'kg' }, { amount: 0.5, unit: 'l' }]
```

Australian recipes measure with a 250 mL cup and a 20 mL tablespoon, but text can't say which cup it means. Pass `units` to read every cup or tablespoon in text as `cup-metric` or `tbsp-au`. The option reads text only, so write those units in a quantity object, as the coconut does:

```ts {13}
import { parseIngredientLine, parseRecipe } from '@recipe-book/core'

const result = parseRecipe(
  {
    name: 'Anzac biscuits',
    ingredients: [
      '1 cup rolled oats',
      '2 tbsp golden syrup',
      { name: 'coconut', quantity: { amount: 1, unit: 'cup-metric' } },
    ],
    steps: ['Mix, then bake.'],
  },
  { parseIngredientLine, units: { cup: 'cup-metric', tbsp: 'tbsp-au' } },
)

if (!result.success) {
  throw result.error
}

result.data.ingredients[0]?.items.map((item) => item.quantity) // [{ amount: 1, unit: 'cup-metric' }, { amount: 2, unit: 'tbsp-au' }, { amount: 1, unit: 'cup-metric' }]
result.data.system // 'metric'
```

Formatting writes the metric cup and the Australian tablespoon as cup and tbsp, as the author wrote them, and [converting](https://recipe-book.siraj.page/guides/convert-units.md) uses their own sizes. [`ParseQuantityOptions`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantityoptions) lists both options. To render these recipes in React, pass `result.data` to `<Recipe.Root>` as its `recipe`, as [Read ingredient lines](https://recipe-book.siraj.page/reference/react/root.md#read-ingredient-lines) does.

## Group ingredients and steps into sections

Split a long list of ingredients or steps into sections, such as the batter and what to serve with it. Any entry with `items` is a section. Give it a `title`, and mix sections with loose items:

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  ingredients: [
    {
      title: 'Batter',
      items: [
        { name: 'all-purpose flour', quantity: '1 ½ cups' },
        { name: 'buttermilk', quantity: '1 ¼ cups' },
      ],
    },
    { title: 'To serve', items: [{ name: 'maple syrup' }] },
  ],
  steps: ['Whisk the batter.', 'Cook on a buttered griddle.'],
})

if (!result.success) {
  throw result.error
}

result.data.ingredients.map((section) => section.id) // ['batter', 'to-serve']
result.data.steps // [{ id: 'steps', items: [{ id: 'step-1', text: 'Whisk the batter.' }, { id: 'step-2', text: 'Cook on a buttered griddle.' }] }]
```

Each run of loose items becomes an untitled section, so the result always has one shape, even when you write a flat list. Sections can't be nested, so `parseRecipe` fails on a section inside another. Steps work the same way, and each step is a string or a [`StepInput`](https://recipe-book.siraj.page/reference/core/types.md#stepinput). Steps without a name are numbered across sections, not from `step-1` in each section.

`parseRecipe` keeps text as written, so it doesn't read a line such as `'For the glaze:'` as a section's title, and a step such as `'1. Heat the oven.'` keeps its number. To read a recipe pasted as text into sections and steps, see [Read a pasted recipe](https://recipe-book.siraj.page/guides/import-recipes.md#read-a-pasted-recipe).

## Set times

Write each time in minutes, or as an ISO 8601 duration, the format that schema.org and many content management systems use. `parseRecipe` fails on a duration with years or months, such as `'P30M'`, unless they're zero, as in `'P0Y0M0DT0H30M'`. Add any other named time, such as resting or chilling, to `custom` with a `label`:

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  times: {
    prep: 10,
    cook: 'PT15M',
    total: 'PT35M',
    custom: [{ label: 'Rest the batter', minutes: 10 }],
  },
  ingredients: [{ name: 'all-purpose flour', quantity: '1 ½ cups' }],
  steps: ['Whisk the dry ingredients in a large bowl.'],
})

if (!result.success) {
  throw result.error
}

result.data.times // { prep: 10, cook: 15, total: 35, custom: [{ id: 'rest-the-batter', label: 'Rest the batter', minutes: 10 }] }
```

`parseRecipe` doesn't add up the other times, so set `total` when you want to show it.

These times are for the whole recipe: a step has no time of its own, but [`segmentStepText`](https://recipe-book.siraj.page/reference/core/units.md#segmentsteptext) finds the durations written in its text, such as `20 minutes`, with their minutes. For a timer the text doesn't state, keep its minutes in your own data under the step's ID, such as `{ cook: 3 }` for a step with `id: 'cook'`. [Set that ID](https://recipe-book.siraj.page/guides/author-recipes.md#set-ids) yourself, so it doesn't change when you edit the steps.

## Add notes, equipment, and links

Write a note or a piece of equipment as a string. Use a [`NoteInput`](https://recipe-book.siraj.page/reference/core/types.md#noteinput) when a note needs a `title`, or an [`EquipmentInput`](https://recipe-book.siraj.page/reference/core/types.md#equipmentinput) when equipment needs a `quantity`, a `plural`, a `url`, or a `note`. Give an ingredient a `url` to link it to a product page or another recipe:

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  ingredients: [
    { name: 'buttermilk', quantity: '1 ¼ cups', url: '/recipes/buttermilk' },
  ],
  steps: ['Whisk the batter.'],
  notes: [
    'The batter keeps overnight in the fridge.',
    {
      title: 'Make it dairy-free',
      text: 'Use oat milk with 1 tbsp lemon juice.',
    },
  ],
  equipment: [
    'whisk',
    { name: 'mixing bowl', plural: 'mixing bowls', quantity: 2 },
  ],
})

if (!result.success) {
  throw result.error
}

result.data.notes.map((note) => note.id) // ['note-1', 'make-it-dairy-free']
result.data.equipment[1] // { id: 'mixing-bowl', name: 'mixing bowl', plural: 'mixing bowls', quantity: 2 }
result.data.ingredients[0]?.items[0]?.url // '/recipes/buttermilk'
```

Write note text as plain text, not HTML: `parseRecipe` keeps tags and entities as written, so JSX such as `{note.text}` shows `<b>` and `&amp;` as typed. Equipment and times stay the same when [`resolveRecipe`](https://recipe-book.siraj.page/reference/core/resolving.md#resolverecipe) scales a recipe. Give the recipe a `description` and an `image` URL, and give a step an `image` by writing it as a [`StepInput`](https://recipe-book.siraj.page/reference/core/types.md#stepinput). [Types](https://recipe-book.siraj.page/reference/core/types.md) lists the URLs a link or image can use.

## Add nutrition

Write `nutrition` for one of the recipe's `servings`. Say what a serving is in `servingSize`. Write each nutrient as a number in its unit, which is kcal for `calories`, mg for `sodium` and `cholesterol`, and g for the rest, or as text with a unit:

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  servings: 4,
  ingredients: [{ name: 'buttermilk', quantity: '1 ¼ cups' }],
  steps: ['Whisk the batter.'],
  nutrition: {
    servingSize: '3 pancakes',
    calories: '1046 kJ',
    fat: 9,
    sodium: '0.5 g',
  },
})

if (!result.success) {
  throw result.error
}

result.data.nutrition // { servingSize: '3 pancakes', calories: 250, fat: 9, sodium: 500 }
```

`calories` takes kcal or kJ, which converts at 4.184 kJ per kcal.

Nutrition copied from schema.org, such as a recipe page's JSON-LD, names most nutrients with a `Content` suffix, as in `fatContent`. `parseRecipe` drops each of those nutrients with an [`unknown_field`](https://recipe-book.siraj.page/errors.md#issue-unknown_field) warning, such as `Unknown field. Did you mean "fat"?`, so rename each field to the name its warning suggests. `calories` and `servingSize` already match, and values such as `'9 g'` or `'250 calories'` can stay as they are.

[`fromJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#fromjsonld) reads a whole schema.org Recipe as it is, nutrition names included. [Import recipes](https://recipe-book.siraj.page/guides/import-recipes.md) shows how to import one from a recipe page.

Nutrition never scales: `resolveRecipe` keeps it unchanged in its [result](https://recipe-book.siraj.page/reference/core/resolving.md#resolvedrecipe), at `resolved.recipe.nutrition`. [`NutritionInput`](https://recipe-book.siraj.page/reference/core/types.md#nutritioninput) lists every nutrient you can write, and [`Nutrition`](https://recipe-book.siraj.page/reference/core/types.md#nutrition) gives the unit of each.

When you publish a recipe with [`toJsonLd`](https://recipe-book.siraj.page/reference/core/schema-org.md#tojsonld) or [`<Recipe.JsonLd>`](https://recipe-book.siraj.page/reference/react/json-ld.md#jsonld), give the recipe its own `servings` along with any yield, because nutrition is for one serving, and a yield such as 24 cookies doesn't say how many servings that is.

## Set IDs

[`parseRecipe`](https://recipe-book.siraj.page/reference/core/parsing.md#parserecipe) derives an ID from each name, title, or label. It numbers steps without a name and notes without a title, and adds a suffix to a repeated name. Set `id` yourself when other code depends on it, such as a link to a step, so it doesn't change when you rename:

```ts
import { parseRecipe } from '@recipe-book/core'

const result = parseRecipe({
  name: 'Buttermilk pancakes',
  ingredients: [
    { name: 'butter', quantity: '3 tbsp', note: 'melted' },
    { name: 'butter', quantity: '1 tbsp', note: 'for the griddle' },
    { id: 'syrup', name: 'maple syrup', note: 'to serve' },
  ],
  steps: [
    'Whisk the dry ingredients in a large bowl.',
    {
      id: 'cook',
      text: 'Cook ¼-cup portions on a buttered griddle, 2–3 minutes per side.',
    },
  ],
})

if (!result.success) {
  throw result.error
}

result.data.id // 'buttermilk-pancakes'
result.data.ingredients[0]?.items.map((item) => item.id) // ['butter', 'butter-2', 'syrup']
result.data.steps[0]?.items.map((step) => step.id) // ['step-1', 'cook']
```

`parseRecipe` keeps each ID you set, but an ID loses the whitespace at its ends, as with `String.prototype.trim`, so `' cook '` becomes `'cook'`. One left empty, such as `''` or `' '`, is derived as if you'd left it out, without a warning. If you set one twice in the same list, such as `'cook'` and `' cook '` on two steps, it adds a suffix to the later one, and `result.warnings` gets a [`duplicate_id`](https://recipe-book.siraj.page/errors.md#issue-duplicate_id) issue.

By default, each [`<Recipe.Step>`](https://recipe-book.siraj.page/reference/react/steps.md#step) renders an `id` that starts with the recipe's `id`. To keep links to its steps working when you rename the recipe, write the recipe an `id` too, or give the Root an [`idPrefix`](https://recipe-book.siraj.page/reference/react/root.md#step-ids).

## Next steps

- [Validate recipes](https://recipe-book.siraj.page/guides/validate-recipes.md) for input from a CMS, an API, or a form
- [Types](https://recipe-book.siraj.page/reference/core/types.md) for every field of `RecipeInput` and `Recipe`
- [Parsing](https://recipe-book.siraj.page/reference/core/parsing.md) for `parseRecipe`, [`parseQuantity`](https://recipe-book.siraj.page/reference/core/parsing.md#parsequantity), and `parseIngredientLine`
- [Units](https://recipe-book.siraj.page/reference/core/units.md) for every unit alias
