Vue Js router in history mode

How to redirect all request to index.html page?

Like we do rewrite_rule in .htaccess file?

I want this to host a vue.js application having vue router in history mode.

It giving me 404 error, when hitting direct url from browser.

Something like netlify.com have _redirects file

Note - I’m talking about glitch static site project without backend.

Hi,

Glitch does not have a config file to set rules like redirecting, yet.

Long story short, you can’t do vue-router projects with History mode.

I’m still trying to figure out a workaround to this problem :slightly_smiling_face: (I use Vue really often and this limitation is the only thing stopping me from hosting Vue projects on Glitch).

Hope this helps!

P.S. You can suggest this as a feature - #feature-ideas

My knowledge of Vue is extremely dated but I looked it up. Does the following not work? It would seem to me that the simple Native Node.js example would work, is that not the case?

https://router.vuejs.org/guide/essentials/history-mode.html#example-server-configurations

Yes and no. For that to work, you need an Express-based backend to serve the built files. But OP’s mention of Netlify’s _redirects file leads me to believe that their project is using a simple static serving of the built files, which is also the recommended way to serve Vue applications.

There might be a way to implement this using lws with a JS config file. (null.config.js or something like that)

Granted I don’t know for certain but the page about the Vue Router includes the following:

`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 http://oursite.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!`

It doesn’t require Express per se the example I mentioned was using the Node server. I’ll defer to others I always used a server to serve my SPA apps (and still do).

Oops, what I meant by “Express-based backed” was a Node server, sorry about that!

Can’t we email this issue to direct glitch team?

Because this thing is a need for most of the frontend framework.

Not a problem at all. I figured there might be an alternative around the issue while (if) another solution is in the works. I used Vue a couple of times but never the Vue Router. Svelte (which I love) has a similar capability but I didn’t use those routers in my SPA apps either.

I realize that many (perhaps most) do.

1 Like

There are two options as of now that I can think of: using a service worker, or manually adding all your routes as files.

Option 1: using a service worker

Service workers are really cool. They run in the background, and can be used to do stuff like cache assets and modify network requests, without a server - it all happens in your browser. Service workers are also fully async and HTTPS only. The only problem with service workers is that you need to register them before they can be used - so a user will have to naviate to the home page of your site first in order to be able to navigate correctly to other pages.

Step 1: create your service worker file

You’ll need to create a js file, usually called sw.js, at the root of your site, with something like the following in it:

self.addEventListener("fetch", event => { // listens to requests on your project
  let modifiedUrl = /^https:\/\/projectname\.glitch\.me/.test(event.request.url) // is the url on the same domain?
    && !/\.(js|css|svg|png|jpg|vue|ico)/.test(event.request.url) // is it not a static asset that we don't want to render as a page?
    && !/vite/.test(event.request.url) // only needed if you're using vite, same purpose as above
    ? "/" : event.request.url; // if all of the above are true, return our index.html instead of glitch's usual 404 page
  event.respondWith(fetch(modifiedUrl)); // respond with the correct response
});

This will need to be adjusted for your needs - replace projectname with ypur project name, and in the section that goes (js|css| ... |ico), make sure to add any file extensions that your site may need to be served normally.

Step 2: register your service worker

Once step 1 is completed, if you go to your site it will act as it usually does i.e. not work. So, you’ll need to add the following code to the top of your main script file, assuming it has the defer tag or is loaded at the end of the <body> - otherwise, wrap this in a window.addEventListener("load", () => { ... });.

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

You can get rid of the console.logs if you’d like.
Now, naviagate to your home page, enter another url on your site in your browsers navigation bar, and you should see your site working correctly! And as long as all your users go to your home page first, it’ll work for them as well :smiley:

Option 2: manually add all your routes

This one’s really simple. For each of your routes, e.g. this/is/a/page, copy your index.html to this/is/a/page/index.html, and it should Just Work™. However, this will only work if your project is fully static and not a generated static site. If it is a generated static site, you’ll have to either write your own extra build script and/or vite/webpack/rollup/whatever plugin that imports your routes and copies build/index.html to build/this/is/a/page/index.html. If this is the case, I’ll leave you to your own devices to build that :slight_smile:

Obviously neither of those options are particularly desirable, but who knows, maybe official support for this will come one day :crossed_fingers:
Hopefully this very long post will help you, and happy glitching :slight_smile:

P.S. I’d recommend checking out Redirect non-existing routes to index.html for Generated Static Sites and giving it a vote :wink:

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.