NextJS: How to add bootstrap via CDN

Viewed 6887

I am new to nextJS and I am having a bad time including bootstrap in the app via CDN. Where to add the links is best practice in the app?

3 Answers

To override the default Document, create the file ./pages/_document.js and extend the Document class as shown below and put CDN path between HEAD tag.

Refer docs for more info

import Document, { Html, Head, Main, NextScript } from "next/document";

class MyDocument extends Document {
  static async getInitialProps(ctx) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html>
        <Head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous" />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

you just need to make it a closed tag

Include Head from ./next and use declare any links to be included there.

     <Head>
         <script src="https://...."/>      
     </Head>

It is preferable to add third-party scripts in the Script tag for better performance, as mentioned in the docs.

The Next.js Script component, next/script, is an extension of the HTML

element. It enables developers to set the loading priority of third-party scripts anywhere in their application without needing to append directly to next/head, saving developer time while improving loading performance.
Related