🔥 All-Access Pass — $199 USD (Regular $499) · Unlock all 2,836 Astro themes ➔
komal.nakrani
Get All-Access Pass ($199)
ThemesCategoriesDocsBlogTips & TricksPricingGet All-Access Pass ($199)
CMS & Integrations••By Komal Nakrani

Astro Lottie: Add Lottie Animations Without the Bloat

Astro Lottie setup with lottie-web or dotLottie: a reusable player component, lazy loading on scroll, reduced motion, no layout shift and ClientRouter cleanup.

#Astro#Lottie#Animation#Web Components#Performance

To use Lottie in Astro, put the exported animation file in public/, install a player such as lottie-web or @lottiefiles/dotlottie-web, and start it from a <script> inside an .astro component. No integration or UI framework is needed. The one thing that matters for performance is loading the player only when the animation is about to be seen, because the player is far heavier than a typical Astro page.

This guide builds a reusable Astro Lottie component step by step: basic playback, lazy loading, reduced motion, layout-shift prevention and cleanup when you use <ClientRouter />.

Key Takeaways

  • Lottie files are JSON (or zipped .lottie) exports from After Effects or LottieFiles; Astro serves them from public/ like any static asset.
  • Wrap the player in a custom element so every instance sets itself up and tears itself down.
  • Import the player with a dynamic import() inside an IntersectionObserver so pages that never scroll to it never download it.
  • Reserve space with aspect-ratio and show a static frame for prefers-reduced-motion.
  • For small icons and loaders, CSS or an animated SVG is usually lighter than any Lottie player.

What Lottie is and when it fits an Astro site

Lottie is a format for vector animation. A designer builds the motion in After Effects (with the Bodymovin exporter) or in LottieFiles’ own tools, exports it as JSON, and a JavaScript player redraws it in the browser as SVG or inside a <canvas> element. The result stays sharp at any size and is usually much smaller than the same animation as video.

It fits Astro sites when the animation is designed rather than coded: an illustrated hero, an onboarding sequence on a SaaS page, a product explainer, an empty-state character. It’s a poor fit for things CSS already does well, such as hover effects, spinners and fades. Our Astro animation options guide compares Lottie with CSS, Motion and GSAP if you’re still choosing.

There are two common players:

Player Package Renders to File formats Notes
lottie-web lottie-web SVG, canvas or HTML .json The original Airbnb player; widely used, large bundle
dotLottie @lottiefiles/dotlottie-web canvas (WebAssembly renderer) .lottie and .json From LottieFiles; supports the compressed .lottie format

Both work the same way in Astro: you give them a container element and a file URL. Pick lottie-web if you need SVG output (crisp at every zoom level, styleable with CSS) and dotLottie if your files are .lottie or you want the smaller file format.

Step 1: install a player and add the file

Install one player:

# terminal
npm install lottie-web

Then put your exported animation in public/, which Astro copies to the build output untouched:

public/
  animations/
    hero.json

The file is now served at /animations/hero.json. Keep Lottie files out of src/ unless you want them bundled into JavaScript, which defeats lazy loading.

Step 2: a minimal Astro Lottie component

The shortest working version is a container div and a script that calls loadAnimation():

---
// src/components/LottieBasic.astro
---
<div id="hero-animation" class="lottie"></div>

<script>
  import lottie from 'lottie-web';

  lottie.loadAnimation({
    container: document.getElementById('hero-animation')!,
    renderer: 'svg',
    loop: true,
    autoplay: true,
    path: '/animations/hero.json',
  });
</script>

<style>
  .lottie { width: 100%; max-width: 480px; aspect-ratio: 1 / 1; }
</style>

Astro processes the <script> as a module, bundles lottie-web into it and includes it once per page. That works, but it has three problems: the ID means you can only use it once per page, the player downloads on every page that renders the component even if the animation is far below the fold, and nothing respects reduced motion.

Step 3: a reusable, lazy-loaded Lottie component

A custom element fixes all three. Each <lottie-player> reads its own settings from data attributes, waits until it’s near the viewport, and only then imports the player:

---
// src/components/Lottie.astro
interface Props {
  src: string;
  label: string;
  loop?: boolean;
  ratio?: string;
  poster?: string;
}
const { src, label, loop = true, ratio = '1 / 1', poster } = Astro.props;
---
<lottie-player
  data-src={src}
  data-loop={String(loop)}
  role="img"
  aria-label={label}
  style={`aspect-ratio: ${ratio}`}
>
  {poster && <img src={poster} alt="" width="480" height="480" />}
</lottie-player>

<script>
  class LottiePlayer extends HTMLElement {
    private anim?: { destroy(): void; goToAndStop(v: number, isFrame?: boolean): void };
    private observer?: IntersectionObserver;

    connectedCallback() {
      this.observer = new IntersectionObserver(
        (entries) => {
          if (entries.some((e) => e.isIntersecting)) {
            this.observer?.disconnect();
            this.start();
          }
        },
        { rootMargin: '200px' }
      );
      this.observer.observe(this);
    }

    async start() {
      const { default: lottie } = await import('lottie-web');
      const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      this.replaceChildren();
      this.anim = lottie.loadAnimation({
        container: this,
        renderer: 'svg',
        loop: !reduce && this.dataset.loop === 'true',
        autoplay: !reduce,
        path: this.dataset.src!,
      });
      if (reduce) {
        (this.anim as any).addEventListener('DOMLoaded', () => this.anim?.goToAndStop(0, true));
      }
    }

    disconnectedCallback() {
      this.observer?.disconnect();
      this.anim?.destroy();
    }
  }

  customElements.define('lottie-player', LottiePlayer);
</script>

<style>
  lottie-player { display: block; width: 100%; max-width: 480px; }
  lottie-player img { width: 100%; height: 100%; object-fit: contain; }
</style>

Use it from any page or component:

---
// src/pages/index.astro
import Lottie from '../components/Lottie.astro';
---
<Lottie
  src="/animations/hero.json"
  label="Illustration of a parcel moving through three delivery stages"
  ratio="4 / 3"
  poster="/animations/hero-poster.png"
/>

What each part does:

  • Dynamic import('lottie-web'): Vite splits the player into its own chunk. The page’s main script stays tiny, and the player downloads only when an animation scrolls within 200 px of the viewport.
  • aspect-ratio on the element: the box has its final size before the animation loads, so nothing below it jumps. This matters for Cumulative Layout Shift; see preventing layout shift in Astro.
  • Poster image: shows a static frame until the player replaces it, and is what users see if JavaScript fails.
  • role="img" and aria-label: Lottie output is a pile of SVG paths. Give screen readers one sentence about what the animation shows, or use aria-hidden="true" if it’s purely decorative.
  • disconnectedCallback: destroys the animation when the element leaves the DOM, which is what makes it safe with client-side navigation.

Using dotLottie instead

If your designer hands you .lottie files, swap the player inside start(). dotLottie renders into a <canvas> element, so the custom element creates one:

// inside start() in src/components/Lottie.astro
const { DotLottie } = await import('@lottiefiles/dotlottie-web');
const canvas = document.createElement('canvas');
canvas.style.width = '100%';
canvas.style.height = '100%';
this.replaceChildren(canvas);

this.player = new DotLottie({
  canvas,
  src: this.dataset.src!,
  loop: !reduce && this.dataset.loop === 'true',
  autoplay: !reduce,
});

Call this.player.destroy() in disconnectedCallback() as before. Install it with npm install @lottiefiles/dotlottie-web. The canvas renderer can’t be styled with CSS the way SVG output can, so check the dotlottie-web repository for the current option list before relying on features like theming or state machines.

Lottie and the ClientRouter

With <ClientRouter />, Astro swaps page content without a full reload, and bundled scripts run only once. Plain loadAnimation() calls at the top level of a script won’t run again for the next page, and animations from the previous page keep their timers running.

Custom elements avoid both problems without extra code. The browser calls connectedCallback() for every <lottie-player> that appears in the swapped-in page and disconnectedCallback() for every one that’s removed. If you skip the custom element, wrap setup in astro:page-load and destroy animations in astro:before-swap:

// src/scripts/lottie-router.ts
import lottie from 'lottie-web';

document.addEventListener('astro:page-load', () => {
  document.querySelectorAll<HTMLElement>('[data-lottie]').forEach((el) => {
    lottie.loadAnimation({ container: el, renderer: 'svg', path: el.dataset.lottie! });
  });
});

document.addEventListener('astro:before-swap', () => lottie.destroy());

lottie.destroy() with no argument destroys every animation the player knows about. The Astro view transitions guide covers the lifecycle events in more detail.

Keep Lottie light

The player is the cost, not the JSON file. A few habits keep Astro Lottie animations cheap:

  1. Use one animation per page where you can. Every instance shares the player, but each one runs its own render loop.
  2. Ask for simpler exports. Effects, masks, mattes and embedded raster images make files larger and rendering slower. Shape layers render best.
  3. Try the light build of lottie-web. lottie-web/build/player/lottie_light includes only the SVG renderer and skips expression support. Test your file with it, since animations that rely on expressions will break.
  4. Pause off-screen animations. For long loops, observe the element and call pause() when it leaves the viewport and play() when it returns.
  5. Don’t use Lottie for loaders above the fold. By the time the player loads, the content it was waiting for has often arrived. A CSS spinner is instant.

If the animation is only decorative motion on a button or icon, an animated SVG with CSS keyframes, or an inline SVG component, is usually smaller still. Our guide to SVG components in Astro shows how to import SVGs directly.

Where Lottie shows up on real Astro sites

Lottie is most common on product and SaaS marketing sites, where an explainer animation replaces screenshots that would go stale. Most Komal themes take a different route and draw their motion in CSS, so they ship zero JavaScript by default; you can drop the component above into any of them if a designer supplies a Lottie file. The Technology category has the SaaS and product themes where that’s most likely, and Astro styling docs explain where component styles live. For how Astro bundles and deduplicates component scripts, the official client-side scripts guide is the reference.

FAQ

Can I use Lottie with Astro?

Yes. Install lottie-web or @lottiefiles/dotlottie-web, put the animation file in public/, and start the player from a <script> tag in an .astro component. No Astro integration or UI framework is required.

Do I need React to use Lottie in Astro?

No. React wrappers such as lottie-react work inside a React island, but they add React to the page. The vanilla players run directly in Astro’s bundled scripts, which keeps the page lighter.

Where should I put Lottie JSON files in an Astro project?

Put them in public/, for example public/animations/hero.json, and load them by URL. Files in public/ are copied to the build unchanged and fetched only when the player requests them.

How do I stop a Lottie animation causing layout shift?

Give the container its final size before the player loads, using CSS aspect-ratio or fixed width and height. A poster image inside the container also gives users something to see while the animation loads.

Is Lottie bad for performance?

The animation files are usually small, but the player is a large script. Load it with a dynamic import() when the animation nears the viewport, use one animation per page where possible, and choose CSS for simple effects.