Sachin
Sachin

Reputation: 582

NextJS 14 - Optional Catch-all Segments dynamic routing not working for optional first slug pattern

While I am trying to create dynamic routing for route pattern

/category1?/category2?/category3?/category4?/c/categoryId

Here category1 to category4 are optional in route but after that /c/categoryId is fixed.

As a solution I had tried optional catch-all-segments

- [[...category]]
------- c
-----------[categoryId]
---------------- page.tsx

But I get an error

[Error: Invalid segment Dynamic("categoryId"), catch all segment must be the last segment (segments: [OptionalCatchAll("category")])

Looks like fix slug can't be placed after a optional route segment.

Is there any way to achieve this URL pattern where optional slugs can be placed before fixed slug part.

enter image description here

enter image description here

Thanks in advance for your time and knowledge sharing.

Upvotes: 2

Views: 1218

Answers (1)

WKD
WKD

Reputation: 11

I think you should go only for the catch all [[...category]].

Then on the page.tsx of that [[...category]] segment, do the necessary checks to resolve the path. By that I mean checking how many category1/category2... you have and which one they are, knowing the last 2 will be your c/:categoryId.

It's actually easier than you might think. I've done it for a website builder I'm working on. I basically have a [[...website]] segment to manage the websites created by my users and a single page.tsx inside it handles all the different pages one of these websites can have. No need to go for crazy patterns for the file-based routing. Just use the proper checks on that page.tsx and return the Page Content accordingly.

Given how the routing of a Next app works, I don't see a future where they let us go for patterns like the one you tried.

Upvotes: 1

Related Questions