nuxt.jsvue-routernuxt3.jsnuxt-link

How to persist query variables across internal <nuxt-link/> components?


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?


Solution

  • You can add a global middleware where you use the suggested function for redirect that is navigateTo().

    Global middlewares are created using the suffix global in the file name in the middleware folder.

    The code to redirect to any NuxtLink path if a query is present in the current page and a query is not declared by the link could be:

    export default defineNuxtRouteMiddleware((to, from) => {
    
      if (Object.keys(from.query).length && !Object.keys(to.query).length) {
    
        return navigateTo({
          path: to.path,
          hash: to.hash,
          params: to.params,
          query: from.query,
          redirectCode: 302, // default
        });
      }
    });
    

    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:

    There are three kinds of route middleware: 3. Global route middleware, which are placed in the middleware/ directory (with a .global suffix) and will be automatically run on every route change.

    https://nuxt.com/docs/guide/directory-structure/middleware#format

    navigateTo:

    navigateTo is a router helper function that allows programmatically navigating users through your Nuxt application. navigateTo is available on both server side and client side. It can be used within plugins, middleware or can be called directly to perform page navigation.

    https://nuxt.com/docs/api/utils/navigate-to