Title:
Favicon Not Loading Due to CSP Violation on GitHub Pages with Vite and Custom Domain
Question:
I’m hosting a site on GitHub Pages using a custom domain (https://do-they-reason.com
) with a project built using Vite and React. I’ve placed my favicon.ico
in the root directory, but I’m encountering a CSP (Content Security Policy) violation that prevents the favicon from loading.
The browser console shows the following error:
GET https://do-they-reason.com/favicon.ico [HTTP/2 404 14ms]
Content-Security-Policy: The page’s settings blocked the loading of a resource (img-src) at https://do-they-reason.com/favicon.ico because it violates the following directive: “img-src data:”.
Setup:
-
Repository Structure:
- Root directory contains
index.html
andfavicon.ico
. - There is a
build
subdirectory where the Vite build output is stored.
- Root directory contains
-
HTML (
index.html
):<!doctype html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="shortcut icon" type="image/x-icon" href="favicon.ico"> <title>My Title</title> </head> <body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script> </body> </html>
-
Vite Configuration (
vite.config.ts
):
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';
export default defineConfig({
plugins: [react()],
build: {
outDir: 'build',
},
base: "/",
});
What I’ve Tried:
- Googled the Issue: I found mentions of placing a favicon in a personal repo to apply it site-wide across GitHub Pages, but that’s not the solution I’m looking for.
- Tweaked Vite Config: Tried tweaking the
vite.config.ts
by providing different values forbase
, both absolute and relative paths. - Modified HTML
<link>
Tag: Experimented with different combinations ofrel
,type
, andhref
values in the<link>
tag. - Custom Domain Verification: Verified that my custom domain is properly set up and points to my GitHub Pages site.
- Cache Clearing: Cleared my browser cache before reloading the site.
- Changed Favicon Format: Attempted to use a
favicon.png
instead offavicon.ico
.
Expected Outcome:
I expected the favicon to load without triggering a CSP violation and to be displayed correctly in the browser.
Questions:
- How can I work around the CSP limitations imposed by GitHub Pages to ensure the favicon loads correctly?
- Is there a specific way to structure my project or reference the favicon to avoid this CSP violation given GitHub’s restrictions?
- Are there best practices for handling favicons with GitHub Pages, Vite, and a custom domain to ensure they load without issues?
cesardgm is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.