Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Performance and Deployment

Astro View Transitions and Client-Side Navigation

Add animated page transitions to Astro with ClientRouter, name and persist elements, run scripts after swaps and respect reduced-motion preferences.

A normal link click tears down the page and loads another: a white flash, a lost scroll position, playing media stops. Single-page apps avoid this by swapping content in place, but they cost a lot of JavaScript. Astro offers a middle path: view transitions. Your site stays multi-page and server-rendered, and Astro adds smooth navigation and optional animations on top.

There are two layers:

  1. The browser's native View Transitions API, which animates between two DOM states.
  2. Astro's <ClientRouter /> component, which intercepts link clicks, fetches the next page, swaps the DOM and triggers the animation. It also gives you fallbacks and lifecycle events.

Enable it

Add the component to the <head> of your layout (once, so every page that uses the layout gets it):

ASTRO
---
// src/layouts/Base.astro
import { ClientRouter } from 'astro:transitions';
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>My site</title>
    <ClientRouter />
  </head>
  <body>
    <slot />
  </body>
</html>

That is all. Links now navigate without a full reload, with a short cross-fade by default. In older Astro versions this component was called <ViewTransitions />; the behaviour is the same.

Browsers that support cross-document view transitions can animate without ClientRouter using CSS (@view-transition { navigation: auto; }). ClientRouter adds wider support, persistence and the events below. Pick whichever matches your needs.

Animations

Control a transition with directives on elements:

ASTRO
<main transition:animate="slide">
  <slot />
</main>
<header transition:animate="none">...</header>

Built-ins: fade (default), initial (browser default), slide, none. You can write your own:

ASTRO
---
import { fade } from 'astro:transitions';
---
<div transition:animate={fade({ duration: '0.4s' })}>...</div>

Morphing between pages

Give the same transition:name to elements on two pages and the browser animates one into the other:

ASTRO
<!-- list page -->
<img src={post.cover} transition:name={`cover-${post.slug}`} />

<!-- detail page -->
<img src={cover} transition:name={`cover-${slug}`} />

Names must be unique on a page, so include an id. This produces the famous "thumbnail grows into a hero image" effect.

Persisting elements

By default, navigation replaces the body. To keep something alive across pages (audio player, video, an open sidebar, an island with state) add transition:persist:

ASTRO
<audio controls src="/music.mp3" transition:persist></audio>
<Counter client:load transition:persist />

An island with transition:persist is not re-created, so its state survives. Use a matching transition:persist="player" name if you need to be explicit. Persisted elements must exist on both pages.

Lifecycle events and scripts

A subtle trap: scripts that run on page load now run once, not on every navigation, because the page never fully reloads. Use Astro's events:

Event When
astro:before-preparation A navigation starts (before fetching)
astro:after-preparation The new page was fetched
astro:before-swap Just before the DOM swap
astro:after-swap Right after the swap, before paint
astro:page-load After navigation completes, and also on the first load
ASTRO
<script>
  document.addEventListener('astro:page-load', () => {
    document.querySelectorAll('pre').forEach(addCopyButton);
  });
</script>

Use astro:page-load for "run on every page". If a theme must be re-applied to the new document (the DOM was replaced), do it in astro:after-swap:

ASTRO
<script is:inline>
  document.addEventListener('astro:after-swap', () => {
    const dark = localStorage.getItem('theme') === 'dark';
    document.documentElement.classList.toggle('dark', dark);
  });
</script>

Bundled <script> tags in a page run once; is:inline scripts are re-executed on each swap unless marked data-astro-rerun rules. When something fails after navigation, check which of these applies.

Programmatic navigation and opting out

ASTRO
<script>
  import { navigate } from 'astro:transitions/client';
  document.querySelector('#go')?.addEventListener('click', () => navigate('/blog', { history: 'push' }));
</script>

Opt a link out with data-astro-reload (does a full reload). Forms are intercepted too; add data-astro-reload to a form that must do a normal submit.

Accessibility

  • Astro respects prefers-reduced-motion: animations are turned off for users who ask for less motion. Do not override this.
  • Astro adds a route announcer (an aria-live region) so screen readers hear the new page title after navigation. Make sure every page has a distinct <title>.
  • Focus moves to the top of the new page content.

Costs and trade-offs

ClientRouter ships a small script (a few KB) to every page and changes how page scripts behave. Use it when smooth navigation or persistent elements are valuable (portfolios, media sites, apps with players). A documentation site with simple links may not need it, and the native CSS approach may be enough.

Try it: swap and lifecycle

A stand-in client router: it keeps pages as strings, swaps the "document", and fires the same events in the same order. It also demonstrates why astro:page-load is the right place for initialisation.

JS Router lifecycle

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Try it: matching names for a morph

The browser animates between elements that share a transition:name. This stand-in finds the pairs between two pages and flags duplicates, the most common mistake.

JS Pairing transition names

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you add <ClientRouter />?

    Put it in the head of the layout used by the pages that should navigate with transitions.
  2. 2. Which attribute keeps an audio player playing across navigation?

    transition:persist keeps the element (and island state) instead of replacing it with the new page's copy.
  3. 3. Your init code stopped running after the first navigation. What is the likely fix?

    Pages are no longer fully reloaded, so page-level setup must listen for astro:page-load, which fires after each navigation.
  4. 4. What must be true of transition:name values?

    Two elements with the same name on one page confuse the browser's pairing, and animations break.

Summary

  • <ClientRouter /> adds animated, no-reload navigation to a multi-page site.
  • Use transition:animate, transition:name and transition:persist to shape animations and keep elements alive.
  • Re-run setup code on astro:page-load and re-apply per-document state on astro:after-swap.
  • Respect reduced motion and give each page a unique title.
  • It costs a small script on every page; use it where the experience justifies it.

Next: Prefetching and Caching Strategies