1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nuxt3でglobal middlewareでnavigateToが使えない

Last updated at Posted at 2024-05-30

概要

Nuxt 3.11.2にて、global middlewarenavigateToを使うとERR_TOO_MANY_REDIRECTSエラーが発生する

※ローカルでnpm run devすると発生しない
 AWS LambdaにデプロイしてCloudFrontにアクセスすると発生した

Nuxt 3.0.0-27444434.856c01aの頃はVue Routerで無限ループが発生していたらしい
(まだこの事象が残っているのか、これが原因でエラーとなっているのかは不明)

回避策

上記記事では「local middlewareなら問題ない」と書いてあるが、ログイン状態によるリダイレクトなどは基本的に全ページで処理したく、全ページにmiddlewareの定義を書くのは面倒
→代わりにrouter.pushを使うと解決した
(他になにか問題が出ているかも、何かあれば追記予定)

/middleware/auth.global.ts
export default defineNuxtRouteMiddleware(async (to, _from) => {
  // なんか時間のかかるログイン状態チェック処理
  const isLoggedIn = await checkIsLoggedIn();

  if (isLoggedIn) {
    if (to.path === "/login") {
-     return navigateTo("/");
+     useRouter().push("/");
    }
  } else {
    if (to.path !== "/login") {
-     return navigateTo({ path: "/login", query: { redirect: to.path } });
+     useRouter().push({ path: "/login", query: { redirect: to.path } });
    }
  }
});
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?