25

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.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
Andres Zapata
  • 1,710
  • 1
  • 16
  • 32

9 Answers9

15

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>

UPDATE

to set up this in nextjs13 refer to:

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

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • 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. – Jarmos May 29 '22 at 20:54
  • 1
    Method 3 works just fine. Using it right now in my project. Thanks @Yilmaz. – nonbeing Nov 03 '22 at 03:58
  • 4
    @Jarmos you have a typo. Not `@fontawesome`, it is `"@fortawesome` – Yilmaz Dec 03 '22 at 01:02
  • 1
    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. – Tushar Sharma Jul 08 '23 at 16:39
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/bootstrap@5.0.0-beta1/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

Hemant
  • 1,127
  • 1
  • 10
  • 18
  • 2
    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 https://cdnjs.com/libraries/font-awesome (*Do not use this link as src. Jump into the website and then get a link there) – harukaeru Jan 23 '21 at 18:33
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:

Vadorequest
  • 16,593
  • 24
  • 118
  • 215
  • 2
    This solution is the one you are looking for – eddyoc Dec 17 '20 at 04:45
  • 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: https://github.com/UnlyEd/next-right-now/blob/e6f6258207/src/pages/_app.tsx#L15 and https://github.com/UnlyEd/next-right-now/blob/e6f625820726d24967b4b14a5f32c93266fac3c9/src/utils/icons/font-awesome.ts – Vadorequest Dec 17 '20 at 22:56
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} />
)
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
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.

rimraf
  • 3,925
  • 3
  • 25
  • 55
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';
    
1

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;

KingJoeffrey
  • 303
  • 5
  • 16
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
Yash Marmat
  • 1,077
  • 10
  • 18
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..