How to add Font Awesome to Next.js project
Asked Answered
F

10

30

I'm trying to add font-awesome to my Next.js project using webpack. I've tried following various instructions I've found on the web (using file-loader, url-loader), but nothing has worked for me. I gave up loading font-awesome with webpack for the moment, but I want to know how I can accomplish this. Currently, I have a .scss file that I use to load font-awesome.

Its contents:

$fa-font-path: "static/fonts";
@import "~font-awesome/scss/font-awesome.scss";

And I'm manually moving the fonts from node_modules/font-awesome/fonts to static/fonts. This works perfectly, But I wanted to know if there's a webpack 2 way to do it in 2017.

Feigned answered 26/6, 2017 at 1:49 Comment(0)
L
23

UPDATE

to set up this in nextjs13 refer to:

How to add Font Awesome to Next.js 13 project error Module not found

There are 3 ways:

1: By Adding a FontAwesome Script to the Head Component

Create Head component, add script and render this component either in Header component or in Layout file where you use it in every page.

<Head>
  <script
    // you might need to get a newer version
    src="https://kit.fontawesome.com/fbadad80a0.js"
    crossOrigin="anonymous"
  ></script>
</Head>

2: Adding a link to the CDN within the _document.js.

It's possible to overwrite the root html file in Next.js by creating a _document.js under the pages folder. You could also add some other CDN as well. But, the easiest way is:

<Html>
  <Head>
    <link
      rel="stylesheet"
      type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
      />
    <link
      rel="stylesheet"
      type="text/css"
      href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
    />
  </Head>
  <body>
    <Main />
    <NextScript />
  </body>
</Html>

3: Install All the Necessary npm Packages for FontAwesome

npm install --save @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/react-fontawesome

And then at the top of the _app.js file add these lines:

 // import Font Awesome CSS
import "@fortawesome/fontawesome-svg-core/styles.css";
import { config } from "@fortawesome/fontawesome-svg-core";
config.autoAddCss = false;

Thereafter, you can import & use the rest of the FontAwesome icons as React Components like so:

import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faCheck, faTrash } from "@fortawesome/free-solid-svg-icons";

<FontAwesomeIcon icon={faCheck} className="fas fa-check" style={{ color: "red" }}
></FontAwesomeIcon>
Luann answered 16/4, 2022 at 4:20 Comment(4)
A heads up for everyone reading this answer, the 3rd method throws a "@fontawesome/fontawesome-svg-core/styles.css module not found" error. Haven't verified the other methods though.Facula
Method 3 works just fine. Using it right now in my project. Thanks @Yilmaz.Symposiac
@Facula you have a typo. Not @fontawesome, it is "@fortawesomeLuann
Thank you! But please move the newer update to the top. I completed everything just to see that it's not for next js 13.Papyrus
M
12

None of the solutions in this post are regarding how to use font-awesome via cdn, So, i am going to do just that.

There are multiple ways of doing it, but i normally use either _app.js or _document.js for such tasks.

Here is how it did it via _document.js

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

class MyDocument extends Document {
    render() {
        return (
            <Html>
                <Head>
                    <link
                        href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
                        rel="stylesheet"
                        integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1"
                        crossOrigin="anonymous"
                    />
                    <script src="https://kit.fontawesome.com/e20sdfsd9.js" crossOrigin="anonymous"></script>
                </Head>
                <body>
                    <Main />
                    <NextScript />
                </body>
            </Html>
        );
    }
}

export default MyDocument;

Here i simply added a link to css cdn of fontawesome in the DOM of next app which will be added in the pages rendered in browser.

to know more about _document.js please refer here

A similart approach can be followed via _app.js which i am not using right now, but in case anybody needs it, fell free to drop a comment and i will do it for you.

Here is a brief intro to custom app or _app.js

Metaplasm answered 26/12, 2020 at 22:12 Comment(1)
Thanks. This was really helpful. However, this src link for Fontawesome seems not reachable anymore. It worked well after I changed the link into a link shown on cdnjs.com/libraries/font-awesome (*Do not use this link as src. Jump into the website and then get a link there)Broddie
L
11

For anyone who'd like to see a real example with Next 9, check out https://github.com/UnlyEd/next-right-now

Interesting parts are:

Disclaimer: I'm a contributor to the project


Config: pages/_app.tsx

import { config, library } from '@fortawesome/fontawesome-svg-core';
import '@fortawesome/fontawesome-svg-core/styles.css';
import { faGithub } from '@fortawesome/free-brands-svg-icons';
import { faAngleDown } from '@fortawesome/pro-solid-svg-icons';

// See https://github.com/FortAwesome/react-fontawesome#integrating-with-other-tools-and-frameworks
config.autoAddCss = false; // Tell Font Awesome to skip adding the CSS automatically since it's being imported above
library.add(
  faGithub, faAngleDown
);

You can use solid/light/etc by importing the icon from the right repository

Usage: components/Nav.tsx

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';

<FontAwesomeIcon icon={['fab', 'github']} />

Edit Next.js 10:

While the above still works, what I recommend now for Next.js 10 and higher is to split your Font-Awesome related config into a different file, and import that file in _app.tsx. This makes the code more maintainable, that's all.

Something like:

Librettist answered 3/3, 2020 at 17:40 Comment(2)
This solution is the one you are looking forPhreno
Note that the current answer is still compatible with Next.js 10, but I found a more maintainable way that is only compatible with Next.js 10+, which is basically to move all font-awesome related stuff to a different file, and import that file in _app.tsx. Like it's done there: github.com/UnlyEd/next-right-now/blob/e6f6258207/src/pages/… and github.com/UnlyEd/next-right-now/blob/…Librettist
T
5

See here for the official documentation of Integrating with other tools and frameworks.

You'll be able to do the following:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { config, library } from '@fortawesome/fontawesome-svg-core';
import { fas } from '@fortawesome/free-solid-svg-icons';
import { fab } from '@fortawesome/free-brands-svg-icons';

config.autoAddCss = false;
library.add(fas, fab);

return ( 
  <FontAwesomeIcon icon={['fas', 'hat-wizard']} />
  <FontAwesomeIcon icon={['fab', 'github']} />
)

or

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAdobe } from '@fortawesome/free-brands-svg-icons/faAdobe';

return ( 
   <FontAwesomeIcon icon={faAdobe} />
)
Trefler answered 23/4, 2020 at 10:9 Comment(0)
O
4

There are a few ways to do this. The first would be to create a head component via next/head and import there - see here:

Another way is to create a HOC to wrap your pages with and import there with a simple import 'font-awesome/css/font-awesome.min.css'

Or, you could just import it into one of your page's with the same kind of import. (I believe this will scope it to that particular page however. Double check me on that)

Hope this helps.

Obligation answered 30/7, 2017 at 16:38 Comment(0)
I
3
  1. yarn add @fortawesome/fontawesome-free

  2. in _app.js

    import '@fortawesome/fontawesome-free/js/fontawesome';
    import '@fortawesome/fontawesome-free/js/solid';
    import '@fortawesome/fontawesome-free/js/regular';
    import '@fortawesome/fontawesome-free/js/brands';
    
Ivanaivanah answered 8/9, 2020 at 6:39 Comment(0)
W
2

I'd like to post an answer using React 18 Next.js 13 and bootstrap 5 with fontAwesome.

There is an error that pops up for me

Error: Hydration failed because the initial UI does not match what was rendered on the server.

In the console I get an error something like this

 Expected server HTML to contain a matching <li> in <div>

I fixed this by doing the useEffect trick everybody does with Next.js to make the fontAwesomeIcon render only when mounted

Here is an example component

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Row, Col } from 'reactstrap';

const AboutUsProcess = ({ icon, iconText, color, title, description, image, lottie, inverse, children }) => {


  const [mounted, setMounted] = useState(false);
  useEffect(() => {
      setMounted(true) // must be true to render FontAwesomeIcon
  }, [])
  
  
  return  (
    <Row className="flex-center">
      <Col md lg={5} xl={4} className={classNames('pl-lg-6', { 'order-md-2': inverse })}>
      </Col>
      <Col md lg={5} xl={4} className="mt-4 mt-md-0">
        <h5 className={`text-${color}`}>
          { mounted && (
            <FontAwesomeIcon icon={icon} className="mr-2" />
            )}
            {iconText}
        </h5>
        <h3>{title}</h3>
        <p>{description}</p>
        {children}
      </Col>
    </Row>
  );
};


export default AboutUsProcess;

Wittgenstein answered 4/1, 2023 at 9:44 Comment(0)
S
0

Try this

const Hello = () => {

    return (
        <div>
            <Head>
                <title>New Title</title>
                <meta name="description" content="some description here" />
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />
            </Head>

            <h1>Hello World <i class="far fa-laugh-beam"></i></h1>
        </div>
    )
}

export default Hello

Do install the below packages before proceeding

npm i --save @fortawesome/fontawesome-svg-core
npm install --save @fortawesome/free-solid-svg-icons
npm install --save @fortawesome/react-fontawesome
Swearingen answered 11/1, 2022 at 8:39 Comment(0)
L
0

In Next13 with Turbo Feature you got to add the font-awesome files into a fonts folder in the "app" folder - then use an absolute path.

Dirty :) hope this will be fixed soon..

Lierne answered 18/3, 2023 at 23:17 Comment(0)
A
0

I inserted the link in the layout.tsx in the new App Router

import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <head>
      <script src="https://kit.fontawesome.com/e822fa5c46.js" crossOrigin="anonymous"></script>
      <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@24,400,1,0" />
      </head>
      <body className={inter.className}>{children}</body>
    </html>
  );
}
Antipersonnel answered 24/5, 2024 at 22:3 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.