Nextjs +jwt authentiction using server components
Unanswered
Scale parasitoid posted this in #help-forum
Scale parasitoidOP
//AuthProvider.tsx
"use client";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
export default function AuthProvider({
children,
}: {
children: React.ReactNode;
}) {
const [isSuccess, setIsSuccess] = useState(false);
const router = useRouter();
useEffect(() => {
(async () => {
const { error } = await getUser();
if (error) {
router.push("/signin");
setIsSuccess(true);
return;
}
setIsSuccess(true);
})();
}, [router.push]);
if (!isSuccess) {
return <>loading...</>;
}
return <>{children}</>;
}//layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<AuthProvider>{children}</AuthProvider>
</body>
</html>
);
}I am implementing custom jwt authentication. Here the AuthProvider is a client component , so that on page refresh it can verify the jwt and act accordingly.
In this implementation there is a slight jitter, that for very small duration where the protected route is seen. How can I not make the protected route seen completely?
Is there any way to implement this only using server components?
Github code:https://github.com/codefromrvk/freespirit
8 Replies
Californian
why do u implement this only using server components?
It's better using client components
Scale parasitoidOP
Can you please let me know whether my current implementation is good enough?
I have a small proble:
I have a small proble:
In this implementation there is a slight jitter, that for very small duration where the protected route is seenGull Dong
Doesn’t middleware have the same effect?
@Californian It's better using client components
Somali
Sever components should offer better security is my guess. Why would you want to use client components?
Scale parasitoidOP
The problem I faced when implementing it with server components was redirecting.
Consider the following code inside a AuthProvider
Consider the following code inside a AuthProvider
const AuthProvider= ({children})=>{
const isTokenValid = jwt.verify(cookies().get("token"), secret_code)
if(isTokenValid){
// I am getting an error if I use something like this- It says browser redirected too many times
return redirect('/signin')
}
return <>{children}</>
}that is because that function is ran on
/signinScale parasitoidOP
So you mean to say that it is redirecting once when clicking on signin button and again it tries to redirect when it reaches the above code?