Error 404 on page reload with vue3 routing

Viewed 2732

Problem

When I hit reload on a route, e.g /installer, in vue3.js I get the following error:

Error

Code

I use the Router with the following setup:

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

Additional Information

(I don't use createWebHashHistory to get rid of the hashtags in url)

I also get this error when I go to the route, e.g. /installer, directly and not via link.

Question

How to resolve this error?

2 Answers

This is to do with your server configuration, read through this section from the docs:

... Here comes a problem, though: Since our app is a single page client side app, without a proper server configuration, the users will get a 404 error if they access https://example.com/user/id directly in their browser. Now that's ugly. Not to worry: To fix the issue, all you need to do is add a simple catch-all fallback route to your server. If the URL doesn't match any static assets, it should serve the same index.html page that your app lives in. Beautiful, again!

The section below it gives different examples for different servers.


It suggests using the connect-history-api-fallback package for an Express server, but I've always just used this which works fine:

if (process.env.NODE_ENV === 'production') {
    // Handle SPA
    app.get(/.*/, (req, res) => res.sendFile(__dirname + '/public/index.html'));
}
Related