How to pass access token from server component to client component in Next.Js - Stack Overflow

admin2025-04-21  2

want check if the accessToken is present before send a get request to fetch the user is this safe or the accessToken can be leaked

this the fetch request

export const fetchUser = async () => {
   const response = await API.get("/user");
   return response.data;
};

this the hook to fetch the user and check if the accessToken is present to prevent unnecessary requests

export const useAuth = (accessToken: string) => {
   const query = useQuery({
      queryKey: ["authUser"],
      queryFn: fetchUser,
      retry: false,
      enabled: !!accessToken,
   });
   return query;
};

in the auth provider i get the accessToken in the client component to pass it to useAuth hook

export const AuthProvider = ({
   children,
   accessToken,
}: {
   children: React.ReactNode;
   accessToken: string;
}) => {
   const { setUser } = useUserStore();
   const { data, isLoading, isFetching, isSuccess } = useAuth(accessToken);
   console.log(accessToken);

   useEffect(() => {
      if (isSuccess) {
         setUser(data?.user);
      }
   }, [setUser, data, isSuccess]);

   
   return <>{children}</>;
};

and in RootLayout i get the accessToken from the cookie to pass it to the auth provider

export default async function RootLayout({
   children,
}: Readonly<{
   children: React.ReactNode;
}>) {
   const accessToken = (await cookies()).get("accessToken")?.value;
   return (
      <html lang="en" dir="rtl">
         <body
            className={`${geistSans.variable} ${geistMono.variable} bg-white text-black antialiased`}
         >
            <QueryProvider>
               <AuthProvider accessToken={accessToken!}>
               {children}
               </AuthProvider>
            </QueryProvider>
         </body>
      </html>
   );
}

is this safe way to do it or i can do it better without pass it to client component Any suggestions?

转载请注明原文地址:http://anycun.com/QandA/1745223520a90428.html