Before setting base
in my Vite configuration I can visit the app root at http://localhost:5173 without issue (renders 'Home'). When I add base though with a value of /tools/evidence
and visit http://localhost:5173/tools/evidence as helpfully output by the Vite dev server it doesn't work - its instead renders the <Not Found />
component.
I have put some debug in Not Found component and the paths are as expected. I can't figure out why they aren't resolving ...
Here are my routes ...
// ... imports ...
const NotFound = () => {
const location = useLocation()
console.log(location)
return <h1>Not Found</h1>
}
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ApolloProvider client={client}>
<BrowserRouter>
<Routes>
<Route index element={<div>Home</div>} />
<Route
path="/topics/*"
element={
<>
<EditorRoutes />
<PrintRoutes />
</>
}
/>
<Route path="/feedback" element={<FeedbackPage />} />
<Route path="/accessibility" element={<Accessibility />} />
<Route path="/cookies" element={<Cookies />} />
<Route path="/algorithms" element={<Algorithms />} />
<Route path="/privacy" element={<Privacy />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
</ApolloProvider>
</React.StrictMode>
);
here is my vite.config.ts
// ... imports ...
export default defineConfig({
plugins: [react()],
base: '/tools/evidence',
css: {
postcss: {
plugins: [
postcssNesting
]
}
}
})
You may just need to add a basename
to the router to match the "directory" the app is now running or being served from. This is to configure, or inform, the router to render all routes and links relative to this basename path, e.g "/tools/evidence/feedback"
.
Example:
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ApolloProvider client={client}>
<BrowserRouter basename="/tools/evidence"> // <-- router basename
<Routes>
<Route index element={<div>Home</div>} /> // "/tools/evidence"
<Route
path="/topics/*" // "/tools/evidence/topics/*"
element={
<>
<EditorRoutes />
<PrintRoutes />
</>
}
/>
<Route
path="/feedback" // "/tools/evidence/feedback"
element={<FeedbackPage />}
/>
<Route path="/accessibility" element={<Accessibility />} />
<Route path="/cookies" element={<Cookies />} />
<Route path="/algorithms" element={<Algorithms />} />
<Route path="/privacy" element={<Privacy />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
</ApolloProvider>
</React.StrictMode>
);