記事

Nuxt3 Firebase authで未認証でもとのページに戻るコード

#tech
Nuxt3
Firebase

import { onAuthStateChanged, getAuth } from "firebase/auth";
export default defineNuxtRouteMiddleware((to, from) => {
  console.log({ to }, { from });
  onAuthStateChanged(getAuth(), (user) => {
    console.log({ user });
    if (!user) {
      // ログインしていない場合はログインページにリダイレクトする
      navigateTo("/login");
    } else {
      const to = from.redirectedFrom?.fullPath || "/home";
      console.log({ to });
      console.log(from.fullPath);
      navigateTo(from.fullPath, { redirectCode: 302 });
    }
  })
});

© 2026 Shotaro Kinjo