Why ever use snippet 2 over 1?
Answered
Mugger Crocodile posted this in #help-forum
Mugger CrocodileOP
1:
2:
I believe 2 responds with 30X response code to client's first request, forcing client to send second request? vs. in 1, the client is not forced to send followup request. So #1 seems to have same semantics as #2, but strictly more efficient. Is that correct?
export default async function Page() {
const router = useRouter();
const user = await getUser();
useEffect(() => {
if (!user) {
router.push("/log-in");
}
});
}
2:
export default async function Page() {
const user = await getUser();
if (!user) {
redirect("/log-in");
}
}
I believe 2 responds with 30X response code to client's first request, forcing client to send second request? vs. in 1, the client is not forced to send followup request. So #1 seems to have same semantics as #2, but strictly more efficient. Is that correct?
Answered by James4u (Tag me if needed)
your welcome! mark solution to close the thread! @Mugger Crocodile
16 Replies
@Mugger Crocodile well your snippet 1 is completely wrong
that's a mix of server component + client component
you even won't be able to build it
you are doing server-side data fetching inside the server component, on the other hand, you are using useEffect() (a hook which can't be used inside the server component)
but if your question was about general redirection approach on server vs client side
my answer would be, it's more efficient and better to do redirect on the server
Mugger CrocodileOP
yep I see now, apologies for not checking before. but conceptually, #1 seems possible. in that do the user fetching server-side, but rather than return 30X code with
Location
header for client to query, return JS which runs that client-side redirect.my app not at scale where it matters. but trying to obtain a thoretical understanding, wouldn't that beat:
forcing client to make another round trip request in the case of server side redirect?
it would be working if you pass the user you queried out to the client coponent, and then you redirect inside useEffect in your client component - it should be working
I just pointed out the issue of hook usage inside the server component
so why not server side redirection? what's your problem? @Mugger Crocodile
Mugger CrocodileOP
i believe I identified my reasoning mistake, I was thinking client side redirect avoided second round trip request
but now I believe both have second round trip request anyway to
/log-in
. in which case no differenceMugger CrocodileOP
I understand now, thank you for help
your welcome! mark solution to close the thread! @Mugger Crocodile
Answer