In Next.js, adding a favicon when deploying your application in static mode is a straightforward task. You can achieve this by following these steps:
-
Prepare Favicon Files: First, prepare one or more favicon files in formats such as
.ico,.png, or.svg. Whilefavicon.icois the most common format due to its compatibility with all browsers, many modern browsers now support other formats like PNG and SVG. -
Place Favicon in public Directory: In the root directory of your Next.js project, there is a
publicdirectory. Place your favicon file in this directory. Next.js automatically maps resources in thepublicdirectory to the root URL of your application. -
Update the
<Head>Component: In your page components or in the_app.jsfile, use Next.js's built-in<Head>component to add link tags for the favicon. Typically, this is set globally inpages/_app.js, or it can be set in specific pages atpages/your-page.js.
Here is an example of adding a favicon in pages/_app.js:
jsximport Head from 'next/head'; function MyApp({ Component, pageProps }) { return ( <> <Head> {/* Add favicon */} <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="icon" href="/favicon.ico" type="image/x-icon" /> {/* Support other sizes */} <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" /> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png" /> <link rel="manifest" href="/site.webmanifest" /> {/* ...other elements if needed (e.g., title, description) ... */} </Head> <Component {...pageProps} /> </> ); } export default MyApp;
In the above example, we add several <link> tags to define icons for different contexts. Modern browsers will select the appropriate icon based on the context.
- Build and Deploy: After completing the above steps, when you build and deploy your Next.js application, the favicon will be included automatically and displayed in the browser tab.
Note that if you make these changes in the development environment, you may need to restart the development server to see the new favicon.