It's really easy to add a favicon to your NextJS website. Unfortunately, the official documentation from Vercel is only relevant for projects using the
/app
structure. I'll show you how to add a favicon to a NextJS project using the/pages
structure.
Before you add a favicon to your NextJS site, you need to create one!
I've used favicon.io before and it works well, otherwise you can just rename a small favicon.png
file to favicon.ico
.
Once you've created your favicon file, you need to add it to your NextJS project.
Technically you can place the file anywhere in the /public/assets
directory. You could place it in a subdirectory like /public/assets/favicons/favicon.ico
if you wanted.
However, I think it makes the most sense just to place it in /public/assets/favicon.ico
—
After copying your favicon into your NextJS project, we should have something like this.
The final step is to add the favicon into our websites <head>
. This will actually embed the favicon into our NextJS website.
All you need to to is import Head
from next/head
, and add the tag —
import Head from 'next/head'
<Head>
... the rest of your HTML head ...
<link rel="icon" href="/favicon.ico" /> // <- HERE
</Head>
You can add this code to any of your components as long as they get imported into all your pages (a Nav
element, for example), or even directly into one of your /pages
(/pages/index.jsx
).
My preferred approach is to create a <HeadMetaTags />
component, and import that into each page —
import Head from 'next/head'
export function HeadMetaTags({ metadata }) {
return (
<Head>
... other head tags ...
<link rel="shortcut icon" href="/favicon.ico" />
</Head>
)
}
Then in each page, we just add a <HeadMetaTags />
component —
import Head from 'next/head'
import { HeadMetaTags } from '@/components/HeadMetaTags'
export default function Home() {
const metadata = {
... metadata for HeadMetaTags ...
}
return (
<>
<HeadMetaTags metadata={metadata} />
... the rest of the app...
</>
)
}
This way, we can make sure our favicon is added to each of our NextJS pages.
It also let's us easily add other meta tags unrelated to the favicon, and adjust the meta tags for each page.