Next.js Discord

Discord Forum

Separate favicon for browser tabs and Google search results

Answered
American posted this in #help-forum
Open in Discord
AmericanOP
I have seen websites which have different icons for the browser tabs and google search results as depicted in the screenshots (example from https://deliveroo.co.uk/).

How can we specify different favicons for those?
Answered by Little fire ant
@American try by checking user-agent
View full answer

3 Replies

Little fire ant
@American try by checking user-agent
Answer
AmericanOP
Like so?
import path from "path";
import { promises as fs } from "fs";
import { NextResponse } from "next/server";
import { NextRequest } from "next/server";

export async function GET(req: NextRequest): Promise<NextResponse> {
  const userAgent = req.headers.get("user-agent") || "";

  let faviconPath: string;

  if (userAgent.includes("Googlebot")) {
    faviconPath = path.join(process.cwd(), "public", "googlebot-favicon.png");
  } else {
    faviconPath = path.join(process.cwd(), "public", "favicon.ico");
  }

  try {
    const favicon = await fs.readFile(faviconPath);
    const contentType = userAgent.includes("Googlebot")
      ? "image/png" //
      : "image/x-icon";

    return new NextResponse(favicon, {
      headers: {
        "Content-Type": contentType,
        "Cache-Control": "public, max-age=86400",
      },
    });
  } catch (error) {
    console.error("Error serving favicon:", error);
    return new NextResponse("Internal Server Error", { status: 500 });
  }
}


Sends a different icon for crawlers.
Then I add it in the root layout like this:
<link rel="icon" href="/api/favicon" type="image/x-icon" />

I dont find many resources on this topic, I dont even know if crawlers look for example.com/favicon.ico or prioritize the <link> tag.
On some pages the apple-touch-icon is displayed in the search results instead of the favicon.

Since it takes Google quite a while to update the favicon (days or weeks), it's not easy to figure it out 😢

With the new <link> tag google should retrieve a new icon (googlebot-favicon.png) and display that one in the search results. The icon in the browser tab will still be the previous one (favicon.ico).

I guess I just gotta wait now for Google to crawl and set the new icon in the search results.
AmericanOP
Google already crawled and updated it 🥳 i just made the favicon.ico in the root accessible only to browsers and gave crawlers another image.
The icon in the search console now looks much better than before! Ty @Little fire ant