DEV Community

Cover image for How to Dynamically Change Favicon Icon in Next.js 14
Sabbir Sobhani
Sabbir Sobhani

Posted on • Updated on

How to Dynamically Change Favicon Icon in Next.js 14

If you want to change favicon based on color modes(dark or light mode) in Next.js 14. And, automatically switch between the black and white favicon versions according to the user's color scheme preference. This article is for you!

Though there were no direct solution in the docs about icons but got a hint so this is how we can achieve it:

I have made a video tutorial if you want to see how it works and how to implement practically! or if you want to stick on the article just read on instead.



// app/layout.tsx
export const metadata: Metadata = {
  title: 'Website Title',
  description: 'Website description',
  icons: {
    icon: [
      {
        media: '(prefers-color-scheme: light)',
        url: '/images/icon-light.png',
        href: '/images/icon-light.png',
      },
      {
        media: '(prefers-color-scheme: dark)',
        url: '/images/icon.png',
        href: '/images/icon-dark.png',
      },
    ],
  },
};


Enter fullscreen mode Exit fullscreen mode

Need to delete app/icon.png or any files that by default map the favicon in order to active the Metadata interface's icon. And, my favicon or icon images stored in public/images/icon-light.png and public/images/icon-dark.png. And, now its working dynamically based on color modes.

Buy Me a Coffee πŸ™:
If this video/article helped you a bit and you'd like to support my work, feel free to buy me a coffee: https://buymeacoffee.com/sobhani β˜•οΈ Thanks for keeping me motivated!

Quick Procedure:

  1. Delete any favicon or icon images from app/ directory.
  2. Store favicon or icon images to public/images/ directory.
  3. In app/Layout.tsx metadata.icons.icon add url and href path to the stored images relative path. βœ…

Follow me on X@sabbirsobhani

Buy Me A Coffee

Top comments (3)

Collapse
 
amandakoster profile image
Amanda Koster • Edited

What is inside the <Head> </Head> ?

Collapse
 
mackenly profile image
Mackenly Jones

Icon links with media queries:

<link rel="icon" href="/icons/icon-black.png" media="(prefers-color-scheme: light)">
<link rel="icon" href="/icons/icon-white.png" media="(prefers-color-scheme: dark)">
Enter fullscreen mode Exit fullscreen mode
Collapse
 
adeyemialameen04 profile image
Al Ameen Adeyemi

Do you have an idea on how whatsapp, discord adds like the number of notifications one has to the favicon and how it changes every time there is a new one?