To build a recipe website with Astro, store each recipe as a Markdown file with typed frontmatter for ingredients, steps, times and servings, render a recipe card from that data, output Recipe JSON-LD so search engines can show rich results, and add a print stylesheet and a small serving scaler. A recipe website built with Astro ships pages with almost no JavaScript, so readers in a kitchen with one hand free get the recipe instantly instead of waiting through ads and pop-ups.
This guide builds the content model, the recipe page, category pages and the details cooks actually use.
Key Takeaways
- Put ingredients, steps, times and servings in frontmatter, not prose, so one source feeds the recipe card, the schema and the print view.
- Durations in
Recipeschema use ISO 8601 format, such asPT45Mfor 45 minutes.- A “jump to recipe” link and a print stylesheet are the two features readers notice most.
- A serving scaler needs about 20 lines of plain JavaScript, no framework.
- Category, cuisine and diet pages come free from
getStaticPaths()once the data is structured.
Why structured recipe data matters
Most recipe blogs store everything in the post body. That makes it hard to reuse: the recipe card, the structured data and the printable version all end up as separate copies that drift apart.
In Astro, put the recipe itself in frontmatter and keep the story, tips and photos in the body. One schema then drives every output:
| Output | Uses |
|---|---|
| Recipe card | Ingredients, steps, times, servings |
Recipe JSON-LD |
Same fields, formatted for search engines |
| Print view | The card only, styled for paper |
| Category pages | category, cuisine, diet fields |
| Recipe index | Title, image, total time |
Start the project
# Terminal
npm create astro@latest recipe-site
cd recipe-site
npx astro add mdx sitemap
npm run dev
Set site in astro.config.mjs to your domain. Structured data and the sitemap both need absolute URLs.
Model recipes as a content collection
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { glob } from 'astro/loaders';
import { z } from 'astro/zod';
const recipes = defineCollection({
loader: glob({ pattern: '**/index.{md,mdx}', base: './src/content/recipes' }),
schema: ({ image }) =>
z.object({
title: z.string(),
description: z.string().max(160),
pubDate: z.coerce.date(),
image: image(),
imageAlt: z.string(),
prepMinutes: z.number().int(),
cookMinutes: z.number().int(),
servings: z.number().int().positive(),
category: z.enum(['breakfast', 'lunch', 'dinner', 'dessert', 'snack']),
cuisine: z.string(),
diet: z.array(z.enum(['vegetarian', 'vegan', 'gluten-free', 'dairy-free'])).default([]),
ingredients: z.array(
z.object({
amount: z.number().optional(),
unit: z.string().optional(),
item: z.string(),
}),
),
steps: z.array(z.string()).min(1),
}),
});
export const collections = { recipes };
Storing amount as a number, separate from unit and item, is what makes the serving scaler possible. “2 cups flour” as a single string can’t be scaled reliably.
A recipe entry:
<!-- src/content/recipes/lemon-ricotta-pancakes/index.md -->
---
title: "Lemon ricotta pancakes"
description: "Light, fluffy lemon ricotta pancakes ready in 25 minutes, with tips for keeping them tall."
pubDate: 2026-10-20
image: "./pancakes.jpg"
imageAlt: "Stack of lemon ricotta pancakes with blueberries"
prepMinutes: 10
cookMinutes: 15
servings: 4
category: "breakfast"
cuisine: "American"
diet: ["vegetarian"]
ingredients:
- { amount: 250, unit: "g", item: "ricotta" }
- { amount: 3, item: "eggs, separated" }
- { amount: 120, unit: "g", item: "plain flour" }
- { amount: 1, unit: "tsp", item: "baking powder" }
- { amount: 1, item: "lemon, zested" }
- { item: "butter, for the pan" }
steps:
- "Whisk the ricotta, egg yolks and lemon zest until smooth."
- "Fold in the flour and baking powder."
- "Beat the egg whites to soft peaks and fold them in gently."
- "Cook spoonfuls in a buttered pan over medium heat, 2 minutes per side."
---
These are the pancakes I make when people stay over...
Build the recipe page
The page renders the story first, then the card. Put a “jump to recipe” link at the top so people who only want the recipe can skip the story.
---
// src/pages/recipes/[id].astro
import { getCollection, render } from 'astro:content';
import { Image } from 'astro:assets';
import Base from '../../layouts/Base.astro';
import RecipeSchema from '../../components/RecipeSchema.astro';
export async function getStaticPaths() {
const recipes = await getCollection('recipes');
return recipes.map((recipe) => ({ params: { id: recipe.id }, props: { recipe } }));
}
const { recipe } = Astro.props;
const { Content } = await render(recipe);
const r = recipe.data;
const total = r.prepMinutes + r.cookMinutes;
---
<Base title={r.title} description={r.description}>
<RecipeSchema recipe={recipe} />
<article>
<h1>{r.title}</h1>
<a href="#recipe" class="jump">Jump to recipe</a>
<Image src={r.image} alt={r.imageAlt} widths={[800, 1600]} sizes="100vw" loading="eager" />
<Content />
<section id="recipe" class="recipe-card">
<h2>{r.title}</h2>
<p>Prep {r.prepMinutes} min · Cook {r.cookMinutes} min · Total {total} min</p>
<label>
Servings
<input type="number" id="servings" min="1" value={r.servings} data-base={r.servings} />
</label>
<h3>Ingredients</h3>
<ul>
{r.ingredients.map((ing) => (
<li>
{ing.amount !== undefined && <span class="qty" data-amount={ing.amount}>{ing.amount}</span>}
{ing.unit && ` ${ing.unit}`} {ing.item}
</li>
))}
</ul>
<h3>Method</h3>
<ol>{r.steps.map((step) => <li>{step}</li>)}</ol>
<button type="button" onclick="window.print()">Print recipe</button>
</section>
</article>
</Base>
The ingredient list and steps are plain HTML, so they’re readable with JavaScript disabled and easy for screen readers.
Add Recipe structured data
Recipe JSON-LD is what makes recipes eligible for rich results with an image, cook time and rating in search. Build it from the same frontmatter:
---
// src/components/RecipeSchema.astro
import { getImage } from 'astro:assets';
import type { CollectionEntry } from 'astro:content';
interface Props {
recipe: CollectionEntry<'recipes'>;
}
const { recipe } = Astro.props;
const r = recipe.data;
const img = await getImage({ src: r.image, width: 1200 });
const iso = (minutes: number) => `PT${minutes}M`;
const schema = {
'@context': 'https://schema.org',
'@type': 'Recipe',
name: r.title,
description: r.description,
image: [new URL(img.src, Astro.site).href],
author: { '@type': 'Person', name: 'Your Name' },
datePublished: r.pubDate.toISOString().slice(0, 10),
prepTime: iso(r.prepMinutes),
cookTime: iso(r.cookMinutes),
totalTime: iso(r.prepMinutes + r.cookMinutes),
recipeYield: `${r.servings} servings`,
recipeCategory: r.category,
recipeCuisine: r.cuisine,
recipeIngredient: r.ingredients.map((i) =>
[i.amount, i.unit, i.item].filter((part) => part !== undefined).join(' '),
),
recipeInstructions: r.steps.map((text) => ({ '@type': 'HowToStep', text })),
};
---
<script type="application/ld+json" set:html={JSON.stringify(schema)} />
Only add aggregateRating if you collect real ratings from readers. Made-up ratings break search engine guidelines. Google’s recipe structured data docs list required and recommended fields, and the Astro JSON-LD guide shows how to combine this with your site-wide schema.
Add a serving scaler
A small inline script multiplies every ingredient amount when the servings number changes. No island or framework needed:
<!-- src/pages/recipes/[id].astro (bottom of the file) -->
<script>
const input = document.querySelector<HTMLInputElement>('#servings');
const quantities = document.querySelectorAll<HTMLElement>('.qty');
const format = (n: number) =>
Number.isInteger(n) ? String(n) : n.toFixed(n < 10 ? 2 : 0).replace(/\.?0+$/, '');
input?.addEventListener('input', () => {
const base = Number(input.dataset.base);
const wanted = Number(input.value);
if (!base || !wanted) return;
quantities.forEach((el) => {
el.textContent = format((Number(el.dataset.amount) * wanted) / base);
});
});
</script>
Astro bundles and processes this <script> once, and it only runs on recipe pages. For a deeper look at when a plain script beats a component island, read island or script.
Make recipes printable
Many readers print recipes or keep them open on a tablet. A print stylesheet hides everything except the card:
/* src/styles/print.css */
@media print {
header, footer, nav, .jump, article > :not(.recipe-card), button, label {
display: none !important;
}
.recipe-card {
font-size: 12pt;
color: #000;
}
.recipe-card li {
break-inside: avoid;
}
@page {
margin: 1.5cm;
}
}
Import it in your base layout. A tip for tablet users: the Screen Wake Lock API (navigator.wakeLock.request('screen')) can keep the screen on while cooking. Offer it as a toggle button and check that the browser supports it first.
Category, cuisine and diet pages
With structured fields, each listing page is one getStaticPaths() call. Here is the category version:
---
// src/pages/category/[category].astro
import { getCollection } from 'astro:content';
import Base from '../../layouts/Base.astro';
import RecipeCard from '../../components/RecipeCard.astro';
export async function getStaticPaths() {
const categories = ['breakfast', 'lunch', 'dinner', 'dessert', 'snack'] as const;
const recipes = await getCollection('recipes');
return categories.map((category) => ({
params: { category },
props: { recipes: recipes.filter((r) => r.data.category === category) },
}));
}
const { category } = Astro.params;
const { recipes } = Astro.props;
---
<Base title={`${category} recipes`} description={`All ${category} recipes, with times and servings.`}>
<h1 class="capitalize">{category} recipes</h1>
<div class="grid">{recipes.map((recipe) => <RecipeCard recipe={recipe} />)}</div>
</Base>
Repeat for cuisine and diet. Pages like “vegan dinner recipes” combine two fields, and readers search for exactly those combinations. Once you pass 30 or so recipes per category, add pagination; Astro pagination covers paginate().
Photos, ads and speed
Food photography sells recipes, so use large, sharp images, but let Astro size them. Use <Image /> with widths and sizes, and keep the hero image loading="eager" because it’s usually the Largest Contentful Paint element.
If you run display ads, they will be the slowest part of the page. Reserve space for each ad slot with a fixed min-height so content doesn’t jump when ads load, and keep ads out of the ingredient list and steps. Readers leave recipe sites that shift under their thumbs.
Deploy
Run npm run build and deploy dist/ to Cloudflare Pages, Netlify, Vercel or GitHub Pages. New recipes go live when you push a new Markdown file. If you’d rather write in a visual editor, a Git-based CMS such as Decap or Keystatic can edit the same files; the content collections docs explain how collections and loaders fit together.
Start from a recipe theme
Free starting points include Astro’s blog starter and community blog templates like AstroPaper, which you’d extend with the recipe schema above. If you’d rather start with recipe pages already designed, the Food & Drink category has recipe-focused Komal themes: All Recipes has recipe, category and video recipe pages with multiple authors, All You Can Eat is a recipe and blog theme for food bloggers, and Diet X is a recipe blog with recipe and video pages. Running a restaurant instead? See how to build a restaurant website with Astro.
FAQ
Is Astro good for a food blog or recipe site?
Yes. Recipe sites are content-first and image-heavy, which suits Astro’s static output and build-time image optimization. Pages ship almost no JavaScript by default, so recipes load quickly even with photos and a few ads.
How do I get recipe rich results for my Astro site?
Add Recipe JSON-LD to each recipe page with at least the name and image, plus recommended fields like times, ingredients, instructions and yield. Build it from your recipe frontmatter so it always matches the visible card, then test it with Google’s Rich Results Test.
How do I add a print button to a recipe in Astro?
Add a button that calls window.print() and a @media print stylesheet that hides navigation, ads and the story, leaving only the recipe card. Use break-inside: avoid on list items so steps don’t split across pages.
Should recipe ingredients go in Markdown or frontmatter?
Frontmatter, as structured data. That lets one source feed the recipe card, the structured data, the serving scaler and the print view. Keep the story, tips and process photos in the Markdown body.
How do I scale recipe servings on a static site?
Store each ingredient amount as a number, output it in a data-amount attribute, and use a short script that multiplies every amount by the new servings divided by the original servings. It runs in the browser, so no server is needed.