Skip to content

Nested API Routes which include ids #96

Answered by lazarv
mrose asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @mrose!

Your directory structure needs to look like this to handle comments on a post with an id route parameter:

.
└── api
    └── posts
        └── [id]
            └── comments.server.ts

In your comments.server.ts, you can access the params on the request:

export async function GET({
  request: {
    params: { id },
  },
}: {
  request: { params: { id: string } };
}) {
  return new Response(`Post #${id}`);
}

To get the request body, you need to use the web standard implementation to read request stream as a JSON:

export async function POST({ request }: { request: Request }) {
  const body = await request.json();
  return new Response(`Comment data: ${JSON.stringify(body)}`);
}

I wi…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by mrose
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants