GSAP ScrollTrigger + Lenis in Next.js App Router
By Md Mahafuj Alam · Updated
Install the packages
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
useGSAPhook, which handles cleanup for you. - lenis is the current package name. Older tutorials import
@studio-freight/lenis; that name is outdated, so replace it withlenisin 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.
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.
'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>
);
}scopelimits 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.dependenciesdefaults to an empty array, so the callback runs once. Pass values when the animation depends on props, and setrevertOnUpdate: trueif each re-run should start from a clean slate.gsap.matchMediacreates the scroll animation only when the visitor has no motion preference. Returningmm.revertfrom the callback removes its animations on unmount.contextSafeis for animations created later, in click handlers or timeouts. Those run outside the hook's callback, so wrap them incontextSafefrom 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.
'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>;
}instance.on('scroll', ScrollTrigger.update)makes ScrollTrigger re-check positions every time Lenis moves the page.onreturns an unsubscribe function, whichstopcalls.gsap.ticker.add(tick)drives Lenis from GSAP's own requestAnimationFrame loop. The ticker passes time in seconds andlenis.rafexpects milliseconds, hencetime * 1000. Because GSAP drives it, Lenis is created with its defaultautoRaf: false; turningautoRafon as well would advance it twice per frame.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:
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:
'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. SetpinSpacing: falseonly 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}`withinvalidateOnRefresh: trueis 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.
Anchor links with Lenis
A plain #section link makes the browser jump, which bypasses Lenis's easing. Route anchor clicks through lenis.scrollTo, which accepts a selector, an element or a pixel value plus options such as offset, duration and immediate.
'use client';
import type { MouseEvent, ReactNode } from 'react';
import { useLenis } from '@/components/SmoothScroll';
type Props = { href: `#${string}`; offset?: number; children: ReactNode };
export default function AnchorLink({ href, offset = -80, children }: Props) {
const lenis = useLenis();
const onClick = (event: MouseEvent<HTMLAnchorElement>) => {
if (!lenis) return; // no Lenis (reduced motion): let the browser jump
event.preventDefault();
lenis.scrollTo(href, { offset, duration: 1.2 });
history.pushState(null, '', href);
};
return (
<a href={href} onClick={onClick}>
{children}
</a>
);
}The negative offset leaves room for a fixed header. When Lenis is off, the link falls back to the native jump, so add scroll-margin-top to the target sections to keep the header from covering them. For pages with many in-page links, Lenis's anchors: true option handles every anchor link automatically.
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
respectReducedMotionoption, 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)'), asPinnedIntrodoes. Content must still be readable without the animation, so animate from visible states withfromtweens 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 symptom | Cause | Fix |
|---|---|---|
ReferenceError: window is not defined | window, document or matchMedia read at module scope or during render, which also runs on the server | Move browser access into useGSAP or useEffect |
| Hydration mismatch | Render output depends on a browser-only value such as matchMedia or innerWidth | Render the same markup on both sides; branch inside effects |
| Animations play twice or pins stack in development | Strict Mode mounts components twice and the first set was never reverted | Create animations inside useGSAP, or revert a gsap.context in the effect cleanup |
| Pinned section jitters with Lenis | ScrollTrigger and Lenis update on different frames | lenis.on('scroll', ScrollTrigger.update) and drive lenis.raf from gsap.ticker |
| scrollTrigger options are ignored | ScrollTrigger was never registered | Import GSAP from lib/gsap.ts, which registers it |
| Pin starts too early after images load | Positions were measured before the layout settled | Reserve 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.
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.
Keep reading
- Start here · the full workflowHow to Build a 3D Motion Website with ClaudeBuild a 3D motion website with Claude: plan the story, generate keyframes and video, cut frames with ffmpeg, then build it in Next.js with GSAP and Lenis.Read the guide
- Guide · BuildCanvas image sequence scroll animation in Next.jsBuild an Apple-style canvas image sequence scroll animation in Next.js: frame preloading, cover-fit drawing, DPR sizing, GSAP scrub, portrait frames.Read the guide
- Guide · BuildAccessible scroll animation with prefers-reduced-motionHow to honour prefers-reduced-motion in a scroll story: detect it in CSS and JS, turn off Lenis and scrub, keep focus visible and meet WCAG 2.2.Read the guide