Next.js Discord

Discord Forum

Auth wrapper handling to prevent enter specific routes

Unanswered
Bartholomeas posted this in #help-forum
Open in Discord
Avatar
Hello, i want to prevent entering several routes when user is logged in/not. I have info about user is logged in or not just on the client (backend is in .Net and logged in user is handled by session token). Everything works great when im moving to page by entering it in url (for example .../login) then user is moved out to another page.

But when i went to that page by <Link/> component my AuthGuest component for some reason doesnt run.. (or it runs but account in that moment is null so i cannot handle logged in user).


What may be wrong? 🤔

"use client";

import React, {  useLayoutEffect } from "react";
import { useRouter, usePathname, redirect } from "next/navigation";

import { useQueryClient } from "@tanstack/react-query";
import { routes } from "@/misc/routes";
import { useCreateGuest } from "@/features/account/customers";
import { CART_KEY } from "@/features/cart";
import { useGetAccount } from "../api/getAccount";

const guestRoutes = [
  routes["public.sign-in"],
  routes["public.signup-default"],
  routes["public.signup-showroom"],
  // routes["public.forgot-password"],
  // routes["account.index"],
  // routes["account.change-password"],
  // routes["account.orders"],
  // routes["account.single-order"],
  // routes["account.update-address"],
];

const AuthGuest = () => {
  const { account } = useGetAccount();
  const pathname = usePathname();
  const { mutate } = useCreateGuest();
  const queryClient = useQueryClient();

  const invalidateCart = async () => {
    await queryClient.invalidateQueries({ queryKey: [CART_KEY] }).catch(console.error);
  };
  useLayoutEffect(() => {
    if (!account) {
      mutate();
      if (pathname.includes('konto')) {
        redirect(routes["public.index"])
      }
    } else if (guestRoutes.includes(pathname) ) {
      redirect(routes["public.index"])
    }

    void invalidateCart();
  }, []);

  return <></>;
};

export default AuthGuest;

0 Replies