Guide · Build

GSAP ScrollTrigger + Lenis in Next.js App Router

By Md Mahafuj Alam · Updated

Install gsap, @gsap/react and lenis, register ScrollTrigger and useGSAP once in a shared module, and write every animation inside useGSAP in a client component so it is scoped and reverted on unmount. Run Lenis from a client provider in the root layout, drive it from the GSAP ticker and call ScrollTrigger.update on every Lenis scroll event so both share one clock. Skip Lenis for visitors who prefer reduced motion.

Install the packages

Terminalbash
npm install gsap @gsap/react lenis
  • gsap contains the core and every plugin, ScrollTrigger included. GSAP states on its pricing page that it is now 100% free for all users, and the installation docs confirm the plugins are freely available on npm. There is no private registry or token to configure.
  • @gsap/react provides the useGSAP hook, which handles cleanup for you.
  • lenis is the current package name. Older tutorials import @studio-freight/lenis; that name is outdated, so replace it with lenis in any code you copy.

Every file that imports GSAP or Lenis runs in the browser, so it must be a Client Component or be imported only by one. Layouts and pages stay Server Components and render the client pieces as children.

Register the plugins once

gsap.registerPlugin tells the core about a plugin and stops bundlers from tree-shaking it away. Do it in one module and import GSAP from there everywhere else. That gives you one registration and one import path to change.

lib/gsap.tsts
import { gsap } from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useGSAP } from '@gsap/react';

// Runs once, the first time any client component imports this file.
gsap.registerPlugin(ScrollTrigger, useGSAP);

export { gsap, ScrollTrigger, useGSAP };

The file has no 'use client' directive because it is not a component. It becomes client code by being imported from client components. Registering useGSAP as a plugin is what the GSAP React docs recommend, to avoid problems with mismatched React versions.

Write animations inside useGSAP

useGSAP is a drop-in replacement for useEffect or useLayoutEffect. Every tween, timeline and ScrollTrigger created while its callback runs is collected in a GSAP context and reverted when the component unmounts. On the server it falls back to useEffect, so it is safe in SSR.

components/PinnedIntro.tsxtsx
'use client';

import { useRef } from 'react';
import { gsap, useGSAP } from '@/lib/gsap';

export default function PinnedIntro() {
  const container = useRef<HTMLElement>(null);

  useGSAP(
    () => {
      const mm = gsap.matchMedia();

      mm.add('(prefers-reduced-motion: no-preference)', () => {
        gsap
          .timeline({
            scrollTrigger: {
              trigger: container.current,
              start: 'top top',
              end: '+=1200',
              pin: true,
              scrub: 1,
            },
          })
          .from('.intro-line', { yPercent: 100, autoAlpha: 0, stagger: 0.2 })
          .to('.intro-panel', { scale: 0.85, borderRadius: 32 }, '<');
      });

      return () => mm.revert();
    },
    { scope: container },
  );

  return (
    <section ref={container} className="intro">
      <div className="intro-panel">
        <h2 className="intro-line">Every frame</h2>
        <h2 className="intro-line">follows the scroll</h2>
      </div>
    </section>
  );
}
  • scope limits selector strings such as '.intro-line' to descendants of the ref. Two copies of the component on one page never animate each other's elements.
  • dependencies defaults to an empty array, so the callback runs once. Pass values when the animation depends on props, and set revertOnUpdate: true if each re-run should start from a clean slate.
  • gsap.matchMedia creates the scroll animation only when the visitor has no motion preference. Returning mm.revert from the callback removes its animations on unmount.
  • contextSafe is for animations created later, in click handlers or timeouts. Those run outside the hook's callback, so wrap them in contextSafe from the hook's return value or they will not be reverted.

Sync Lenis with ScrollTrigger in a provider

Lenis smooths wheel scrolling by easing the real scroll position towards the target on every animation frame. ScrollTrigger must read that position on the same frame, or pinned elements lag a frame behind and jitter. The Lenis README gives three lines for this, and the provider below wraps them in React state and cleanup.

components/SmoothScroll.tsxtsx
'use client';

import { createContext, useContext, useEffect, useState, type ReactNode } from 'react';
import { usePathname } from 'next/navigation';
import Lenis from 'lenis';
import { gsap, ScrollTrigger } from '@/lib/gsap';

const LenisContext = createContext<Lenis | null>(null);

/** The page's Lenis instance, or null when smooth scrolling is off. */
export const useLenis = () => useContext(LenisContext);

export default function SmoothScroll({ children }: { children: ReactNode }) {
  const [lenis, setLenis] = useState<Lenis | null>(null);
  const pathname = usePathname();

  useEffect(() => {
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)');
    let instance: Lenis | null = null;
    let unsubscribe: (() => void) | null = null;
    const tick = (time: number) => instance?.raf(time * 1000); // seconds -> ms

    const stop = () => {
      gsap.ticker.remove(tick);
      unsubscribe?.();
      instance?.destroy();
      instance = null;
      setLenis(null);
    };

    const start = () => {
      instance = new Lenis({ lerp: 0.1, smoothWheel: true });
      unsubscribe = instance.on('scroll', ScrollTrigger.update);
      gsap.ticker.add(tick);
      gsap.ticker.lagSmoothing(0);
      setLenis(instance);
    };

    const sync = () => {
      stop();
      if (!reduce.matches) start();
      ScrollTrigger.refresh();
    };

    sync();
    reduce.addEventListener('change', sync);
    return () => {
      reduce.removeEventListener('change', sync);
      stop();
    };
  }, []);

  // New route: the page height changed, so re-measure Lenis and every trigger.
  useEffect(() => {
    lenis?.resize();
    ScrollTrigger.refresh();
  }, [pathname, lenis]);

  return <LenisContext.Provider value={lenis}>{children}</LenisContext.Provider>;
}
  1. instance.on('scroll', ScrollTrigger.update) makes ScrollTrigger re-check positions every time Lenis moves the page. on returns an unsubscribe function, which stop calls.
  2. gsap.ticker.add(tick) drives Lenis from GSAP's own requestAnimationFrame loop. The ticker passes time in seconds and lenis.raf expects milliseconds, hence time * 1000. Because GSAP drives it, Lenis is created with its default autoRaf: false; turning autoRaf on as well would advance it twice per frame.
  3. gsap.ticker.lagSmoothing(0) turns off GSAP's lag compensation, so after a slow frame the animation does not jump to make up time while Lenis catches up.

lerp: 0.1 is the Lenis default: at 60 fps the scroll covers roughly 10% of the remaining distance each frame. Lower values feel heavier. Add the provider and the Lenis stylesheet to the root layout:

app/layout.tsxtsx
import type { ReactNode } from 'react';
import 'lenis/dist/lenis.css';
import SmoothScroll from '@/components/SmoothScroll';

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en">
      <body>
        <SmoothScroll>{children}</SmoothScroll>
      </body>
    </html>
  );
}

The layout stays a Server Component. The provider only wraps children, which follows the Next.js advice to render providers as deep in the tree as possible. lenis/react also ships a ReactLenis component with a root prop; the hand-written provider is used here because it can switch Lenis off at runtime for reduced motion without remounting the page.

Pinning gotchas

ScrollTrigger measures start and end positions once and caches them. Anything that changes the page height afterwards, such as images, web fonts or expanding content, leaves those positions wrong. That is the cause of most pins that start too early or end in the wrong place.

Refresh after images and fonts load

The best fix is to reserve space: give images explicit width and height, which next/image requires anyway. For content you cannot size up front, re-measure once it has loaded:

components/RefreshOnImages.tsxtsx
'use client';

import { useRef, type ReactNode } from 'react';
import { ScrollTrigger, useGSAP } from '@/lib/gsap';

/** Re-measures every trigger once the images and fonts inside have loaded. */
export default function RefreshOnImages({ children }: { children: ReactNode }) {
  const ref = useRef<HTMLDivElement>(null);

  useGSAP(
    () => {
      // Lazy images off screen never load, so only wait for eager ones.
      const images = Array.from(ref.current?.querySelectorAll('img') ?? []).filter(
        (img) => img.loading !== 'lazy',
      );
      const ready = images.map((img) => img.decode().catch(() => undefined));
      let cancelled = false;
      Promise.all([...ready, document.fonts.ready]).then(() => {
        if (!cancelled) ScrollTrigger.refresh();
      });
      return () => {
        cancelled = true;
      };
    },
    { scope: ref },
  );

  return <div ref={ref}>{children}</div>;
}

After a click that expands content, call ScrollTrigger.refresh(true). The true argument makes it a "safe" refresh: if the page is in the middle of scrolling, ScrollTrigger waits until the scroll has finished before it measures, so an in-progress momentum scroll is not interrupted.

Rules that prevent most pin bugs

  • Do not animate the pinned element itself. Pin a wrapper and animate its children, as the ScrollTrigger docs advise. Pinning already controls the element's position.
  • Keep the default pinSpacing. It pads the page so the content below waits until the pin releases. Set pinSpacing: false only when you want the next section to slide over the pinned one.
  • Create triggers in page order. A pin adds height that later triggers depend on. If components mount out of order, give earlier ones a higher refreshPriority.
  • Use functions for size-dependent values. end: () => `+=${window.innerHeight * 2}` with invalidateOnRefresh: true is recalculated on resize; a number is not.

Cleanup on route changes

In the App Router the root layout persists across navigations, so Lenis is created once and survives. Pages do not. When a page unmounts, useGSAP reverts its tweens and kills its ScrollTriggers, including pin spacers. Triggers created anywhere else, in a plain useEffect or at module scope, stay alive, keep listening and point at removed DOM nodes. Keep all GSAP code inside useGSAP, or call kill() on those triggers yourself.

The second effect in SmoothScroll handles the new page. Child effects run before parent effects, so by the time it fires the new page's triggers exist. lenis.resize() re-reads the page height and ScrollTrigger.refresh() recalculates every start and end. When debugging, a quick ScrollTrigger.getAll().length in the console after a few navigations shows whether triggers are leaking.

Reduced motion

Smooth scrolling changes how the page responds to input, and long scrubbed sequences are exactly what prefers-reduced-motion: reduce asks you to avoid. Handle it on two levels.

  • Scrolling. The provider never creates Lenis for these visitors and listens for the setting changing mid-session. Current Lenis versions also have a respectReducedMotion option, on by default, that disables smoothing; not creating the instance at all is simpler and removes the ticker work too.
  • Animations. Wrap scroll-linked timelines in gsap.matchMedia('(prefers-reduced-motion: no-preference)'), as PinnedIntro does. Content must still be readable without the animation, so animate from visible states with from tweens rather than hiding content in CSS.

The Orbitly template is built with Next.js, TypeScript, three.js, GSAP ScrollTrigger and Lenis, and respects reduced motion. Its 691-frame canvas scrub is the pattern explained in canvas image sequence scroll animation in Next.js.

Common errors and fixes

Error or symptomCauseFix
ReferenceError: window is not definedwindow, document or matchMedia read at module scope or during render, which also runs on the serverMove browser access into useGSAP or useEffect
Hydration mismatchRender output depends on a browser-only value such as matchMedia or innerWidthRender the same markup on both sides; branch inside effects
Animations play twice or pins stack in developmentStrict Mode mounts components twice and the first set was never revertedCreate animations inside useGSAP, or revert a gsap.context in the effect cleanup
Pinned section jitters with LenisScrollTrigger and Lenis update on different frameslenis.on('scroll', ScrollTrigger.update) and drive lenis.raf from gsap.ticker
scrollTrigger options are ignoredScrollTrigger was never registeredImport GSAP from lib/gsap.ts, which registers it
Pin starts too early after images loadPositions were measured before the layout settledReserve image space, or call ScrollTrigger.refresh() after load

The setup above is the scroll layer of a larger build. The 3D website with Claude guide covers the whole site, and the template catalogue has finished scroll stories to start from. API details are in the GSAP React guide, the ScrollTrigger docs and the Lenis README.

FAQ

Questions, answered.

The questions people ask most about this topic.

01Is GSAP free to use with ScrollTrigger?

Yes. GSAP states on gsap.com that it is now 100% free for all users, thanks to Webflow, and its plugins, ScrollTrigger included, are installed from the public gsap package on npm.

02What is the difference between lenis and @studio-freight/lenis?

They are the same library under its old and new package names. Install lenis and import Lenis from it; the React bindings live at lenis/react and the stylesheet at lenis/dist/lenis.css.

03Where should Lenis go in a Next.js App Router project?

In a client provider component rendered by the root layout around children. The layout persists between routes, so one Lenis instance serves the whole site, while each page creates and cleans up its own ScrollTriggers.

04Why do I need gsap.ticker.lagSmoothing(0) with Lenis?

Lag smoothing makes GSAP adjust its clock after a long frame. With Lenis driven from the GSAP ticker, that adjustment can make scroll-linked animation jump. Setting it to 0 turns the adjustment off, as the Lenis README recommends.

05Should smooth scrolling be disabled for reduced motion?

Yes. Visitors who set prefers-reduced-motion should get native scrolling and no scroll-scrubbed animation. Do not create Lenis for them, and wrap scroll-linked timelines in gsap.matchMedia so they are never built.