nuxt / nuxt

The Intuitive Vue Framework.

Home Page:https://nuxt.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

navigateTo not working inside defineNuxtPlugin on initial render

theathleticnerd opened this issue Β· comments

Discussed in #27301

Originally posted by theathleticnerd May 22, 2024
I'm trying to navigate the app to a path in my $fetch wrapper plugin. The url to be redirected to is being sent by the API.
If response._data.redirect is true, then it should redirect to response._data.redirect_url_path.
The code below doesn't work on the initial render (while directly going to the particular url), but it does work after the app loads and the user navigates through the app to the particular url.

This is payload in case of a page that should be redirected:

{
    "redirect":true,
    "redirect_url_path":"/xyz/def",
}

This is the code of the $fetch wrapper.

// plugins/customFetch.ts
export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig();
  const $customFetch = $fetch.create({
    baseURL: config.public.baseURL,
    async onRequest({ request, options, error }) {
      options.headers = {
        "X-PUBLIC-URL": `https://www.abcd.com${request}`,
      };
    },
    async onResponse({ response }) {
      if (response._data.redirect) {
        await navigateTo(response._data.redirect_url_path);
      }
    },
  });
  // Expose to useNuxtApp().$customFetch
  return {
    provide: {
      customFetch: $customFetch,
    },
  };
});

This is the code of the the useFetch wrapper composable

// composables/serverFetch.ts
import type { UseFetchOptions } from "nuxt/app";
export function $serverFetch<T>(
  url: string | (() => string),
  options: UseFetchOptions<T> = {},
) {
  return useFetch(url, {
    ...options,
    $fetch: useNuxtApp().$customFetch,
  });
}

I have tried using nuxtApp.runWithContext and callWithNuxt but it is still not working.
I would greatly appreciate your help.
Thank you.

Would you be able to provide a reproduction? πŸ™

More info

Why do I need to provide a reproduction?

Reproductions make it possible for us to triage and fix issues quickly with a relatively small team. It helps us discover the source of the problem, and also can reveal assumptions you or we might be making.

What will happen?

If you've provided a reproduction, we'll remove the label and try to reproduce the issue. If we can, we'll mark it as a bug and prioritize it based on its severity and how many people we think it might affect.

If needs reproduction labeled issues don't receive any substantial activity (e.g., new comments featuring a reproduction link), we'll close them. That's not because we don't care! At any point, feel free to comment with a reproduction and we'll reopen it.

How can I create a reproduction?

We have a couple of templates for starting with a minimal reproduction:

πŸ‘‰ https://stackblitz.com/github/nuxt/starter/tree/v3-stackblitz
πŸ‘‰ https://codesandbox.io/s/github/nuxt/starter/v3-codesandbox

A public GitHub repository is also perfect. πŸ‘Œ

Please ensure that the reproduction is as minimal as possible. See more details in our guide.

You might also find these other articles interesting and/or helpful:

I have attached a link to the code below:
https://stackblitz.com/edit/github-m9sk89?file=plugins%2FcustomFetch.ts

While this works after the app is loaded, it doesn't work during SSR.

navigateTo is being used inside the defineNuxtPlugin(), but still i'm getting the error:
A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function.

See the link in the error message. You will probably need to do nuxtApp.runWithContext. You're not calling it in the plugin, you're registering a hook that runs sometime later after an async operation.