NuxtN
Nuxt7mo ago
8 replies
AlexDev

Middleware and navigateTo have weird behavior

Hello there, iam using Nuxt v3 and middleware for authentication. So iam trying to redirect a user from "a" url to url "b" when he is not authenticated. The url "a" gets appended with a query to url "b" for easy redirection. Unfornatley, my page (index.vue) has a await useFetch for ssr, this useFetch throws an 401 errror not authenticated from my backend as an error. The whole problem is that the "navigateTo" does not navigate before the ssr throws that error, there is the sample code from the middleware:
import { useUser } from "~/composable/auth";

export default defineNuxtRouteMiddleware(async (to) => {
  const user = useUser();

  if (user.value !== null) return;
  if (to.path === "/authenticated") return;

  const routeParts = to.path.split("/");
  let isProtected = false,
    forward = "";

  for (let crrRoute of routeParts) {
    if (crrRoute === "authenticated") {
      isProtected = true;
      continue;
    }
    if (isProtected) {
      forward += `/${crrRoute}`;
    }
  }

  return navigateTo(`/authenticated?forward=${forward}`, { replace: true });
});

Note: The middleware is named: 02_auth.global.ts and there is 01_user.global.ts for user authentication

Any help is appreicated, thanks!
Was this page helpful?