Next.js Discord

Discord Forum

Dynamic route handling with params on server side

Answered
Maine Coon posted this in #help-forum
Open in Discord
Maine CoonOP
Hello guys,

I have the following structure:
'api/user/[id]/orders/[orderId]/route.ts'
How can i get the orderId as params inside api route?

When I try console.log(params.orderId) I always got the slug of id instead of the orderId.
export async function GET( req: NextRequest, { params }: { params: { orderId: string } } ) { console.log(params.orderId); return NextResponse.json( { message: `OrderId: ${params.orderId} has not found` }, { status: 404 } ); }
Answered by Maine Coon
oh I see, i try go get id instead of orderId
View full answer

65 Replies

@Ray what do you see with this ts console.log(params);
Maine CoonOP
{ id: 'undefined', orderId: '107260973032197099699' }
@Maine Coon { id: 'undefined', orderId: '107260973032197099699' }
how do you access this url?
@Maine Coon { id: 'undefined', orderId: '107260973032197099699' }
look like you are accessing to /api/user/undefined/orders/107260973032197099699
try go to /api/user/1/orders/2 with browser
@Ray how do you access this url?
Maine CoonOP
the URL is fine, i see the right user id and right order id on the browser, but somehow the API does not get it
@Ray try go to `/api/user/1/orders/2` with browser
Maine CoonOP
I can see the following in the browser when I hit your suggestion: {"message":"OrderId: 2 has not found"}
wait what are you trying to do?
@Maine Coon { id: 'undefined', orderId: '107260973032197099699' }
do you mean 107260973032197099699 should be the id?
Maine CoonOP
yes it should be the id
but on the console I see { id: '1', orderId: '2' }
@Maine Coon { id: 'undefined', orderId: '107260973032197099699' }
how did you get this? check the url there
Maine CoonOP
http://localhost:3000/user/107260973032197099699/orders/clr7jouj4000vaiakszjydw6r
shoudn't it be http://localhost:3000/api/user/107260973032197099699/orders/clr7jouj4000vaiakszjydw6r?
Maine CoonOP
if i hit the api url directly than i get the right response
@Ray shoudn't it be `http://localhost:3000/api/user/107260973032197099699/orders/clr7jouj4000vaiakszjydw6r`?
Maine CoonOP
yes I use this to get the api response and the response is correct: { id: '107260973032197099699', orderId: 'clr7jouj4000vaiakszjydw6r' }
@Maine Coon if i hit the api url directly than i get the right response
yea so how do you access the api and get the wrong one?
Maine CoonOP
the interesting is that I get the right url: http://localhost:3000/user/107260973032197099699/orders/clr7jouj4000vaiakszjydw6r however the API respnse wrong
im a little bit confused
I think it should be http://localhost:3000/api/user/107260973032197099699/orders/clr7jouj4000vaiakszjydw6r?
do you have two route at
user/[id]/orders/[orderId]/route.ts
and
api/user/[id]/orders/[orderId]/route.ts
Maine CoonOP
user/[id]/orders/[orderId]/page.tsx and api/user/[id]/orders/[orderId]/route.ts
page.tsx try to fetch data from route.ts
so the one inside api is working fine?
Maine CoonOP
yes it seems fine the api route.ts
the page.tsx also seems ok in the browser, I see the correct url link
but when the page.tsx try to fetch data from api route, the params are wrong
could you show the code on the page.tsx?
Maine CoonOP
'use client';

//...imports ....

const OrderItem = ({ order }: OrderItemProps) => {
 
//.......some content ....

  return (
    <div className="flex flex-col items-center gap-3 md:flex-row md:justify-center">
      <OrderTableContentWrapper>{order.id}</OrderTableContentWrapper>
      <OrderTableContentWrapper className="md:w-[200px]">
        {format(new Date(order.createdAt), 'hh:mmaaa MMM do, yyyy')}
      </OrderTableContentWrapper>
      <OrderTableContentWrapper className="md:w-24">
        {formattedTotalCartPrice}
      </OrderTableContentWrapper>
      <OrderTableContentWrapper className="flex flex-row justify-center md:w-20">
        <div
          className={cn(
            'w-20 rounded-sm p-1 text-center text-sm text-white',
            {
              'bg-red-600': !order.paid,
              'bg-green-600': order.paid
            }
          )}
        >
          {order.paid ? 'Paid' : 'Not Paid'}
        </div>
      </OrderTableContentWrapper>
      <OrderTableContentWrapper className="flex flex-row justify-center md:w-24">
        <Link
          href={`/user/${order.userId}/orders/${order.id}`}
          className={cn(
            buttonVariants({ variant: 'outline', size: 'sm' }),
            'rounded-xl'
          )}
        >
          Details
        </Link>
      </OrderTableContentWrapper>
    </div>
  );
};

export default OrderItem;
Maine CoonOP
sorry I missunderstood, it is the page.tsx where I reach the .../orders/[orderId]/page.tsx
'use client';

//..imports

const OrderId = ({ params }: { params: { id: string } }) => {

//...useState

  const { id } = params;

  const { status, data: session } = useSession();


  const fetchData = async () => {
    try {
      setIsLoading(true);
      const response = await fetch(
        `/api/user/${session?.user.id}/orders/${id}`,
        {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json'
          },
          cache: 'no-cache'
        }
      );

      if (response.ok) {
        const data: OrderProps = await response.json();
        console.log(data.order);
        // setOrder(data);
      } else {
        setIsError(true);
        toast.error('An unexpected error occurred');
      }
      setIsLoading(false);
    } catch (error) {
      setIsError(true);
      toast.error('An unexpected error is occured');
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  if (status === 'loading') {
    return (
      <div className="m-auto mt-20">
        <Loading />
      </div>
    );
  }

  return <div>OrderId</div>;
};

export default OrderId;
Maine CoonOP
oh I see, i try go get id instead of orderId
Answer
yep
Maine CoonOP
thank you very much to guided me
can i give you star or feedback somehow?
@Maine Coon can i give you star or feedback somehow?
no prob, yeah you could do that in #kudos
Maine CoonOP
is it ok?
sure 😆
Maine CoonOP
i just waited some feedback that you have xy kudos or something from discort like other forums but nothing happend 😄
thank you again
have a nice day
you too😀
Maine CoonOP
I would reopen this, because something went wrong
@Ray can you help?
I would like to get the params prop on /api/user/[id]/orders/route.ts but the params is undefined
I have /api/user/[id]/orders/[orderId]/route.ts, inside route.ts I can get params for both [id] and [orderId] also
@Maine Coon I would like to get the params prop on /api/user/[id]/orders/route.ts but the params is undefined
where are you sending request to /api/user/[id]/orders/route.ts?
Maine CoonOP
now i just try from browser url directly to test api
I meant where you made the request and you get undefined on the route.ts?
Maine CoonOP
yes on route.ts
most likely it is sending the /api/user/undefined/orders
@Maine Coon yes on route.ts
wdym? I think you should have a client component to make request to the api route?
Maine CoonOP
yes you are right, i just want to follow the same method as yesterday, test the API directly, I can use postman also but now it is not necessary, therefore I use browser and hit the right url directly
http://localhost:3000/api/user/clr95k09k00007ggz6w8zgpmc/orders
this is the url, the params is undefined when I console.log it
@Maine Coon this is the url, the params is undefined when I console.log it
could you show the code on /api/user/[id]/orders/route.ts
Maine CoonOP
import { NextResponse } from 'next/server';
import prisma from '../../../../../../prisma/client';

export const revalidate = 0;

export async function GET({ params }: { params: { id: string } }) {
  console.log('params:', params);
  try {
    const orderListbyUserId = await prisma.order.findMany({
      where: {
        userId: params.id
      },
      orderBy: {
        createdAt: 'desc'
      },
      include: {
        user: true,
        cartItems: {
          include: {
            menu: true // Include Menu details within cartItems
          }
        }
      }
    });

    return NextResponse.json(
      {
        orderList: orderListbyUserId,
        message: `All orders to userId: ${params.id} are returned`
      },
      { status: 200 }
    );
  } catch (error) {
    return NextResponse.json(
      {
        message: error
      },
      { status: 500 }
    );
  }
}
Maine CoonOP
does it mean I have to use req as function argument independently of it is used inside the code or not?
becaues it works now
I did not get any error which shows this missing argument
@Maine Coon does it mean I have to use req as function argument independently of it is used inside the code or not?
you can ignore it if you don't need it but you can't skip it
Maine CoonOP
hm I did not know it is a must and not an optional, thank you very much again, I give kudo 🙂