Page Not Found on Reload Vuejs — Netlify

Oluwatobi Seun
Nov 7 · 3 min read

Have you hosted your app (Single Page Application) on Netlify and gotten a heart break when you reload any page/component and saw “Page Not Found” ?

Don’t worry, The solution is almost no brainer as it is just 1 simple task.


QUICK PEEK ON THE PROBLEM.

Vue Router has a property that you set on; it’s called mode. It can have different values and each values have their uniqueness.

Here’s what the Vue-Router documentation says:

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, which leverages the history.pushState API to achieve URL navigation without a page reload:

In hash mode our url would look like this localhost:8080/#/endpoint

In history mode our url would look like this: localhost:8080/endpoint

Guess you have seen this, but don’t until now. Don’t worry, there’s more to learn.

When hosting on any server like Netlify, if you refresh the page on any url other than ‘/’ you will receive a 404 error. This will also happen if a user tries to directly access a url on your site. This is quite not ideal, and really limits how users interact and can share your website.

Vue Router documentation has information on how you can fix this; But unfortunately, not quite with Netlify. To check the documentation, see here.


SOLUTION

All you have to do is to create a file called _redirects in the /public folder in your application and please note that this file should not have an extension. Ever wondered what will be in this file, just add this line of code:

/* /index.html 200.

My Project Snapshot

Read more because Netlify has documentation on redirects here.

And guess what, That’s All!!!

But there is one little problem, the initial problem is solved but there is a new behaviour of the application to be corrected. If a user enters a wrong url, it will automatically redirect to the index.html page and which i am sure you don’t want that.

Sue you know how to do that. But incase you don’t.

A SNEAK PEEK INTO SOLVING THE NEW PROBLEM

Just create a custom 404 page, setup a new route like this:

{
path: ‘/*’,
component: 404
},

in the routes.js or route/index.js depending on whichever you find yourself using. And this will allow you application to redirect to a proper 404 page whenever a user enters a wrong url.

The you can successfully test your application.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade