Astro view transitions animate the change from one page to the next. You can get them two ways: add one CSS rule, @view-transition { navigation: auto; }, for native cross-document transitions with no JavaScript, or add <ClientRouter /> from astro:transitions to your layout, which turns navigation into client-side routing and adds transition:name, transition:animate and transition:persist directives, lifecycle events and a fallback for browsers without the View Transition API.
This guide covers both approaches in Astro 7, the directives, the events you’ll need for scripts, and the pitfalls that catch most sites after switching.
Key Takeaways
- Native CSS view transitions need no JavaScript and work across full page loads in supporting browsers.
<ClientRouter />in the<head>intercepts same-origin links and swaps pages without a reload.transition:namepairs elements across pages;transition:persistkeeps an element (and its state) alive.- With the router, page scripts don’t re-run on navigation. Use the
astro:page-loadevent instead ofDOMContentLoaded.- Add
data-astro-reloadto any link that must do a full page load.
Two ways to add view transitions in Astro
| Native CSS | <ClientRouter /> |
|
|---|---|---|
| JavaScript | None | The router script on every page |
| Navigation | Normal full page loads | Client-side, no reload |
| Browser support | Browsers with cross-document view transitions | All browsers, with a fallback animation |
| Persist state between pages | No | Yes, with transition:persist |
| Lifecycle events | Standard pageswap / pagereveal |
astro:before-preparation to astro:page-load |
| Script behaviour | Scripts run on every page as normal | Bundled scripts run once; re-init on astro:page-load |
If you only want a fade between pages, start with native CSS. If you need persistent elements, such as an audio player or a video that keeps playing, or consistent behaviour in every browser, use the router. Our comparison of ClientRouter vs native view transitions goes deeper into the trade-offs.
Native cross-document transitions
Add this to a global stylesheet:
/* src/styles/global.css */
@view-transition {
navigation: auto;
}
That’s it. On same-origin navigations, supporting browsers capture the old page, load the new one, and cross-fade between them. Browsers without support just navigate normally, so there’s nothing to break.
To animate a specific element, give it the same view-transition-name on both pages:
---
// src/components/PostCard.astro
const { post } = Astro.props;
---
<a href={`/blog/${post.id}/`}>
<img
src={post.data.cover}
alt=""
style={`view-transition-name: cover-${post.id}`}
/>
<h2>{post.data.title}</h2>
</a>
Use the same name on the post page’s hero image and the browser morphs the card image into the hero. Names must be unique on a page, which is why the post id is part of the name.
Customize the animation with the ::view-transition-old() and ::view-transition-new() pseudo-elements, and respect reduced motion:
/* src/styles/global.css */
@media (prefers-reduced-motion: reduce) {
::view-transition-group(*),
::view-transition-old(*),
::view-transition-new(*) {
animation: none !important;
}
}
Adding the ClientRouter
For the router, add the component to the <head> of every page, usually in your base layout:
---
// src/layouts/BaseLayout.astro
import { ClientRouter } from 'astro:transitions';
const { title } = Astro.props;
---
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{title}</title>
<ClientRouter />
</head>
<body>
<slot />
</body>
</html>
Now same-origin links are intercepted. The router fetches the next page, swaps the <head> and <body>, updates history and scroll position, announces the new page title for screen readers, and wraps the swap in a view transition where the browser supports it.
<ClientRouter /> was called <ViewTransitions /> in older versions of Astro. If you’re upgrading an old project, rename the import.
The fallback prop
In browsers without the View Transition API, the router still navigates without reloading. The fallback prop controls what happens visually:
<ClientRouter fallback="animate" /> <!-- default: Astro simulates the animation -->
<ClientRouter fallback="swap" /> <!-- swap with no animation -->
<ClientRouter fallback="none" /> <!-- full page loads in unsupported browsers -->
When the visitor has prefers-reduced-motion enabled, Astro disables the transition animations, including the fallback.
The transition directives
With the router in place, three directives control individual elements.
transition:name
Pairs elements across the old and new page, the router’s equivalent of view-transition-name:
---
// src/pages/blog/[id].astro
const { post } = Astro.props;
---
<img src={post.data.cover} alt="" transition:name={`cover-${post.id}`} />
<h1 transition:name={`title-${post.id}`}>{post.data.title}</h1>
Astro generates names automatically for elements it can match, but explicit names give you control and make the morph predictable.
transition:animate
Sets the animation for an element. Built-in values are fade (the default), slide, initial (the browser’s default) and none:
---
// src/layouts/BaseLayout.astro
import { fade, slide } from 'astro:transitions';
---
<header transition:animate="none">...</header>
<main transition:animate={slide({ duration: '0.3s' })}>
<slot />
</main>
<footer transition:animate={fade({ duration: '0.2s' })}>...</footer>
transition:animate="none" on a header keeps it perfectly still while the content changes, which looks more polished than fading the whole page. Put transition:animate="none" on the <html> element to turn off the default root animation entirely.
transition:persist
Keeps an element in the DOM across navigations instead of replacing it:
---
// src/layouts/BaseLayout.astro
import Player from '../components/Player.jsx';
---
<video controls muted autoplay transition:persist="intro-video" src="/intro.mp4"></video>
<Player client:load transition:persist />
A playing video keeps playing, and a hydrated island keeps its state. For islands, the router reuses the component instance if it finds a matching one on the next page. Add transition:persist-props if the island should keep its old props rather than receiving the new page’s props.
Scripts and lifecycle events
This is where most sites break after adding the router. Bundled <script> tags in Astro components are modules, and modules run once. After a client-side navigation, the new page’s elements exist, but the script that attached event listeners already ran on the previous page.
Wrap setup code in an astro:page-load listener, which fires on the first load and after every navigation:
---
// src/components/MenuToggle.astro
---
<button id="menu-toggle" aria-expanded="false">Menu</button>
<script>
document.addEventListener('astro:page-load', () => {
const button = document.querySelector('#menu-toggle');
button?.addEventListener('click', () => {
const open = button.getAttribute('aria-expanded') === 'true';
button.setAttribute('aria-expanded', String(!open));
});
});
</script>
The full sequence of events on each navigation:
| Event | When | Typical use |
|---|---|---|
astro:before-preparation |
Before the next page is fetched | Show a loading indicator, change the URL to load |
astro:after-preparation |
Next page fetched and parsed | Hide the loading indicator |
astro:before-swap |
Just before the DOM swap | Copy state onto the new document (theme class) |
astro:after-swap |
Right after the swap | Restore things like dark mode before paint |
astro:page-load |
Navigation complete | Re-initialize scripts and analytics |
A common need is keeping a dark-mode class on <html>, which the swap replaces:
<script is:inline>
function applyTheme() {
const dark = localStorage.getItem('theme') === 'dark';
document.documentElement.classList.toggle('dark', dark);
}
applyTheme();
document.addEventListener('astro:after-swap', applyTheme);
</script>
Inline scripts (is:inline) in the new page’s body do re-run after a swap. To make a bundled script re-run too, add data-astro-rerun to it.
Controlling navigation
Opt a link out of the router with data-astro-reload, which forces a normal full page load. Use it for links into parts of the site that don’t use the router, or pages with heavy third-party scripts:
<a href="/app/" data-astro-reload>Open the app</a>
<a href="/search/?q=astro" data-astro-history="replace">Search</a>
data-astro-history="replace" replaces the current history entry instead of pushing a new one. To navigate from code, use navigate():
// src/scripts/search.ts
import { navigate } from 'astro:transitions/client';
const form = document.querySelector<HTMLFormElement>('#search');
form?.addEventListener('submit', (event) => {
event.preventDefault();
const q = new FormData(form).get('q');
navigate(`/search/?q=${encodeURIComponent(String(q))}`);
});
The router also handles <form> submissions to same-origin URLs, including POST, so forms keep working without a reload.
View transitions and performance
View transitions don’t make pages load faster on their own. With the router, the next page is fetched as HTML just like a normal navigation, and the swap avoids re-parsing shared CSS and keeps persistent elements alive. Combine it with prefetching so the fetch starts before the click:
// astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
prefetch: { prefetchAll: true, defaultStrategy: 'hover' },
});
With <ClientRouter />, prefetching is enabled by default. The Astro prefetch tip covers the strategies. Keep the router’s cost in mind: it adds a script to every page, which a purely static site with native CSS transitions doesn’t need. Our Astro performance guide covers the rest of the page-speed checklist.
Common view transition problems
- Menus or buttons stop working after navigating. Scripts ran once. Move setup into
astro:page-load. - Dark mode flashes on navigation. Re-apply the theme class in
astro:after-swap. - Analytics count only the first page. Send page views from
astro:page-load. - Duplicate
transition:namevalues. Names must be unique per page; include an id. - Third-party widgets break. Load them with a full page load using
data-astro-reload, or re-initialize them onastro:page-load.
Komal themes ship as plain multi-page Astro 7 sites, so you can add either approach to the base layout in a few lines; browse Astro themes and see the astro.config docs for where prefetch options go. The official view transitions guide documents every option.
FAQ
How do I enable view transitions in Astro?
For native transitions, add @view-transition { navigation: auto; } to your global CSS. For client-side routing with Astro’s directives and events, import ClientRouter from astro:transitions and place <ClientRouter /> in the <head> of your layout.
What happened to ViewTransitions in Astro?
The <ViewTransitions /> component was renamed to <ClientRouter />. It’s imported from the same astro:transitions module and works the same way, so upgrading is a rename.
Why do my scripts stop working with Astro view transitions?
With <ClientRouter />, bundled module scripts run only once, on the first page. Wrap your setup code in document.addEventListener('astro:page-load', ...), which runs after every navigation.
Do Astro view transitions work in all browsers?
Native CSS transitions only animate in browsers that support cross-document view transitions; others navigate normally. <ClientRouter /> works everywhere, using the View Transition API where available and a simulated fallback animation elsewhere.
Do view transitions hurt SEO in Astro?
No. Every page is still a complete HTML document at its own URL, which crawlers fetch directly. The router only changes how the browser moves between pages after the first load.