DEV Community

Cover image for Adding Bootstrap to Next.js
Anurag Gharat
Anurag Gharat

Posted on

Adding Bootstrap to Next.js

In my opinion Bootstrap is still the OG of CSS frameworks. I love it because of it's simplicity and readymade components like Navbar, Cards, Modals and much more. Even with Tailwind, Chakra out there Bootstrap is still being used by a lot of Front end developers. Now Bootstrap has got even more powerful with Version 5.

Adding Bootstrap to your React or a basic HTML file was a simple straight forward task. You run the installation using npmor just add the CDN links in the HTML file. But the process is not that simple when in Next.js.

Bootstrap can be added to your Next.js application in two different ways. Choose the one which you prefer

  1. Using CDN
  2. Installing using NPM

Using CDN links:

Bootstrap 5 got rid of jquery so we only have to add the JS, Popper and CSS.

Go ahead and open up your Next.js project in your Favorite code editor.

Now Next.js does not have a index.html file unlike regular react application where you can add the Link and Script tags. So here we have to use _app.js and _document.js files. These are custom App and Document components which are used to initialize pages. _app.js is already created in your file, just create _document.js alongside the _app.js in the pages folder. Now paste the following code in _document.js file.

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

export default function Document() {
  return (
    <Html>
      <Head>
        <link
          href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
          crossOrigin="anonymous"
        />
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
Enter fullscreen mode Exit fullscreen mode

As you can see we have added the Bootstrap stylesheet here. <Head /> is the custom component by Next.js which compiles down to <head/> of our plain HTML. If you have other CSS styles or external icon links you can add them here as I have shown in below example.

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

export default function Document() {
  return (
    <Html>
      <Head>
        <link
          href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"
          rel="stylesheet"
          integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
          crossOrigin="anonymous"
        />
                {* Bootstrap Icons *}
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css"></link>
                    {* Google Fonts *}
                <link rel="preconnect" href="https://fonts.googleapis.com" />
        <link rel="preconnect" href="https://fonts.gstatic.com" crossOrigin="" />
        <link href="https://fonts.googleapis.com/css2?family=Mulish:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet"></link>
      </Head>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now you can test your application with some simple Bootstrap classes. It will work without any issues. But Bootstrap components like Modal, Navbar etc won’t work since they require JS and Popper and we haven’t imported them yet.

We can’t add the Bootstrap script which contains JS and Popper here in _document.js file because Next.js recommends us to add only stylesheets in custom Document component and all the external scripts should be added in custom App component only. Consider it as a best practice.

If you want to read more about the topic, check their documentation here.

stylesheets-in-head-component | Next.js

Change the _app.js code to this.

import Head from "next/head";
import Script from "next/script";
function MyApp({ Component, pageProps }) {
  return (
    <>
      <Head>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </Head>

      <Script
        src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW"
        crossOrigin="anonymous"
      />
      <Component {...pageProps} />
    </>
  );
}
export default MyApp;
Enter fullscreen mode Exit fullscreen mode

And all done, You can now start using Bootstrap in your project!

Installing Bootstrap using NPM

The second way to install bootstrap is using npm( Node Package Manager). Open terminal inside your project and install Bootstrap 5 using this command.

npm i bootstrap
Enter fullscreen mode Exit fullscreen mode

Once bootstrap is installed we have to import the Bootstrap CSS in _app.js. We import the CSS in App component because App component is rendered for every page. So you don’t have to import CSS in every page.

import 'bootstrap/dist/css/bootstrap.css';
Enter fullscreen mode Exit fullscreen mode

Now you can go ahead and use bootstrap’s CSS features but you won’t be able to use JS since we haven’t imported it yet!

Importing JS is not easy as CSS. If we directly import JS like CSS we will run into error which would say window and document is not defined. This is because window and document are client side objects, while Next.js renders HTML on Client side as well as server side. Hence to avoid such errors we will dynamically import JS using useEffect() hook. Look at the below code.

useEffect(()=>{
        import("bootstrap/dist/js/bootstrap");
},[])
Enter fullscreen mode Exit fullscreen mode

Add the following code in your _app.js file. Now you will only import JS when the page is loaded on the browser.

Use Effect hook only runs on Client side i.e in the Browser.

This was all about Adding Bootstrap to your Next.js application.
Thanks for reading! If you love such content make sure you follow me on twitter. I post regular content on Web Development and Programming.

Oldest comments (9)

Collapse
 
shahryarjb profile image
Shahryar Tavakkoli

Hi, What we should do in typescript?

useEffect(() => {
import('bootstrap/dist/js/bootstrap');
}, []);

has this error

Could not find a declaration file for module 'bootstrap/dist/js/bootstrap'. '/Users/shahryar/Documents/Programming/Docker/Front/mishka-cms-front/node_modules/bootstrap/dist/js/bootstrap.js' implicitly has an 'any' type.
If the 'bootstrap' package actually exposes this module, consider sending a pull request to amend 'github.com/DefinitelyTyped/Definit...

Collapse
 
leorsgomes profile image
Leonardo Dutra

hey @shahryarjb you need to import useEffect from react in your file

Collapse
 
shahryarjb profile image
Shahryar Tavakkoli • Edited

@leorsgomes @anuraggharat
Hi friends, I imported react before, but for fixing this problem based on this post that helped me to fix it

blog.logrocket.com/handling-bootst...

useEffect(() => {
require('bootstrap/dist/js/bootstrap.bundle.min.js');
}, []);

we need to use require instead of import

Collapse
 
anuraggharat profile image
Anurag Gharat

Hi Shahryar. Can you share your code so that we can understand your issue?

Collapse
 
ondiek profile image
Ondiek Elijah

Hi, I had the same issue and this is how I fixed it in TypeScript and Next.js 13

import '../styles/globals.css'
import 'bootstrap/dist/css/bootstrap.css'
import Script from 'next/script'


import type { AppProps } from 'next/app'

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
    <Component {...pageProps} />
    <Script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"/>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
alaasaedy profile image
Alaa A. Al Sa'edy

Anybody facing a problem with importing bootstrap JS file into next.js _app, you need to use require instead of import inside React.useEffect

Collapse
 
akashthakur05 profile image
Akash Singh

How to do if its class based component.

Collapse
 
krisztinaivan profile image
krisztinaivan

After npm i bootstrap, "const bootstrap = require("bootstrap");" worked for me at the place of usage.

Collapse
 
jorawarsinghnijjar profile image
Jorawar Singh Nijjar

Thanks