Back to blog

Fix 404 errors with Vue.js apps on Netlify

Posted

If you've deployed a Vue.js app application to Netlify, chances are you've seen this 404 error page:

404 error page in Netlify

Netlify 404 error: Page Not Found - Looks like you've followed a broken link or entered a URL that doesn't exist on this site.

I faced this issue with a Vue.js app that uses Vue Router in history mode. This is what the official documentation mentions about it:

  • The default mode for vue-router is hash mode - it uses the URL hash to simulate a full URL so that the page won't be reloaded when the URL changes.
  • To get rid of the hash, we can use the router's history mode.
  • 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 http://oursite.com/user/id directly in their browser. [...] 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.

// Example URLs without history mode
http://myweb.com/#
http://myweb.com/#/contact
http://myweb.com/#/about

// Example Routes WITH history mode
http://myweb.com/
http://myweb.com/contact
http://myweb.com/about

In summary, the problem is that when we enable history mode in Vue Router, the app routes behave like normal HTTP routes so unless we do something, the web server will try to fetch a different file for each route.

A quick fix for this is to enable an automatic redirect in the server to automatically serve the entry point of the app (the index.html) to redict to if the requested route does not match any static file (like a picture). In Netlify we can do this by adding a file named "_redirects" with the following content inside the public folder of the app:

/*    /index.html   200

Which basically tells Netlify to redirect all routes to the index.html page, the entry point of your app. But don't worry, this doesn't mean that if you enter http://myweb.com/about in your browser, it will redirect you to the index page in http://myweb.com. It will just go the app entry point, Vue Router will be triggered, it'll analyze the URL and display the correct view 🤘.

Hope you find this useful. Happy coding!

Included in categories

vue.js javascript tooling deployments servers
Related articles

If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️

Buy me a coffeeBuy me a coffee

Oh! and don't forget to follow me on Twitter where I share tons of dev tips 🤙