I have a Nuxt3 app, and I am needing to persist any query variables across all internal instances of .
An example would be if a user were to arrive from a Google ad, several query variables would be appended to the URL. However once I start clicking around on internal buttons, those query variables are lost.
I was looking into global middleware that would look for from.query, and if that exists, set that to to.query, however it doesn't appear to run when clicking on any (I only see console logs on page refresh).
export default defineNuxtRouteMiddleware((to, from) => {
console.log({ from });
console.log({ to }); <-- these don't run across pages
if (from.query) {
to.query = from.query;
}
});
I suppose one way would be to manually alter each and every nuxt-link within the application to look for query variables and append those to the href, however there are a ton of buttons and would require a lot of code duplication.
What's the best way to persist these variables?
You can add a global middleware where you use the suggested function for redirect that is
navigateTo().Global middlewares are created using the suffix
globalin the file name in themiddlewarefolder.The code to redirect to any
NuxtLinkpath if a query is present in the current page and a query is not declared by the link could be:I created a simple project where you can verify that the
{ foo: 'bar' }query (or any other query provided), is preserved while you navigate back and forth between the home, the contact page and the page with id param:https://stackblitz.com/edit/nuxt-starter-rw7pv4?initialpath=?foo=bar
Documentation:
Middleware directory:
https://nuxt.com/docs/guide/directory-structure/middleware#format
navigateTo:
https://nuxt.com/docs/api/utils/navigate-to