Next.js Discord

Discord Forum

setting default dynamic route

Unanswered
Oak rough bulletgall wasp posted this in #help-forum
Open in Discord
Oak rough bulletgall waspOP
In my nextJS app, I want to have my home page under a dynamic route is based on data that is fetched during authentication.

Basically here is the flow:
“Merchant” parameter is in URL, validate it is a valid “merchant” of the user (i store this data in the session) and use it. If it is not in the URL, we default to the first “merchant”.

I tried doing this with router in a useEffect in my clientLayout, but got tons of errors when I used router.push in the useEffect. Here is my structure

18 Replies

Northern Wheatear
Did you use useRouterfrom "next/navigation" ? Can you verify
Oak rough bulletgall waspOP
Yes I did, I’ll post the code one sec.
Here is the useEffect
And the console error I get from the router.push
Northern Wheatear
I think its because you used router.push in useEffect itself
Oak rough bulletgall waspOP
Is that not recommended? Not sure how else I would go about this scenario.
Northern Wheatear
Basically you are trying to setup a redirect right?
Its best to do it server side😅
Actually can you try including router also in the useEffect's dependency array
Oak rough bulletgall waspOP
I did include router in the array and tried it, same thing. And yeah, pretty much redirect, but I think this may have to be done client side. I will see if I can do it in my server component.
Oak rough bulletgall waspOP
Actually not even sure how I would handle this in a server component without the user interacting.
Northern Wheatear
Actually you can get both the session details and page params server side
So its possible right?
Oak rough bulletgall waspOP
I know I can get them, but afaik useEffect is a client component. How would I handle auto redirecting if the param is not present?
I’m still not sure why I’m not supposed to be using router in useEffect?
Oak rough bulletgall waspOP
Yeah, didn’t work in server component when using redirect. Errors out hard. I’m wondering if this is an issue of not following best practice at this point. Everything I’ve tried has not worked.