Next.js Discord

Discord Forum

Nested API Route..

Answered
Horned oak gall posted this in #help-forum
Open in Discord
Horned oak gallOP
My structure is as:

api/
  user/
    [user]/
      - route.ts
    details/
      - route.ts


I'd like to go to /api/user/foo/details. User route would query the database for user data and the details route would query detail data about the user.

- How do I take the data from both of these routes into one response back to the fetch?
Answered by aardani
better to just use the DRY method to refactor the code
View full answer

14 Replies

/api/user/foo/details would give you 404 | not found
you can just write the same thing in /api/user/foo/route.ts into /api/user/foo/details/route.ts
then return them in /api/user/foo/details/route.ts
Horned oak gallOP
So, potentially, there will be additional routes under [user] and I'd like for each one of them to fetch specific data.
api/
  user/
    [user]/
      - route.ts
      details/
        - route.ts

you meant like this?
routes don't get nested so for now just rewrite the route from [user] and merge the data :/
Horned oak gallOP
For instance, there could be
api/
  user/
    [user]/
      - route.ts
      details/
        - route.ts
      posts/
        - route.ts
      comments/
        - route.ts


I still want [user] to get data, but then depending on the route called, it would fetch that data too.

So, if /api/user/foo/posts/ is called, [user] gets data, posts gets data, concatenate into one object and return the one object.
yes
you can just extract the logic in [user]/route.ts and reuse them in all the child routes
Horned oak gallOP
Ehh.. Now that I'm thinking about this, I wonder if I can use a builder pattern..
Im sure you can 😁
we're trying to avoid having to fetch your own api inside the api which is uneccesary round trips and inefficient
better to just use the DRY method to refactor the code
Answer
Horned oak gallOP
Yeah... Trying to be too fancy, I suppose.