Making breadcrumbs base on routes is straightforward. In SvelteKit, +page.server.ts, +page.ts, +layout.server.ts, and +layout.ts load functions have an event parameter with an async parent() method that returns data from parent +layout.server.ts and +layout.ts load functions.
By placing a breadcrumbs array in the root layout, you can use event.parent() and Array.concat to append breadcrumbs at each route segment which requires a breadcrumb. And you can use data from that route segment to make the breadcrumb value and href dynamic.
Leon Radley came up with a clever way to use $effect to create a global store that automatically adds and removes segments as layouts mount and unmount.
This method uses a SvelteMap, a reactive Map from Svelte, to hold the individual breadcrumb segments. When the setBreadcrumb function is called from a +layout.svelte file, the effect will insert the segment into the SvelteMap. When the layout unmounts during navigation, the effect cleanup function runs and the segment will be automatically removed.
The getBreadcrumbs function returns an array of breadcrumbs sorted by the number of path segments in the path property.
<script lang="ts"> import { setBreadcrumb } from '$lib/breadcrumb-state.svelte' import type { LayoutProps } from './$types'const { children }: LayoutProps = $props()setBreadcrumb({name: 'Level 1',path: '/level-1/',})</script>{@render children()}
svelte
<script lang="ts"> import { getBreadcrumbs } from './breadcrumb-state.svelte'</script><nav class="breadcrumbs text-sm"> <ul> {#each getBreadcrumbs() as breadcrumb (breadcrumb.path)} <li><a href={breadcrumb.path}>{breadcrumb.name}</a></li> {/each} </ul></nav>
Using Page Module Exports (SSR)
This method uses the import.meta.glob function to import the page modules and extract the pageTitle or getPageTitle function from each module. If a page module does not export a pageTitle or getPageTitle function, it will use the corresponding URL pathname segment to generate a title.