Next.js Discord

Discord Forum

Dynamic API Route handler

Answered
Cape horse mackerel posted this in #help-forum
Open in Discord
Cape horse mackerelOP
Hi all. I have an API that should be able to GET and DELETE some products.
I've made API and it looks like
// products/[id]/route.ts
import prismadb from '@/lib/prismadb';
import { auth } from '@clerk/nextjs';
import { NextApiRequest } from 'next';
import { NextResponse } from 'next/server';

const allowedMethods = ['GET'];

const handler = async (req: NextApiRequest) => {
  try {
    if (!allowedMethods.includes(req.method!) || req.method === 'OPTIONS') {
      return NextResponse.json(`Method ${req.method} not allowed`, { status: 405 });
    }

    const { userId } = auth();
    if (!userId) return NextResponse.json('Unauthorized', { status: 401 });

    if (!req.query.id) return NextResponse.json('Product id is missing', { status: 400 });

    if (req.method === 'GET') {
      const product = await prismadb.product.findFirst({
        where: {
          id: req.query.id as string,
        },
      });

      return NextResponse.json(product);
    }
  } catch (error) {
    console.log('Server error', error);
    return NextResponse.json('Server error', { status: 500 });
  }
};

export { handler as GET };

but it's not working, I'm getting 500 server error. What am I doing wrong?
Answered by aardani
You can extract params from the second parameter of the route
View full answer

9 Replies

Im guessing you didnt export handler as DELETE too
Cape horse mackerelOP
nope, now it's working. I was doing GET request to /api/products/someId
and was extracting someId from req.query.id
Allright glad it worked for you
Cape horse mackerelOP
but in order to do it with req.query.id how should I send request?
/api/product?id=someId ?
You can extract params from the second parameter of the route
Answer
If you have created route.ts in /api/product/[id]/route.ts then you can extract id from the context parameter
Cape horse mackerelOP
oh, now I see, Thanks man 👌🏻