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.

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 an index.md is a collection node, and its photos sit in an img/ 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.

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.md per folder plus a [...slug].astro gives 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 tagToSlug helper used everywhere keeps tag URLs from drifting apart.

More on this

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
Builds on
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

Show in the graph view →