Optional dynamic route
Unanswered
Temminck's Stint posted this in #help-forum
Temminck's StintOP
Hi, I am building an app where a user can have personal space and a space with team members. I want the url to be either
localhost:3000/board
or localhost:3000/[teamName]/board
. Can the [teamName] be optional? I do not want to repeat files14 Replies
yes it can be optional when using queryParams. So you have one route
localhost:3000/board
and when you need the teamname with it you go to localhost:3000/board?teamName=someName
Temminck's StintOP
Not quite the url structure I want. Seems like this is currently not possible without duplicating files
Thanks for your help
Maybe I read your issue wrong. I thought the url should be in the format of
localhost:3000/board
?I want the url to be either localhost:3000/board
Yucatan Vireo
So you would like a route structure like
I don't think doing what you want is possible in Next.js, but I am curious if anyone knows otherwise.
/user/[username]/[view]
where the [view]
string is treated as state and not associated with a page.tsx
or layout.tsx
? searchParams achieves the same thing, but is aesthetically different. One option is to create a layout at [username] and a page at [view] but this is not a good solution in many cases.I don't think doing what you want is possible in Next.js, but I am curious if anyone knows otherwise.
Additionally, you could use a page at
/board
that redirects to a default team at /[team]/board
... (I imagine the current user's team or something)What's so bad about using a searchParams? Among other things, they are also made for this
Yucatan Vireo
I believe wanting a url structure like this is primarily for aesthetics and ease-of-construction. Search params are exactly for this.
Yucatan Vireo
Also, when one uses a URL structure like this, they are deliberately choosing one param as having the highest importance and should become a route segment. You may still use search params in this case, like
/user/$username/posts?sortedBy=age
or /user/$username/collections?filter=abcxyz&search=helloworld
which semantically I feel is appealing because it is clear which param is the most important: the route segment.Well.. we don't know when OP is not talking with us
Yucatan Vireo
Ok, so I forgot catch-all segments exist & can be used but only for subsequence segments.
https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes#catch-all-segments
https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes#catch-all-segments
yea.. all these things exists. However if OP is not talking to us he won't get a suitable solution
Temminck's StintOP
Hi sorry. Academics take away time. It is true its purely for aesthetics. But its also not a viable solution. I went with having a username instead for the user and team name for team and keeping the route structure the same for both
So the structure will always be /[username or team]/board