DEV Community

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

Posted 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:

// 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.

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

Top comments (0)