Next JS

Stylesheets and Script tag In Head Component of next js

Why This Error Occurred?

Do not add stylesheets using next/head (see <link rel="stylesheet"> tag with href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css"). Use Document instead. 
See more info here: https://nextjs.org/docs/messages/no-stylesheets-in-head-component
Do not add <script> tags using next/head

Next JS don’t recommend this pattern because it will potentially break when used with Suspense and/or streaming. In these contexts, next/head tags aren’t:

  • guaranteed to be included in the initial SSR response, so loading could be delayed until client-side rendering, regressing performance.
  • loaded in any particular order. The order that the app’s Suspense boundaries resolve will determine the loading order of your stylesheets.

So how we can add external CSS and Javascript in Next JS?

Add the stylesheet in a custom Document component.

// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html>
      <Head>
        <link rel="stylesheet" href="..." />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

14 − 3 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top