#Why ever use snippet 2 over 1?

18 messages · Page 1 of 1 (latest)

devout jay
#

1:

  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?
vital templeBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

silver gyro
#

@devout jay 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

devout jay
#

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?

silver gyro
#

I just pointed out the issue of hook usage inside the server component

#

so why not server side redirection? what's your problem? @devout jay

devout jay
#

but now I believe both have second round trip request anyway to /log-in. in which case no difference

#

I understand now, thank you for help

silver gyro
#

your welcome! mark solution to close the thread! @devout jay