Structuring Photos as a Collection Tree
How the photos of my old Astro site grew from flat albums into a recursive tree: one catch-all route, photos per node, breadcrumbs and tag pages.
Reviewed by adrian
on
The albums of my old site were a flat list, each album holding photos. That worked for a handful of trips and fell apart once places started to nest. Asia is no album; it is a region with cities, and each city is a collection of its own. So I turned the section into a recursive collection tree and built tag pages on the same data.
Later the site went bilingual, and the content collection described here did not survive that. Why the photo tree is no content collection explains what came instead. This page records the design as it was in March.
The setup
- Astro 6 content layer, without
@astrojs/mdx. - A new root,
src/content/photos/collections/: every folder with anindex.mdis a collection node, and its photos sit in animg/folder inside it. - One route,
[...slug].astro, renders every collection page and every photo page.
The folders are the URLs
src/content/photos/collections/
├── travels/
│ ├── index.md
│ └── asia/
│ ├── index.md
│ ├── img/ ← photos belonging to "Asia" directly
│ ├── chiang-mai/
│ │ ├── index.md
│ │ └── img/
│ └── singapore/
│ ├── index.md
│ └── img/
The URL of a collection is its folder path, /photos/collections/travels/asia/chiang-mai, and a photo in it is /photos/collections/travels/asia/chiang-mai/2025-10-06-121017. No configuration, no slug mapping.
A content collection for the metadata only
getCollection loads only the index.md files, not the images or sidecars:
const collections_photos = defineCollection({
loader: glob({
pattern: "**/index.{md,mdx}",
base: "./src/content/photos/collections",
}),
schema: z.object({
title: z.string(),
description: z.string(),
location: z.string().optional(),
order: z.number().int().default(0),
draft: z.boolean().default(false),
}),
});
The entry ID of travels/asia/chiang-mai/index.md is exactly that path, which strips cleanly to a slug:
function collectionSlug(entry: CollectionEntry<"collections_photos">): string {
return entry.id
.replace(/\/index\.mdx?$/, "")
.replace(/^index\.mdx?$/, "");
}
One route file for everything
A recursive tree needs collection pages (child cards plus the node's own photos) and photo pages, at every depth. Two route files would have duplicated much of the layout and slug logic. So a single [...slug].astro generates all routes, and getStaticPaths emits two shapes of props:
type CollectionProps = { type: "collection"; slug: string; title: string; … };
type PhotoProps = { type: "photo"; sidecar: PhotoSidecar; image: ImageMetadata; … };
For each collection it emits one collection path and one path per photo:
for (const col of allCollections) {
const slug = collectionSlug(col);
const photos = buildCollectionPhotos(sidecars, imageModules, slug);
paths.push({ params: { slug }, props: { type: "collection", … } });
photos.forEach((photo, i) => {
paths.push({
params: { slug: `${slug}/${photo.sidecar.id}` },
props: { type: "photo", … },
});
});
}
The template branches on props.type.
Photos per node, not recursive
buildCollectionPhotos loads only the photos directly in a node's img/ folder:
function buildCollectionPhotos(sidecars, imageModules, slug): LoadedPhoto[] {
const prefix = `/src/content/photos/collections/${slug}/img/`;
return Object.entries(sidecars)
.filter(([p]) => p.startsWith(prefix) && !p.slice(prefix.length).includes("/"))
.map(([jsonPath, sidecar]) => {
const imgPath = jsonPath.replace(/\.json$/, ".jpg");
const image = imageModules[imgPath]?.default;
if (!image) return null;
return { sidecar, image };
})
.filter((p): p is LoadedPhoto => p !== null)
.sort((a, b) => new Date(a.sidecar.date).getTime() - new Date(b.sidecar.date).getTime());
}
A collection page shows its own photos and cards for its children, never the photos of grandchildren.
Breadcrumbs
Every collection page gets a breadcrumb trail from the slug segments:
function buildBreadcrumbs(slug, allCollections): Breadcrumb[] {
const crumbs = [{ label: "Collections", href: "/photos/collections" }];
const segments = slug.split("/");
for (let i = 0; i < segments.length; i++) {
const partialSlug = segments.slice(0, i + 1).join("/");
const entry = allCollections.find((c) => collectionSlug(c) === partialSlug);
crumbs.push({
label: entry?.data.title ?? segments[i],
href: `/photos/collections/${partialSlug}`,
});
}
return crumbs;
}
For travels/asia/chiang-mai that gives Collections / Travels / Asia / Chiang Mai.
Tag pages
Every sidecar already had a tags array from the vision model. Two new pages made them browsable. /photos/tags collects the tags of all sidecars, counts them and shows them as pills in alphabetical order:
const tagMap = new Map<string, { label: string; count: number }>();
for (const sidecar of Object.values(sidecars)) {
for (const tag of sidecar.tags) {
const slug = tagToSlug(tag);
const entry = tagMap.get(slug);
if (entry) entry.count++;
else tagMap.set(slug, { label: tag, count: 1 });
}
}
/photos/tags/[slug] shows every photo with that tag in the same justified grid as the stream and the collections. The photo links still point to the photo's URL in its collection; the tag page is a view, not a second home. On the photo page the tags became links to their tag page at the same time. All three files build tag URLs with the same helper, tagToSlug(). It lowercases the tag, turns whitespace into hyphens and drops every character other than a to z, 0 to 9 and the hyphen.
The dev server and import.meta.glob
When new files land in a folder that a glob pattern already covers, the dev server may not pick them up in getStaticPaths until a restart. The collection page still shows the new thumbnails, because it calls buildCollectionPhotos on every request. But getStaticPaths stays as it was at the last start, so the photo page returns a 404. A restart fixes it; that is how Vite behaves, not a routing bug.
Takeaways
- An
index.mdper folder plus a[...slug].astrogives a recursive tree without any mapping from slug to path. - One catch-all route with two prop shapes beats two parallel route trees.
- Load photos per node, not recursively.
- One
tagToSlughelper used everywhere keeps tag URLs from drifting apart.
Based on
-
Structuring Photos as a Collection Tree
(
raw/2026/2026-03-21/structuring-photos-as-a-collection-tree.md) [post]
Topic
- Static Website A website made of finished HTML files that are built once and then served unchanged. No server code, no database.
Basis for
- Collection Sets and Category Collections One boolean in the frontmatter told the photo sets of my old site apart from pure navigation nodes, so only finished sets reached the archive.
Builds on
- Photo Albums with Astro's Content Layer Album pages on top of the photo stream of my old site: a content collection per album, covers by filename, album-scoped photo routes and a sub-nav.
Uses
- Astro Tool for building websites from content such as Markdown. Ships plain HTML by default and only loads JavaScript where it is needed.
Mentioned in
- Building the Photo Stream The photo stream of my old Astro site: JSON sidecars next to each JPG, import.meta.glob, a justified grid and batches revealed on scroll.
Mentioned
- Why the Photo Tree Is No Content Collection Anymore When my old Astro site went bilingual, the photo tree left the content layer: every photo and node needs both languages in one file.