Using react router and Firebase hosting to run a website, when refreshing or navigating to a specific path I get a Mime type error.
Example: I can navigate to website.com/projects just fine When entering website.com/projects/ or website.com/projects/project1 etc. I get the error.
This only happens when hosting, not when running locally.
When using the build in navigation buttons (ie. I navigate to website.com/projects to website.com/projects/project1 by clicking a button on projects) it works as expected. However, if I refresh it breaks again.
Error is:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
Firefox gives a little more detail: The stylesheet https://website.com/projects/assets/index-8ea4127f.css was not loaded because its MIME type, “text/html”, is not “text/css”.
Loading module from “https://website.com/projects/assets/index-c61e1629.js” was blocked because of a disallowed MIME type (“text/html”).
Loading failed for the module with source “https://website.com/projects/assets/index-c61e1629.js”.
I have firebase rewrites setup for a single page application:
"site": "examplewebsite.com",
"public": "dist",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
],
"rewrites": [
{
"source": "**",
"destination": "/index.html"
}
]
And have the structure of my dist folder as so:
Attempted to refresh or navigate directly to a page. Expected firebase to rewrite to index.html and react router to handle it from there and load the correct components. Instead got mime type error and blank page. Also did not result in secondary expected result of 404 page loading.
Fixed the issue by updating my vite.config.js from:
export default defineConfig({
plugins: [react()],
build: {
outDir: "dist" // tells vite to output the build to a folder called docs
},
base: './' // tells vite to request dependencies relative to the path the app is hosted on, not the root domain
})
to
export default defineConfig({
plugins: [react()],
build: {
outDir: "dist" // tells vite to output the build to a folder called docs
},
base: '/' // tells vite to request dependencies from the root domain
})