withastro/astro
View transitions
Astro's built-in client-side router that uses the View Transitions API to animate between pages. Adding <ClientRouter /> to a layout opts a project into smoothly-transitioned same-origin navigation.
Purpose
- Avoid full-page reloads while keeping pages individually authored as Astro pages.
- Animate in/out elements that match
transition:namebetween routes. - Preserve scroll position, focus, and form state with minimal user code.
Key files
| File | Purpose |
|---|---|
packages/astro/src/transitions/router.ts |
The client-side router (~the largest of the transitions sources). Hooks navigations, fetches the next page, applies transitions. |
packages/astro/src/transitions/swap-functions.ts |
DOM swap strategies (auto, same, custom). |
packages/astro/src/transitions/events.ts |
The custom event surface (astro:before-preparation, astro:after-preparation, astro:before-swap, astro:after-swap, astro:page-load, astro:before-rate-limit). |
packages/astro/src/transitions/cssesc.ts |
CSS-escape helpers for view transition names. |
packages/astro/src/transitions/types.ts |
Public types. |
packages/astro/src/transitions/vite-plugin-transitions.ts |
Vite plugin that injects the router script. |
packages/astro/components/ViewTransitions.astro, ClientRouter.astro |
User-facing components. |
How it works
graph LR
A[Click on link] -->|history.pushState| B[ClientRouter intercepts]
B --> C[Fetch new HTML]
C --> D[Parse + extract <head> / <body>]
D --> E[document.startViewTransition]
E --> F[Swap function]
F --> G[Run inline scripts on new page]
G --> H[Emit astro:after-swap]The router falls back to a normal navigation if document.startViewTransition is unavailable. The swap is configurable via transition:persist, transition:name, and data-astro-reload on individual links.
Persistence and re-mounting
transition:persistkeeps a DOM node alive across navigations (useful for video players, audio elements).- Astro fires
astro:before-swapbefore the DOM is replaced, giving user code a chance to mutate the incoming document.
E2E coverage
packages/astro/e2e/view-transitions.test.ts is the single largest e2e test in the repo (1,884 lines). Many subtle scroll, focus, and history behaviors are pinned by tests there.
Related pages
- features / prefetch — frequently used together.
- features / dev toolbar — the "View transitions inspector" toolbar app shows live transition events.
Built by Factory AutoWiki from public repository content. It is a generated preview for codebase exploration, not source-maintained documentation.