Middleware can depend on query string. Middleware runs once per navigation, wherever. This works wonderfully for first SSR load from a living server.
However, when generating pages, query
is always {}
.
So, when a static page is accessed with a query string (from another site, bookmarks, chat) the resulting page is as if there was no query string, since the middleware is pre-executed only.
Hence, middleware depending on query is broken on static load.
What should we do?
Yeah the middleware doesn't fire on first page visit because it's supposed to fire on the backend (which, ofcourse, doesn't exist when generated)
Any workaround to this?
@qm3ster
Commented too quickly, you should use a plugin, I solved it like this;
// plugins/token.js
export default function ({ app, store }) {
app.router.onReady(() => console.log(app.router.currentRoute.query))
}
// nuxt.config.js
plugins: [
{src: '~/plugins/token.js', ssr: false}
]
Hope it helps :)
@Mat-thieu that is indeed one of the workarounds.
Myself, I put the logic into the page component's created
hook.
But a decision on how this should be addressed should be made, for instance by having no-generate middleware that otherwise conforms to the middleware environment, but runs on the client in case of generate.
Can a contributor tell me if this is expected behaviour?
It's definitely not a bug, if that's what you mean.
It's _accepted_ behavior.
Fair enough, will use plugins then :)
This has been soooo helpful that it should be in the official docs.
@qm3ster @Mat-thieu
Do you have any solutions for running a redirect in this specific scenario? seems like the router can't find the route in that point of runtime.
@SnirShechter The code I posted should also work for a redirect, it waits until the router is completely ready.
Are you using this on the initial load or after some navigation?
@Mat-thieu
I'm using it in the initial load(since after that Vue & Vue-Router are up and running).
Thing is, your code doesn't switch layouts. the router redirects to the correct page with the current layout.
Any help here, anyone?
This question has been resolved by @Mat-thieu, see answer.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Most helpful comment
@qm3ster
Commented too quickly, you should use a plugin, I solved it like this;
Hope it helps :)