nuxt.jsnuxt3.jsnuxt-auth

Redirect to auth screen if no token is available in defineNuxtRouteMiddleware


When the app loads by default it will go to the / route which is the protected route and if there is no user token available then the app should push the page to /auth.

import { defaultStore } from "@/store/default";

export default defineNuxtRouteMiddleware((to, from) => {
  const router = useRouter();

  let token = defaultStore()?.getUserDetails?.authToken;
  let loginURL = "/auth";

  let isAllowedRoute =
    to.path.startsWith("/ko/auth") ||
    to.path.startsWith("/auth") ||
    to.path.startsWith('/setup') 

  if (isAllowedRoute) return;

  if (!token && to.path !== loginURL) {
    router.push(loginURL);
  }
});

Here is my middleware and rightnow when the site loads i can see the / page rendered and in a second its redirecting to the /auth route which looks glitchy.


Solution

  • The only thing that caused that 'glitchy look' is useRouter(). Try to use navigateTo() helper there insted useRouter(), this should solve that problem.

    router.push(loginURL);
    return navigateTo(loginURL);

    Link to docs