Back to Next Js

Missing data-scroll-behavior Attribute for Smooth Scroll

errors/missing-data-scroll-behavior.mdx

16.2.82.1 KB
Original Source

Why This Warning Occurred

Your application has smooth scrolling enabled via CSS (scroll-behavior: smooth), but you haven't added the data-scroll-behavior="smooth" attribute to your <html> element.

Next.js automatically attempts to detect the smooth scrolling configuration to ensure that navigating back/forward through the router doesn't also trigger the smooth scrolling behavior, as this is often not desired.

In a future version of Next.js, this behavior will no longer be automatically detected, and you will need to add the data-scroll-behavior attribute to your <html> element to opt-in to having Next.js disable smooth scrolling during route transitions.

Possible Ways to Fix It

Add data-scroll-behavior="smooth" to your <html> element to prepare for the upcoming optimization:

html
export default function RootLayout({ children, }: { children: React.ReactNode })
{ return (
<html lang="en" data-scroll-behavior="smooth">
  <body>
    {children}
  </body>
</html>
) }

Or if you're using the Pages Router:

html
import { Html, Head, Main, NextScript } from 'next/document' export default
function Document() { return (
<html lang="en" data-scroll-behavior="smooth">
  <head />
  <body>
    <main />
    <NextScript />
  </body>
</html>
) }

Why This Optimization Matters

Without the data attribute, Next.js must modify the scroll-behavior style on the <html> element on every navigation to ensure smooth scrolling isn't triggered. This can cause unnecessary style recalculation and impact performance.

With the data attribute, Next.js can instantly detect smooth scrolling configuration without triggering style recalculation, resulting in faster navigation and making this behavior opt-in.

Enabling the Optimization Early

You can enable this optimization early by adding the experimental flag to your next.config.js:

js
/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    optimizeRouterScrolling: true,
  },
}

module.exports = nextConfig