Adding Bootstrap to Next.js
Tags: javascript, bootstrap, webdev, beginners
Published: 2022-03-23 18:41:41

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 `npm `or 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. 


```jsx
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>
  );
}
```

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. 

```jsx
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>
  );
}
```

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](https://nextjs.org/docs/messages/no-stylesheets-in-head-component)

Change the `_app.js` code to this.

```jsx
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;
```

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.

```bash
npm i bootstrap
```

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.

```bash
import 'bootstrap/dist/css/bootstrap.css';
```

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. 

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

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](https://twitter.com/anurag_gharat). I post regular content on Web Development and Programming.