Favicon Setup in React + Vite Projects

Configure favicons in a React application built with Vite. Covers the public directory structure, index.html configuration, and environment-based favicon switching.

Framework Setup

Detailed Explanation

Favicon Setup in React + Vite

Vite-based React projects handle favicons through the index.html file and the public directory. Here is a comprehensive setup guide.

Project Structure

project/
├── public/
│   ├── favicon.ico
│   ├── favicon-16x16.png
│   ├── favicon-32x32.png
│   ├── favicon-48x48.png
│   ├── favicon.svg
│   ├── apple-touch-icon.png
│   ├── android-chrome-192x192.png
│   ├── android-chrome-512x512.png
│   └── site.webmanifest
├── index.html
└── src/
    └── ...

index.html Configuration

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <!-- Favicons -->
  <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
  <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="icon" type="image/png" sizes="48x48" href="/favicon-48x48.png" />

  <!-- Apple Touch Icon -->
  <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />

  <!-- Web App Manifest -->
  <link rel="manifest" href="/site.webmanifest" />

  <!-- Theme Color -->
  <meta name="theme-color" content="#ffffff" />

  <title>My React App</title>
</head>
<body>
  <div id="root"></div>
  <script type="module" src="/src/main.tsx"></script>
</body>
</html>

Dynamic Favicon in React

You can change the favicon programmatically:

import { useEffect } from "react";

function useFavicon(url: string) {
  useEffect(() => {
    const link = document.querySelector<HTMLLinkElement>(
      'link[rel="icon"]'
    );
    if (link) {
      link.href = url;
    } else {
      const newLink = document.createElement("link");
      newLink.rel = "icon";
      newLink.href = url;
      document.head.appendChild(newLink);
    }
  }, [url]);
}

Environment-Based Favicons

Use different favicons for development and production:

const favicon = import.meta.env.DEV
  ? "/favicon-dev.svg"
  : "/favicon.svg";

Vite Build Handling

Files in the public directory are:

  • Copied to the build output as-is
  • Not processed or hashed by Vite
  • Accessible at the root URL path
  • Not subject to tree-shaking or optimization

This means favicon files maintain their original filenames and paths after building.

Use Case

React developers using Vite (Create React App's modern replacement) need this guide when setting up favicons for their single-page applications. This covers the standard Vite approach as well as advanced techniques like dynamic favicons and environment-specific icons.

Try It — Favicon Checker

Open full tool