JWT auth using react-query and next 14 for frontend and custom Django backend

  Kiến thức lập trình

so iam working on a CMS project using next14 as the front-end and python for the custom backend “backend colleague

the backend takes credintials and send my 2 httponly cookies in response “access-token” 10 mins expiration ,”refresh-token” 10 days expiration.

i handled protected routes state using wrapper component wraps the root layout.tsx and with react-query hitting an endpoint that validates the token in the backend and returns boolean

export const AuthorizationProvider = ({
  children,
}: {
  children: React.ReactNode;
}) => {
  const router = useRouter();
  const pathname = usePathname();
  const { data, isLoading } = useQuery({
    queryKey: ["authorized"],
    queryFn: authorized,
    staleTime: 10 * 60 * 1000, //10 mins
  });
  if (isLoading) {
    return <div>loading...</div>;
  }
  if (!data) { 
    router.push("/login");
  } else if (pathname === "/login") {
    router.push("/domain");
  }
  return <>{children}</>;
};

so whenever a user try to access protected route by changing the path in the URL the wrapper checks if true go ahead false go back to login.

the questions are:

  1. is this the right way to handle protected routes? and if not what to do?
  2. how to handle the refresh token the right way?

most tutorials on youtube handle refresh very easily as the backend is next api, which is not helping in my case.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT