A search engine works in three steps: it discovers addresses, crawls them and decides whether to index them. Every AgendaViva page already knows how to describe itself. But nobody has told the search engine which pages exist: the concerts four months from now are on page 9 of the guide, and their event pages nine clicks away from the home page. At the other extreme, the filters generate thousands of addresses with the same cards in a different order, and crawling them eats up time that isn't spent on what matters.
In this lesson you'll provide a list of what you want visited, say what isn't worth it and describe each event in a format a machine understands without reading the prose. You'll also solve two cases specific to an events guide that almost nobody thinks about until they become a nuisance: events that are over and events that are canceled.
- Four tools that get confused
| Tool | What it says | What it does not do |
|---|---|---|
sitemap.xml |
"These addresses exist and I care about them" | It doesn't force them to be indexed |
robots.txt |
"Don't request these addresses" | It doesn't stop them from appearing in results, and it protects nothing |
noindex |
"You can read it, but don't show it" | It doesn't work if robots.txt prevents reading it |
canonical |
"This page is a copy; the real one is that one" | It's a suggestion, not an order |
The third row holds the classic mistake: blocking a route in robots.txt and giving it noindex. Since the search engine doesn't read it, it doesn't see the directive, and if someone links to it, it may show it without a description. For it to disappear, the engine must be able to crawl it.
And none of them hides anything: robots.txt is public, and listing sensitive routes in it is pointing them out.
- The sitemap
app/sitemap.ts exports a function that returns addresses, and Next.js serves /sitemap.xml. It's a special Route Handler: with Cache Components it's prerendered if everything it queries is cached. First, the query:
// lib/data/events.ts (added)
const MAX_IN_SITEMAP = 20_000
export async function listEventsForSitemap(): Promise<Pick<AgendaEvent, 'slug' | 'image'>[]> {
'use cache'
cacheLife('hours')
cacheTag(EVENTS_TAG)
const db = await getDb()
return db
.select({ slug: events.slug, image: events.image })
.from(events)
.where(isCurrent())
.orderBy(...byDate)
.limit(MAX_IN_SITEMAP)
}// app/sitemap.ts
import type { MetadataRoute } from 'next'
import { listEventsForSitemap } from '@/lib/data/events'
import { listVenueSummaries } from '@/lib/data/venues'
import { createEventsUrl } from '@/lib/filters'
import { imageUrl } from '@/lib/images'
import { SITE_URL } from '@/lib/site'
import { CATEGORIES } from '@/lib/types'
function absolute(path: string): string {
return new URL(path, SITE_URL).href
}
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const [events, venues] = await Promise.all([
listEventsForSitemap(),
listVenueSummaries(),
])
return [
{ url: absolute('/') },
{ url: absolute('/events') },
...CATEGORIES.map((category) => ({ url: absolute(createEventsUrl({ category })) })),
{ url: absolute('/venues') },
...venues.map(({ slug }) => ({ url: absolute(`/venues/${slug}`) })),
...events.map(({ slug, image }) => ({
url: absolute(`/events/${slug}`),
...(image ? { images: [absolute(imageUrl(image))] } : {}),
})),
]
}- It updates itself. When an event is published,
invalidateEventexpires theeventstag, and the sitemap with it. There's no task that regenerates it, nor one that can be forgotten. - It contains what's current and published:
isCurrent()excludes what's over, drafts and canceled events. Nothing that responds with a 404, redirects or carriesnoindexshould be here. - The addresses are absolute, and the value of
NEXT_PUBLIC_SITE_URLis fixed at build time. - It needs the database at build time, like the rest of the shell.
- The text isn't escaped. Next.js copies each address as is into the XML. With a single parameter there's no problem; with two, the URL's
&would produce an invalid file and you'd have to write&. - The images help associate them with their page. The poster is the original, not the
/_next/imageversion.
2.1. The date we leave out
The format accepts lastModified, changeFrequency and priority. The last two are ignored in practice. The first is useful if it's true. Many examples show lastModified: new Date(), which claims that everything changed today: search engines soon learn not to believe it. Besides, reading the clock while prerendering is an error with Cache Components (05-01).
We don't have a column that says when an event's content changed. Rather than make the data up, we leave it out. You'll add it in exercise 2.
2.2. When it doesn't fit in one
A file accepts 50,000 addresses. If there were more, they're split with generateSitemaps:
// Example only: app/archive/sitemap.ts
const PER_FILE = 50_000
export async function generateSitemaps() {
const total = await countArchivedEvents()
return Array.from({ length: Math.max(1, Math.ceil(total / PER_FILE)) }, (_, id) => ({ id }))
}
export default async function sitemap({
id,
}: {
id: Promise<string>
}): Promise<MetadataRoute.Sitemap> {
const index = Number(await id) // Since 16, a promise, and always a string
return listArchiveRange(index * PER_FILE, PER_FILE)
}The files end up at /archive/sitemap/0.xml, /archive/sitemap/1.xml… List them in robots.ts, which accepts an array in sitemap. The number is decided at build time.
- robots.txt
// app/robots.ts
import type { MetadataRoute } from 'next'
import { SITE_URL } from '@/lib/site'
export default function robots(): MetadataRoute.Robots {
return {
rules: { userAgent: '*', allow: '/', disallow: '/api/' },
sitemap: new URL('/sitemap.xml', SITE_URL).href,
}
}Only the API is excluded: those are JSON responses nobody is interested in on a search engine. The rest, with reasons:
| Route | Block it? | Why |
|---|---|---|
/dashboard, /admin, /account, /my-bookings |
No | They carry noindex, and without a session they redirect to /sign-in, which carries it too |
/events?q=… |
No | It must be read for its noindex to be seen (section 4) |
/_next/ |
Never | Without the CSS and JavaScript, the search engine doesn't see the page as a person does |
/images/ |
No | They're the posters for image search |
Each userAgent can have its own rules, and there are bots that collect text to train models or to answer with it. Whether to allow them is the client's decision; robots.txt communicates it to those that respect it. Those that don't are stopped by a rate limit, not by a text file.
3.1. Staging environments
A copy at staging.agendaviva.example that gets indexed competes with the original. The right thing is for it to require a password. If it must be accessible, it's flagged with a header, which also works for images and PDFs:
// next.config.ts, inside headers(), as the last rule
...(process.env.ALLOW_INDEXING === '1'
? []
: [{ source: '/:path*', headers: [{ key: 'X-Robots-Tag', value: 'noindex' }] }]),The default is not to index: if someone forgets the variable in a new environment, nothing happens; if they forget it in production, it shows up when checking. Since it's configuration, it's fixed at build time. Add it to .env.example and to the deployment checklist (11-04). And remember: in that environment, don't also block with robots.txt.
- Filters and pagination
/events accepts four parameters. With 4 categories, 3 districts, free text and pages, the combinations are endless. You have to decide which ones are pages and which are only states of a page:
| Address | Does it match a real search? | Decision |
|---|---|---|
/events |
Yes: "Vallenar cultural events" | Indexable |
/events?category=concert |
Yes: "concerts in Vallenar" | Indexable, with its own title |
/events?page=3 |
No, but it leads to event pages | Indexable, with canonical pointing to itself |
/events?district=Northside |
Maybe; there are few, and the venue pages cover them | noindex, following links |
/events?q=jazz |
No, and anyone can write them | noindex, following links |
/events?utm_source=newsletter |
It's the same page | canonical to /events |
On the third row there's a frequently repeated piece of advice that's wrong: pointing canonical on every page to the first one. Google advises against it, because page 3 is not a copy of page 1 and its event pages would stop being discovered. Each one points to itself, and they're linked with ordinary <a href> elements, as Pagination does. rel="next" and rel="prev" are no longer used.
// lib/format.ts (added)
export const CATEGORY_PLURALS: Record<Category, string> = {
concert: 'Concerts',
theater: 'Theater',
exhibition: 'Exhibitions',
workshop: 'Workshops',
}// lib/guide-metadata.ts
import type { Metadata } from 'next'
import { createEventsUrl } from '@/lib/filters'
import { CATEGORY_PLURALS } from '@/lib/format'
import { createMetadata } from '@/lib/metadata'
import type { EventFilters } from '@/lib/types'
export function createGuideMetadata(filters: EventFilters): Metadata {
const { category, district, q, page = 1 } = filters
const topic = category ? CATEGORY_PLURALS[category] : 'Event guide'
const title = q ? `Search: ${q}` : `${topic} in Vallenar del Río`
const metadata = createMetadata({
title: page > 1 ? `${title} (page ${page})` : title,
description: `${topic} in Vallenar del Río: dates, venues and free bookings.`,
path: createEventsUrl(filters),
})
const isIndexable = !district && !q
return isIndexable ? metadata : { ...metadata, robots: { index: false, follow: true } }
}// app/(public)/events/page.tsx (replaces the metadata object)
export async function generateMetadata({
searchParams,
}: Pick<Props, 'searchParams'>): Promise<Metadata> {
return createGuideMetadata(normalizeFilters(await searchParams))
}normalizeFiltersandcreateEventsUrldo the work. Unknown parameters are ignored, default values are omitted and the order is always the same: any variant of an address produces the samecanonical. We decided this in 02-02 for clarity, and here you can see how much it was worth.- The function is pure and depends on Next.js only for a type. It'll be tested without a browser in 10-03.
searchParamsbelongs to the request, so this metadata arrives through the stream (09-03). The page has other holes, so nothing needs to be declared.qis third-party text in a title. Next.js escapes it, it's truncated to 80 characters and the page isn't indexed: nobody can use our site to place text in the results.
follow: true lets crawlers follow the links to event pages from a non-indexed search.
- Events that end and events that are canceled
A finished event drops out of the listings (05-03) and the sitemap, and its event page keeps responding: there are links, past bookings and calendars pointing to it. The question is whether it should stay in search engines.
| Option | Consequence |
|---|---|
| Delete it: 404 or 410 | Broken links everywhere |
Redirect to /events |
Someone looking for something specific lands somewhere generic; search engines treat it as a 404 |
| Keep it indexed forever | Thousands of old event pages compete with current ones |
noindex after a while |
It stays accessible and stops appearing |
The fourth is reasonable, and it seems to require reading the clock in the metadata, with everything that implies. It doesn't: there's a directive that says from when, and the date comes from the event itself:
// app/(public)/events/[slug]/page.tsx, at the end of generateMetadata
const ONE_MONTH = 30 * 24 * 60 * 60 * 1000 // Outside the function
return {
...createMetadata({ /* … as in 09-03 … */ }),
robots: {
index: true,
follow: true,
unavailable_after: formatIsoDay(new Date(event.endsAt.getTime() + ONE_MONTH)),
},
}unavailable_after accepts an ISO 8601 date, and Google stops showing the page after it and crawls it less. new Date with an argument doesn't read the clock: it's a calculation with cached data, and the page stays in the shell. It's a good example of a principle we've often used: if the data can say when it expires, nobody has to check the time. To remind people, there's the notice from exercise 3 in 05-03.
A canceled event is different: the worst thing would be for it to disappear, because anyone with a booking will search for what's going on. Keep the event page, the title starts with "Canceled", it drops out of the sitemap and it's also communicated to machines, as you'll see right away.
- Structured data
A person reads "Friday, May 12, 8:30 PM" and knows it's the when. A machine works it out, with luck. JSON-LD is a block of JSON with a shared vocabulary, schema.org, that states it unambiguously. Search engines use it to show results with a date and a place, and other programs to add the event to a calendar.
// lib/dates.ts (added)
const offsetFormatter = new Intl.DateTimeFormat('en', {
timeZone: TIME_ZONE,
timeZoneName: 'longOffset', // 'GMT+02:00'
})
// Instant → '2028-05-12T20:30:00+02:00'
export function formatIsoDateTime(date: Date): string {
const parts = offsetFormatter.formatToParts(date)
const name = parts.find(({ type }) => type === 'timeZoneName')?.value ?? 'GMT'
return `${formatLocalDateTime(date)}:00${name.replace('GMT', '') || 'Z'}`
}// lib/json-ld.ts
import { formatIsoDateTime } from '@/lib/dates'
import { imageUrl } from '@/lib/images'
import { SITE_URL } from '@/lib/site'
import type { Category, EventDetailsData } from '@/lib/types'
export type JsonLd = Record<string, unknown>
const EVENT_TYPES: Record<Category, string> = {
concert: 'MusicEvent',
theater: 'TheaterEvent',
exhibition: 'ExhibitionEvent',
workshop: 'EducationEvent',
}
export function createEventJsonLd({ event, venue }: EventDetailsData): JsonLd {
const url = new URL(`/events/${event.slug}`, SITE_URL).href
const status = event.status === 'canceled' ? 'EventCancelled' : 'EventScheduled'
return {
'@context': 'https://schema.org',
'@type': EVENT_TYPES[event.category],
name: event.title,
description: event.summary,
url,
startDate: formatIsoDateTime(event.startsAt),
endDate: formatIsoDateTime(event.endsAt),
eventStatus: `https://schema.org/${status}`,
eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode',
isAccessibleForFree: true,
location: {
'@type': 'Place',
name: venue.name,
address: {
'@type': 'PostalAddress',
streetAddress: venue.address,
addressLocality: 'Vallenar del Río',
addressCountry: 'ES',
},
},
...(event.image ? { image: [new URL(imageUrl(event.image), SITE_URL).href] } : {}),
offers: { '@type': 'Offer', price: 0, priceCurrency: 'EUR', url },
}
}
export function serializeJsonLd(data: JsonLd): string {
return JSON.stringify(data).replace(/</g, '\\u003c')
}- Required by Google:
name,startDate,locationand itsaddress. Everything else is recommended. - The date carries the offset.
toISOString()would be the same instant, but in UTC; with+02:00it also states the local time, which is the one being advertised. - Canceling doesn't delete data. Date and place are kept and
eventStatuschanges. If it were postponed to a new date,EventRescheduledandpreviousStartDate. price: 0expresses that it's free.- What's missing is missing on purpose.
availabilitywould say whether there are spots left, and the event page is cached for an hour: it would often be false.organizerwould require a public name the model doesn't store. Structured data must match what's visible; publishing made-up data can cost you the rich result.
6.1. Writing it without opening a hole
The block goes in a <script type="application/ld+json">, and its content can't be set as an ordinary child, because React would escape it as text. You have to use dangerouslySetInnerHTML, the only time in the application with data written by other people. This title would be enough to attack every visitor:
JSON.stringify doesn't prevent it: it escapes quotes, not tags, and the browser closes the script as soon as it sees </script>, knowing nothing about JSON. That's why serializeJsonLd replaces every < with \u003c, which means the same in JSON and nothing in HTML. It's the promise left over from 08-06.
// components/structured-data.tsx
import { type JsonLd, serializeJsonLd } from '@/lib/json-ld'
export function StructuredData({ data }: { data: JsonLd }) {
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: serializeJsonLd(data) }}
/>
)
}// app/(public)/events/[slug]/page.tsx (EventContent)
return (
<>
<StructuredData data={createEventJsonLd(details)} />
<EventDetails {...details} />
</>
)- A single door. No other component serializes JSON into the HTML. If another
dangerouslySetInnerHTMLshows up in a review, ask about it. - It goes in the page, not in
EventDetails: the modal's quick view mustn't repeat it in the list. <script>is used, notnext/script, which is for executable code.- The CSP doesn't block it. It isn't a script that runs, but a data block. But if the injection succeeded, our policy, which allows inline scripts (08-05), wouldn't block the injected script either. Here escaping is the only defense.
- It stays in the shell of the generated event pages, because it only uses cached data.
The schema-dts package provides types for the vocabulary, useful if you're going to describe many things. For one, the function above and a validator are enough.
- Checking
npm run build && npm run start
curl -s localhost:3000/robots.txt
curl -s localhost:3000/sitemap.xml | xmllint --noout - && echo 'XML OK'
curl -s localhost:3000/sitemap.xml | grep -c '<loc>'
# Every address in the sitemap must respond with 200 without redirecting
curl -s localhost:3000/sitemap.xml | grep -oE '<loc>[^<]+' | cut -c6- |
while read -r url; do curl -so /dev/null -w '%{http_code} %{url_effective}\n' "$url"; done | grep -v '^200'
# Canonical and robots of a search, as an HTML-limited bot sees them
curl -s -A 'bingbot/2.0' 'localhost:3000/events?utm_source=x&category=workshop' | grep -oE '<link rel="canonical"[^>]*>'
curl -s -A 'bingbot/2.0' 'localhost:3000/events?q=jazz' | grep -oE '<meta name="robots"[^>]*>'
# The data block, parsed
curl -s localhost:3000/events/jazz-night |
grep -oP '(?<=application/ld\+json">).*?(?=</script>)' | head -1 | python3 -m json.toolIn the build table, /sitemap.xml appears as static, with the one-hour revalidation that the query gives it.
Try the attack: with an event whose title contains </script>, the HTML must show \u003c/script> inside the block, and the page must show the title as is.
Then, with the site published:
- Google's Rich Results Test and the schema.org validator read an address or a pasted snippet, and tell you what's missing.
- The search engine's console (Search Console for Google; the others have their own) shows what has been indexed and why not. To get in you have to prove the domain is yours: better with a DNS record than with a tag, because it doesn't depend on the code. If you use the tag, it goes in
metadata.verification. - URL inspection shows the page as the bot sees it. If the styles or the content are missing there, check
robots.txtand the data queried at request time (05-02).
Be patient: changes take days. And don't measure ranking, which varies depending on who's searching, but indexed pages and incoming visits.
Common Mistakes and Tips
- Blocking in
robots.txtand settingnoindexon the same thing. - Believing that
robots.txtprotects, or writing secret routes in it. lastModified: new Date()on every entry.- Including in the sitemap addresses that redirect, have
noindexor don't exist. canonicalto the first page across all the pagination.- Indexing internal searches.
- Redirecting past events to the home page.
JSON.stringifywithout escaping<inside a<script>.- Structured data that isn't visible on the page.
- Dates without a time zone offset.
- Forgetting
noindexin the staging environment, or carrying it into production. - Building with a
localhostSITE_URL: the whole sitemap points there.
Exercises
Exercise 1: deciding
For each address, say whether it goes in the sitemap, whether it's indexed and what its canonical is: (a) /events?page=1; (b) /events?category=theater&page=2; (c) /events?category=circus; (d) /venues/the-factory, with no upcoming events; (e) the event page of a canceled workshop scheduled for tomorrow; (f) /images/events/….webp; (g) /sign-in?returnTo=/account; (h) /api/events/jazz-night/calendar.
Solution
- (a) It isn't in the sitemap.
canonicalto/events, becausecreateEventsUrlomits page 1. - (b) Not in the sitemap; indexable,
canonicalto itself. - (c) The category doesn't exist and is ignored: it's the full guide,
canonicalto/events. - (d) Yes, yes, to itself. It's a page with its own content: address, district.
- (e) Not in the sitemap; it is indexed, so the cancellation can be seen; to itself, with
EventCancelled. - (f) Only as an image associated with its event page.
- (g) No,
noindexfrom its layout. Nocanonical. - (h) No. It's under
/api/, whichrobots.txtasks not to be crawled.
Exercise 2: a reliable modification date
Add lastModified to the sitemap with the date when the event's content changed. Booking spots doesn't count as a change; editing the text, the poster or the date, or publishing, does. Specify the schema, the writes and the query. Why doesn't Drizzle's $onUpdate option work?
Solution
// Practice only
// lib/db/schema.ts, in events
modifiedAt: timestamp('modified_at', { withTimezone: true }).notNull().defaultNow(),
// In updateEvent, changeImage and resolveReview, inside set({ … })
modifiedAt: sql`now()`,
// listEventsForSitemap
.select({ slug: events.slug, image: events.image, modifiedAt: events.modifiedAt })
// app/sitemap.ts
lastModified: modifiedAt,$onUpdate would change the value on any update, including when spots are subtracted on each booking: every event page would look freshly modified. The date is a domain decision and is written where the decision is made. now() uses the database's clock and not the server's. There's no prerendering error, because the value is cached data. The migration gives existing rows the deployment date: an inaccuracy worth accepting once and not repeating.
Exercise 3: reviewing some structured data
Find the security and content problems, and fix them.
export function EventJsonLd({ event, spots }: Props) {
const data = `{
"@context": "https://schema.org",
"@type": "Event",
"name": "${event.title}",
"startDate": "${formatDateTime(event.startsAt)}",
"aggregateRating": { "@type": "AggregateRating", "ratingValue": 4.9, "reviewCount": 120 },
"offers": { "availability": "${spots > 0 ? 'InStock' : 'SoldOut'}" }
}`
return <Script id="ld" type="application/ld+json">{data}</Script>
}Solution
- JSON built from text: quotes in the title break it, and
</script>injects code. Build an object and serialize it withserializeJsonLd. - The date is an English phrase. It must be ISO 8601 with an offset:
formatIsoDateTime. - Made-up ratings. There are no reviews in AgendaViva. It's misleading for people and grounds for a penalty from search engines.
locationis missing, which is required, along with its address.availabilityshould be a schema.org URL, and it depends on uncached data: it would force the block out of the shell, or it would lie.next/scriptis for executable code.- Missing:
eventStatusfor canceled events and@typeinoffers.
With <StructuredData data={createEventJsonLd(details)} /> they're all solved.
Conclusion
The sitemap lists what matters and is refreshed with the same tags as everything else; robots.txt says what isn't worth crawling and protects nothing; noindex and canonical separate pages from their variants, and only work if they can be read. Past events declare their own expiry, canceled ones say so, and JSON-LD describes each event page with true data and an escaping step on which everyone's security depends.
All of it in a single language. Every summer Vallenar del Río welcomes visitors who don't read English, and so far AgendaViva offers them nothing: no text, no dates in their format, no address to share. Adding a language looks like a translation task and turns out to be an architecture one. It's the module's last lesson, Internationalization.
