Search code examples
vue.jsexpressserver-side-renderingwebpack-dev-serverquasar

Vue Router not working for root path ("/") when using Quasar SSR


ISSUE DESCRIPTION

I have an Quasar CLI (Webpack) running my app, it works just fine in SPA mode. But when I switch to SSR. Out of nowhere Vue Router redirect from path "/" to e.g. "/index" doesn't work. By which I mean, that it shows an empty "index.html", But App wasn't mounted. This problem only applies to root ("/"). Redirect from e.g. "/feed" to "/feed/something" works as expected.

router > routes.js

const routes = [
  { path: '/', name: "Index2", redirect: '/index' },
  {
    path: '/index',
    name: 'Index',
    component: Index
  }, 
  // ...
]

So my question is is there a way to use root path ("/") to serve a content or redirect.

SOLVING STEPS

DEVELOPMENT

I have solved the problem in an very unclean way as follows

In quasar.config.js > devServer

onBeforeSetupMiddleware: (server) => {
  server.app.use(function(req, res, next) {
    if(req.url === "/") res.redirect("http://localhost:8080/index")
    next()
  })
}

PRODUCTION

This approach works just fine in development mode, but still I'm assure that it's not the best solution.

  1. I tried doing the same for production build inside of first "SSR middleware"
    OUTPUT: failure

  2. So I tried putting the "same code" into "production-export.js"
    OUTPUT: failure

export default ssrProductionExport(async ({ app, port, isReady }) => {
  app.use(function(req, res, next) {
    if(req.url === "/") res.redirect("https://example.com/index")
    next();
  })
  await isReady()
    return app.listen(port, () => {
      console.log('Server listening at port ' + port)
  })
})
  1. Then I become really desperate so I tried the same approach inside of actual exported SSR server.
    OUTPUT: works but it is errored and also it's the worst approach I could ever came up with.
    ERROR: Error: Can't set headers after they are sent.

dist > ssr > index.js

// function I added
m.use(function(req, res, next) {
  if(req.url === "/") res.redirect("https://example.com/index");
  next();
});

m.use(g("/"), S(".")); // This line was already in here

I see this as temporary solution, now wondering if it wouldn't be better to just make it redirect inside of NGINX with some kind of "rewrite" rule.

Thanks for any input.


Solution

  • My fault, left of an "index.html" file inside of "public" folder after migrating from Vue.js CLI, while Quasar uses "index.template.html" inside of "src" folder. So it has been served static by express server.

    So solution is for sure deleting/renaming that "index.html" file.