A restaurant’s website has a short job description. Show the menu as it is tonight. Say when you’re open, and be right about it. Let someone ask for a table. Be found when a person searches for dinner nearby.
Most restaurant sites get at least one of those wrong, usually because the same fact lives in four places. The hours in the footer say ten, the contact page says eleven, and the listing on the search results page says something else again.
Astro suits this kind of site well. The pages are plain HTML, so they load fast on a phone on a street corner, and the one part that needs a server, the reservation form, is a single function. This guide builds the four pieces in Astro 7, each from one source of truth. The code below was built and run against Astro 7.4.5 before it went on this page, with only the page shell trimmed from the examples.
If you need the site this week instead, Vesper, our Restaurant template, is this guide finished: every page designed and written, on the same ideas. The rest of this post shows how the core works, which is worth knowing whichever way you go.
Set up the project
Start from Astro’s minimal template and add an adapter. The adapter is only there to run the reservation form: every other page is still built once and served as a file.
npm create astro@latest restaurant -- --template minimalnpx astro add nodeUse vercel, netlify or cloudflare in place of node if that is where you host. Then declare the one secret the site needs, the address reservation requests are sent to:
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
import node from '@astrojs/node';
export default defineConfig({
site: 'https://example.com',
// Pages stay static. The adapter is only there to run the reservation form.
adapter: node({ mode: 'standalone' }),
env: {
schema: {
RESERVATIONS_WEBHOOK: envField.string({ context: 'server', access: 'secret' }),
},
},
});Keep the facts in one file
Everything else in this guide reads from one config file: the name, the address, the hours and the times you seat people. Change a closing time here and the hours table, the “open now” line, the reservation form and the structured data all change with it.
// src/config/restaurant.ts
export const restaurant = {
name: 'Vesper',
phone: '+15035550142',
address: { street: '18 Calloway Row', city: 'Portland', region: 'OR', postcode: '97205', country: 'US' },
cuisine: 'Wood-fire cooking',
priceRange: '$$$',
timeZone: 'America/Los_Angeles',
/** One entry per run of days with the same hours. A day that isn't listed is closed. */
hours: [
{ days: ['Tuesday', 'Wednesday', 'Thursday'], opens: '17:30', closes: '22:00' },
{ days: ['Friday', 'Saturday'], opens: '17:30', closes: '23:00' },
{ days: ['Sunday'], opens: '12:00', closes: '20:00' },
],
/** The times a table can be asked for */
seatings: ['17:30', '18:15', '19:30', '20:45'],
maxGuests: 6,
} as const;The time zone matters more than it looks. It is the restaurant’s clock that decides whether you’re open, not the visitor’s.
Keep the menu as data
A menu changes more often than anything else on the site, and the person changing it is rarely a developer. So keep it out of the page template. A content collection reads a JSON file and checks it against a schema:
// src/content.config.ts
import { defineCollection } from 'astro:content';
import { file } from 'astro/loaders';
import { z } from 'astro/zod';
const menus = defineCollection({
loader: file('src/content/menus.json'),
schema: z.object({
name: z.string(),
order: z.number(),
sections: z.array(
z.object({
title: z.string(),
items: z.array(
z.object({
name: z.string(),
description: z.string().optional(),
price: z.number().positive(),
diets: z.array(z.enum(['v', 'vg', 'gf'])).default([]),
}),
),
}),
),
}),
});
export const collections = { menus };The menu itself is src/content/menus.json, one entry per menu:
[
{
"id": "dinner",
"name": "Dinner",
"order": 1,
"sections": [
{
"title": "To begin",
"items": [
{ "name": "Hearth bread", "description": "Cultured butter, smoked salt", "price": 9, "diets": ["v"] },
{ "name": "Leeks in the coals", "description": "Hazelnut, brown butter", "price": 16, "diets": ["v", "gf"] }
]
}
]
}
]The schema is what makes this safe to hand over. Delete the price of the leeks by accident and the build stops instead of publishing a dish with no price:
[InvalidContentEntryDataError] menus → dinner data does not match collection schema.
sections.0.items.1.price: RequiredThe page reads the collection and prints it. Prices stay numbers in the data and get their currency symbol here, in one place:
---
// src/pages/menu.astro
import { getCollection } from 'astro:content';
const menus = (await getCollection('menus')).sort((a, b) => a.data.order - b.data.order);
const price = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 });
---
<h1>Menu</h1>
{
menus.map((menu) => (
<section>
<h2>{menu.data.name}</h2>
{menu.data.sections.map((section) => (
<>
<h3>{section.title}</h3>
<ul>
{section.items.map((item) => (
<li>
<strong>{item.name}</strong> {price.format(item.price)}
{item.description && <p>{item.description}</p>}
{item.diets.length > 0 && <small>{item.diets.join(', ')}</small>}
</li>
))}
</ul>
</>
))}
</section>
))
}Add a lunch menu by adding a second entry to the file. Nothing in the page changes.
Say whether you’re open
The hours table is the easy half: loop over restaurant.hours and print each row. The line people actually look for is the other half, “open now” or “closed now”, and a static page cannot know that when it is built.
So that one line is worked out in the browser, on the restaurant’s clock. Intl.DateTimeFormat gives the weekday and the time in any time zone, with no library:
// src/lib/hours.ts
import { restaurant } from '../config/restaurant';
/** The weekday and the time on the clock at the restaurant, wherever the visitor is */
export function clockAt(date: Date) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone: restaurant.timeZone,
weekday: 'long',
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
}).formatToParts(date);
const part = (type: string) => parts.find((p) => p.type === type)?.value ?? '';
return { day: part('weekday'), time: `${part('hour')}:${part('minute')}` };
}
/** The hours for a weekday ("Friday"), or undefined on a day you are closed */
export function hoursFor(day: string) {
return restaurant.hours.find((slot) => (slot.days as readonly string[]).includes(day));
}
export function isOpen(date = new Date()) {
const { day, time } = clockAt(date);
const slot = hoursFor(day);
// "17:30" < "19:05" < "22:00" compares correctly as text, as long as you close before midnight
return Boolean(slot && time >= slot.opens && time < slot.closes);
}---
// src/components/OpenNow.astro
---
<p id="open-now" hidden></p>
<script>
import { isOpen } from '../lib/hours';
const line = document.getElementById('open-now');
if (line) {
line.textContent = isOpen() ? 'Open now' : 'Closed now';
line.hidden = false;
}
</script>The paragraph starts hidden, so a visitor with JavaScript off sees the hours table and no wrong claim. We tested this from a browser set to Tokyo time: at seven on a Friday evening in Portland it says open, on a Monday it says closed, and at five past eleven on a Friday night it says closed.
Astro bundles that <script> and, if you use a Content Security Policy, hashes it for you.
Take table requests with an Action
An Astro Action is a function that runs on the server and checks its input before your code sees it. This one accepts the form, refuses days you are closed, and passes the request on:
// src/actions/index.ts
import { ActionError, defineAction } from 'astro:actions';
import { RESERVATIONS_WEBHOOK } from 'astro:env/server';
import { z } from 'astro/zod';
import { restaurant } from '../config/restaurant';
import { hoursFor } from '../lib/hours';
export const server = {
reserve: defineAction({
accept: 'form',
input: z.object({
name: z.string().min(2),
email: z.email(),
guests: z.number().int().min(1).max(restaurant.maxGuests),
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
time: z.enum(restaurant.seatings),
}),
handler: async (request) => {
// The weekday of a calendar date. Noon UTC keeps it on the same day everywhere.
const day = new Date(`${request.date}T12:00:00Z`).toLocaleDateString('en-US', { weekday: 'long', timeZone: 'UTC' });
if (!hoursFor(day)) {
throw new ActionError({ code: 'BAD_REQUEST', message: `We are closed on ${day}s. Please pick another day.` });
}
// Send it where a person will see it: an email service, a spreadsheet, your booking system.
const sent = await fetch(RESERVATIONS_WEBHOOK, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(request),
});
if (!sent.ok) {
throw new ActionError({ code: 'INTERNAL_SERVER_ERROR', message: 'We could not send your request. Please call us.' });
}
return request;
},
}),
};Two details are worth noticing. The party size limit and the seating times come from the config file, so the form cannot offer a time the server refuses. And the check runs on the server, so it holds even when someone skips the browser’s own validation.
The page is an ordinary HTML form. It works with JavaScript off, because the browser posts it and the page reads the result when it comes back:
---
// src/pages/reserve.astro
import { actions, isInputError } from 'astro:actions';
import { restaurant } from '../config/restaurant';
// This page answers a form post, so it runs on the server. Every other page stays static.
export const prerender = false;
const result = Astro.getActionResult(actions.reserve);
const fieldErrors = isInputError(result?.error) ? result.error.fields : {};
---
<h1>Reserve a table</h1>
{
result?.data && (
<p role="status">
Thank you, {result.data.name}. We have your request for {result.data.guests} on {result.data.date} at{' '}
{result.data.time}, and will write to confirm.
</p>
)
}
{result?.error && !isInputError(result.error) && <p role="alert">{result.error.message}</p>}
<form method="POST" action={actions.reserve}>
<label>Name <input name="name" autocomplete="name" required /></label>
{fieldErrors.name && <p role="alert">{fieldErrors.name.join(', ')}</p>}
<label>Email <input name="email" type="email" autocomplete="email" required /></label>
{fieldErrors.email && <p role="alert">{fieldErrors.email.join(', ')}</p>}
<label>Guests <input name="guests" type="number" min="1" max={restaurant.maxGuests} value="2" required /></label>
{fieldErrors.guests && <p role="alert">{fieldErrors.guests.join(', ')}</p>}
<label>Date <input name="date" type="date" required /></label>
<label>
Time
<select name="time" required>
{restaurant.seatings.map((time) => <option>{time}</option>)}
</select>
</label>
<button>Request a table</button>
</form>In our test, a party of four on a Friday came back with the thank-you line and arrived at the webhook as JSON. A Monday came back with “We are closed on Mondays” and sent nothing. A party of twelve, forced past the browser’s check, was refused by the schema.
Be honest with guests about what this is. It is a request, not a booking: nothing here knows how many tables are free. Say so on the page, and confirm by hand or pass the request to a booking system that does know.
Tell search engines what you are
The opening hours a search engine shows for you come from structured data, and the usual mistake is typing them out a second time. Build them from the same config instead:
---
// in your home page or layout
import { restaurant } from '../config/restaurant';
const schema = {
'@context': 'https://schema.org',
'@type': 'Restaurant',
name: restaurant.name,
telephone: restaurant.phone,
servesCuisine: restaurant.cuisine,
priceRange: restaurant.priceRange,
address: {
'@type': 'PostalAddress',
streetAddress: restaurant.address.street,
addressLocality: restaurant.address.city,
addressRegion: restaurant.address.region,
postalCode: restaurant.address.postcode,
addressCountry: restaurant.address.country,
},
openingHoursSpecification: restaurant.hours.map((slot) => ({
'@type': 'OpeningHoursSpecification',
dayOfWeek: slot.days,
opens: slot.opens,
closes: slot.closes,
})),
menu: new URL('/menu/', Astro.site).href,
acceptsReservations: true,
};
---
<script type="application/ld+json" set:html={JSON.stringify(schema)} />Now the footer, the hours table, the “open now” line, the reservation form and the Restaurant data cannot disagree, because there is only one copy of the hours.
What this leaves out
That is a working core, and it is deliberately small. A real restaurant site needs more before it opens:
- Days you close: holidays and private hires. Add a
closedDateslist to the config and check it inisOpenand in the Action. - Closing after midnight: the text comparison in
isOpenassumes you close before midnight. A bar that shuts at one in the morning needs the day handled too. - A date picker that knows your week: the form above lets someone choose a Monday and tells them afterwards. Better to offer only the days you open.
- A second language: Astro’s i18n routing handles the URLs. The menu needs an entry per language.
- Photos: use
astro:assetsso each one is resized and served in a modern format. - A menu that prints: people print menus. A short print stylesheet that drops the header and footer is an hour well spent.
- The design: everything above is unstyled HTML.
Or start from the finished one
We built all of this out as Vesper, the Restaurant template in Velocity Premium. It uses the same ideas, with opening hours and booking rules in one config file and menus in a checked JSON file.
It adds the parts this guide leaves out:
- a booking bar in the opening photo that carries guests, date and time through to the form
- a full-screen reservation form that asks one question at a time and offers only the days and times you open
- menus set as printed cards, with set menus, dietary marks and a print button
- ticketed evenings, each with its own page, a booking card and a last-seats note
- closed dates, private dining, a visit page with live hours, and a journal
- English and Spanish throughout, light and dark, and three color presets
Its forms are honest in the same way: they check what is typed and show their confirmation, and they deliver nothing until you connect them to your own service.
You can click through the live demo, or see every page first. The template is $49 on its own, a launch price until December 31, then $79, with a commercial license for as many sites as you build.
If you would rather build it yourself, the code above is yours to take.