How to add a favicon to a Next.js static site?
The accepted answer is nice, but might be worth pointing out that you don't have to modify _document.js
for adding a favicon (nor for adding any tags to head
).
I found out for myself that placing favicon in _app.js
makes more sense. This file is most likely to exist already for setting up a layout for the pages or something like this. And you can add Head
tag literally anywhere (see the docs)
So I ended up with _app.js
class MyApp extends App {
render() {
const { Component, pageProps } = this.props;
return (
<Layout>
<Head>
<link rel="shortcut icon" href="/favicon.ico" />
</Head>
<Component {...pageProps} />
</Layout>
);
}
}
As of June 2020, you don't have to add/edit the document.js
or _head.js
files. All you need do to is place the favicon.ico
file inside the public directory and that's it.
- Create a
/static
folder in project root. This will be added to the static export folder. - Add favicon file in
/static
folder. - Add
_document.js
to/pages/
folder according to documentation (nextjs.org) or documentation (github.com). - Add
<link rel="shortcut icon" href="/static/favicon.ico" />
to head. npm run build && npm run export
P.S. Thanks to the previous answer that was deleted. It works!
Edit: Another way is to do this is to import Head into your root layout and add the link there. Anything added to Head gets inserted into the document head tag.
import Head from 'next/head';
const Page = (props) => (
<div>
<Head>
<link rel="shortcut icon" href="/static/favicon.ico" />
</Head>
// Other layout/components
</div>
);
export default Page;
Update :
The static directory has been deprecated in favor of the public directory. Doc
So, the code would now look like
import Head from 'next/head';
const Page = (props) => (
<div>
<Head>
<link rel="shortcut icon" href="/favicon.ico" />
</Head>
// Other layout/components
</div>
);
Simply add your favicon.ico in public folder, Next js will automatically take that favicon for all pages.
No need to add any favicon link to any pages or in tag no need to add link for favicon.
https://github.com/zeit/next.js/blob/master/errors/static-dir-deprecated.md