How to add a dynamic favicon in a nextjs app on a dynamic route

Viewed 713

I want my nextjs app to have a different favicon based on the route. This is the working application where I want to implement this. I want the favicon to become the countries flag whenever someone goes to that countries page.

I have the following code in my react components Head tag:

            <Head>
                <title>{country.name} | {country.subregion}</title>
                <link rel="icon" href={country.flag} />
            </Head>

This works sometimes but most of the times the favicon is not updated or the previous favicon stays.

2 Answers

One issue that I had was that your <link> element must be a direct child of next.js's <Head> element. This means you cannot have a <Favicon> React element that internally renders a <link> element. Instead you should call your <Favicon {...props}> React element as a function as shown below:

<Head>
  {Favicon({...props})}
</Head>

Something similar happened to me. Thats my solution. In href, navigate to file folder.

import Head from 'next/head';

export default function MyPage() {
  return (
    <>
      <Head >
        <link rel="icon" type="image/x-icon" href="../../file.svg" />
      </Head>

      <div>Something...</div>
    </>
  )
}

Related