Fix 404 errors with Vue.js apps on Netlify
If you've deployed a Vue.js app application to Netlify, chances are you've seen this 404 error page:
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/iddirectly 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) and redict if the requested route does not match a 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.
If you enjoyed this article consider sharing it on social media or buying me a coffee ✌️
Oh! and don't forget to follow me on Twitter where I share tons of dev tips 🤙
Other articles that might help you
Apart from writing articles in this blog, I spent most of my time working on my personal projects.
Quicktalks is a place where indie hackers, makers, creators and entrepreneurs share their knowledge, ideas, lessons learned, failures and tactics they use to build successfull online products and businesses. It'll contain recorded short interviews with indie makers.Message me to be part of it