next.js / ssr-safeapp router · pages router

Scroll animations for Next.js

svg-scroll-draw is built SSR-first. All scroll APIs guard against window being undefined. Works in App Router Server Components, Client Components, and Pages Router — no hydration errors, no document is not defined.

React guide →
Gzipped
11.9 KB
Server render
No-op
Patterns
4
Licence
MIT

servernode · render

  1. app/page.tsxA Server Component. Fetches its data and renders on the server.
  2. 'use client' <FadeUp>Still pre-rendered to HTML with the rest of the page.
  3. typeof window === 'undefined'Every engine returns a no-op instance. Nothing touches the DOM.

browserclient · scroll

  1. hydrateThe markup matches what the server sent. No hydration error.
  2. useEffectRuns in the browser only. The engine attaches to the element.
  3. animation-timeline: view()Supported: the browser’s scroll timeline, no JS per frame. Not yet: the JS engine.native CSSorJS engine
Fig. 1 — one animated component, from request to scroll
01The answer

Render it from a Server Component

The components in svg-scroll-draw/react carry 'use client' (from v2.16.1), so a Server Component renders them directly: your markup is server-rendered, and the animation starts in the browser. The page needs no directive.

app/page.tsx17 lines
// app/page.tsx — a Server Component, no directive
import { ScrollAnimate, ScrollDraw } from 'svg-scroll-draw/react';

export default function Page() {
  return (
    <main>
      <ScrollAnimate props={{ opacity: [0, 1], transform: ['translateY(32px)', 'translateY(0)'] }} once>
        <h2>Fades up on scroll</h2>
      </ScrollAnimate>
      <ScrollDraw>
        <svg viewBox="0 0 400 24">
          <path d="M2 12 C 100 2, 300 22, 398 12" fill="none" stroke="currentColor" strokeWidth="2" />
        </svg>
      </ScrollDraw>
    </main>
  );
}

Fig. 1 — the line above is that <ScrollDraw>, rendered by this page, a Server Component.

Callbacks
A function cannot cross from a Server Component to a client one, so options such as onProgress or onComplete go in a 'use client' file of your own, as in the complete example below. On v2.16.0 and earlier, wrap every component that way.
02Copy the whole thing

A complete App Router example

The smallest project that shows the split: one client file holds every animated part, and the page stays a Server Component that fetches its data. Install, add these files, run next dev.

project5 lines
app/
  layout.tsx       Server Component, nothing to add
  page.tsx         Server Component: fetches, renders the animated parts
components/
  motion.tsx       'use client': the only client file

file · components/motion.tsx

The components work from the page itself; a client file is where your own wrappers go — named, reusable, and the only place callbacks can live. Each sets up on mount and cleans up on unmount.

components/motion.tsx33 lines
'use client';

import type { ReactNode } from 'react';
import { ScrollAnimate, ScrollDraw, ScrollText } from 'svg-scroll-draw/react';

/** Fades its children up the first time they scroll into view. */
export function FadeUp({ children }: { children: ReactNode }) {
  return (
    <ScrollAnimate props={{ opacity: [0, 1], transform: ['translateY(32px)', 'translateY(0)'] }} once>
      {children}
    </ScrollAnimate>
  );
}

/** A headline whose words rise in one after another. */
export function Headline({ text }: { text: string }) {
  return (
    <ScrollText as="h2" split="words" stagger={0.06} once>
      {text}
    </ScrollText>
  );
}

/** A rule that draws itself across the section as you scroll. */
export function DrawnRule() {
  return (
    <ScrollDraw>
      <svg viewBox="0 0 400 24" width="100%" aria-hidden="true">
        <path d="M2 12 C 100 2, 300 22, 398 12" fill="none" stroke="currentColor" strokeWidth="2" />
      </svg>
    </ScrollDraw>
  );
}

file · app/page.tsx

The page has no directive. It fetches on the server, renders the markup in full, and the animated parts hydrate on their own.

app/page.tsx26 lines
import { DrawnRule, FadeUp, Headline } from '@/components/motion';

type Feature = { id: string; title: string; body: string };

async function getFeatures(): Promise<Feature[]> {
  const res = await fetch('https://example.com/api/features', { next: { revalidate: 3600 } });
  return res.json();
}

export default async function Page() {
  const features = await getFeatures();
  return (
    <main>
      <Headline text="Scroll animations, rendered on the server." />
      <DrawnRule />
      {features.map((f) => (
        <FadeUp key={f.id}>
          <article>
            <h3>{f.title}</h3>
            <p>{f.body}</p>
          </article>
        </FadeUp>
      ))}
    </main>
  );
}
Pages Router
Pages Router components already run in the browser, so drop the 'use client' line and use components/motion.tsx from any page as it is.
034 patterns

The patterns

pattern 01 · components/AnimatedCards.tsx

Pattern 1 — Client Component (recommended)

Add 'use client' to any component that uses scroll APIs. Everything else can be a Server Component.

components/AnimatedCards.tsx25 lines
'use client';
import { useEffect } from 'react';
import { scrollReveal } from 'svg-scroll-draw/reveal';
import { scrollAnimate } from 'svg-scroll-draw';

type Card = { id: string; content: React.ReactNode };

export function AnimatedCards({ cards }: { cards: Card[] }) {
  useEffect(() => {
    const reveal = scrollReveal('.card', { preset: 'fadeUp', stagger: 0.1 });
    const hero   = scrollAnimate('#hero-title', {
      props: { opacity: [0, 1], transform: ['translateY(32px)', 'translateY(0)'] },
      easing: 'ease-out',
      once:   true,
    });
    return () => { reveal.destroy(); hero.destroy(); };
  }, []);

  return (
    <div>
      <h1 id="hero-title">Features</h1>
      {cards.map(c => <div key={c.id} className="card">{c.content}</div>)}
    </div>
  );
}

pattern 02 · components/LazyShowcase.tsx

Pattern 2 — Dynamic import (split a heavy section’s code)

Call next/dynamic from a client file. Without ssr: false the section is still rendered on the server, so its content is in the HTML; only its JavaScript comes in a chunk of its own. A Server Component cannot do this: Next refuses ssr: false there, and does not split a client component that a Server Component imports dynamically.

components/LazyShowcase.tsx16 lines
'use client';
import dynamic from 'next/dynamic';

// Rendered on the server as usual; its JavaScript loads as a separate chunk.
// No ssr: false — that would leave the section out of the server HTML.
const AnimatedShowcase = dynamic(() => import('./AnimatedShowcase'));

type Item = { id: string; title: string };

export function LazyShowcase({ items }: { items: Item[] }) {
  return <AnimatedShowcase items={items} />;
}

// app/page.tsx stays a Server Component, no directive:
//   const items = await getItems();
//   return <main><Hero /><LazyShowcase items={items} /></main>;

pattern 03 · components/PinnedSection.tsx

Pattern 3 — useEffect cleanup (avoid memory leaks)

components/PinnedSection.tsx28 lines
'use client';
import { useEffect, useRef } from 'react';
import { scrollPin }    from 'svg-scroll-draw/pin';
import { scrollReveal } from 'svg-scroll-draw/reveal';

export function ProductWalkthrough() {
  const imageRef = useRef<HTMLDivElement>(null);
  const trackRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const instances = [
      imageRef.current && scrollPin(imageRef.current, {
        pinDistance: '300vh',
        onEnter: () => console.log('pinned'),
      }),
      scrollReveal('.feature-text', { preset: 'fadeUp', stagger: 0.08 }),
    ].filter(Boolean);

    return () => instances.forEach(i => i && i.destroy());
  }, []); // run once on mount

  return (
    <div style={{ display: 'flex' }}>
      <div ref={imageRef}>...</div>
      <div className="feature-text">...</div>
    </div>
  );
}

pattern 04 · components/AnimatedPage.tsx

Pattern 4 — Route change cleanup

components/AnimatedPage.tsx22 lines
'use client';
import { useEffect, useRef } from 'react';
import { usePathname } from 'next/navigation';
import { scrollReveal } from 'svg-scroll-draw/reveal';

export function AnimatedPage({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const instanceRef = useRef<{ destroy: () => void } | null>(null);

  useEffect(() => {
    // Re-run on route change — pathname in deps array
    instanceRef.current = scrollReveal('.animate-in', {
      preset: 'fadeUp',
      stagger: 0.08,
      once: true,
    });

    return () => instanceRef.current?.destroy();
  }, [pathname]); // re-initialize on route change

  return <div>{children}</div>;
}
SSR safety
Every svg-scroll-draw engine starts with if (typeof window === 'undefined') return NOOP;. All server-side renders return a no-op instance — no hydration mismatch, no crashes.
Native CSS
When the browser supports animation-timeline: view(), svg-scroll-draw automatically uses it — zero JS scroll listeners, zero rAF calls, no JavaScript per frame. Where it is missing, the JS engine draws the same thing.
046 questions

Questions Next.js developers ask

Q1

Does svg-scroll-draw work with React Server Components?

Yes. From v2.16.1 the components in svg-scroll-draw/react carry 'use client', so a Server Component renders <ScrollDraw>, <ScrollAnimate> and the rest directly. Only options that are functions, such as onProgress, need a 'use client' file of your own. On the server every svg-scroll-draw call returns a no-op instance, so rendering never touches window or document.

Q2

Do I need next/dynamic with ssr: false?

No. The library renders on the server as it is, and ssr: false would take the section out of the server HTML; Next 16 also refuses ssr: false in a Server Component. To load a heavy animated section's JavaScript in a chunk of its own, call next/dynamic without ssr: false from a 'use client' file, as in pattern 2.

Q3

Will scroll animations cause hydration errors in Next.js?

No. The server renders your markup unchanged and the library only starts after the component mounts in the browser, so the HTML React hydrates matches what the server sent.

Q4

Does it work with the Pages Router?

Yes. Pages Router components already run in the browser, so no directive is needed: use the same components, or call the functions inside useEffect and return their destroy().

Q5

What happens on route changes?

Components from svg-scroll-draw/react clean up when they unmount, so pages that change need nothing extra. Selector-based calls made in a layout that persists across routes should re-run when the pathname changes, as in pattern 4.

Q6

Does it respect prefers-reduced-motion?

Yes. With reduced motion requested, drawings, reveals and text show in their final state instead of animating, and if the reader turns it on while the page is open, everything still moving finishes at once.

05measured

vs common alternatives

GSAP + ScrollTrigger45.3 KB
Framer Motion34.3 KB
svg-scroll-draw11.9 KB
fig. 2 — bundle, minified + gzipped, to one scale

GSAP + ScrollTrigger

Bundle
45.3 KB
SSR-safe
✓ client-side setup
TypeScript
✓

Free since 2025, mature, and does far more — at 3.81× the bytes.

Framer Motion

Bundle
34.3 KB
SSR-safe
✓
TypeScript
✓

React-only. Draws SVG via pathLength; no pin/snap.

svg-scroll-draw

Bundle
11.9 KB
SSR-safe
✓
TypeScript
✓

MIT. Works in React, Vue, Svelte and vanilla JS.

All sizes minified + gzipped at level 9, measured 2026-08-14 against gsap 3.15.0, framer-motion 13.1.0, svg-scroll-draw 2.31.0 — measured, not estimated.

06Drop it in

Built for Next.js

SSR
Safe by default
Router
App Router ready
Licence
MIT
Gzipped
11.9 KB
Types
TypeScript
Full docs →React guide →