Next.js Discord

Discord Forum

Dynamic Routes Nex.js

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
I'm trying to create a dynamic route for messages based on the senderId, but I don't seem to be doing it correctly, this api is simply returning all messages from the database, instead of only returning messages from a specific senderId (http://localhost:3000/api/messages?senderId=29). I'm using Next.js 13 with the App Route directory. This is the dynamic route that I created api/messages/[messageId]/route.ts in this case the api to retrieve my messages through senderId is present inside [messageId] . Below is my api and my model


model Message { id Int @id @default(autoincrement()) senderId Int content String imageUrl String? createdAt DateTime @default(now()) sender User @relation(fields: [senderId], references: [id]) }

import { db as prisma } from "@/lib/db";

export async function GET(
  request: Request,
  context: { params: { senderId: number } }
) {
  try {
    const senderId = Number(context.params.senderId);

    const userMessages = await prisma.message.findMany({
      where: {
        senderId: {
          equals: senderId,
        },
      },
    });

    if (!userMessages || userMessages.length === 0) {
      return new Response(
        JSON.stringify({ message: "Mensagens não encontradas" }),
        { status: 400 }
      );
    }

    return new Response(JSON.stringify(userMessages), { status: 200 });
  } catch (error) {
    console.error("Erro ao buscar mensagens:", error);
    return new Response(
      JSON.stringify({ message: "Erro ao buscar mensagens" }),
      {
        status: 500,
      }
    );
  }
}

10 Replies

I wonder if it's something with converting the param to Number()? If you console log senderId what does it give you?
@Spectacled bear I'm trying to create a dynamic route for messages based on the senderId, but I don't seem to be doing it correctly, this api is simply returning all messages from the database, instead of only returning messages from a specific senderId (http://localhost:3000/api/messages?senderId=29). I'm using Next.js 13 with the App Route directory. This is the dynamic route that I created api/messages/[messageId]/route.ts in this case the api to retrieve my messages through senderId is present inside [messageId] . Below is my api and my model `model Message { id Int @id @default(autoincrement()) senderId Int content String imageUrl String? createdAt DateTime @default(now()) sender User @relation(fields: [senderId], references: [id]) }` javascript import { db as prisma } from "@/lib/db"; export async function GET( request: Request, context: { params: { senderId: number } } ) { try { const senderId = Number(context.params.senderId); const userMessages = await prisma.message.findMany({ where: { senderId: { equals: senderId, }, }, }); if (!userMessages || userMessages.length === 0) { return new Response( JSON.stringify({ message: "Mensagens não encontradas" }), { status: 400 } ); } return new Response(JSON.stringify(userMessages), { status: 200 }); } catch (error) { console.error("Erro ao buscar mensagens:", error); return new Response( JSON.stringify({ message: "Erro ao buscar mensagens" }), { status: 500, } ); } }
I think you should do /api/messages/29 instead of /api/messages?senderId=29
Former is dynamic segment params latter is search (query) params
@Marchy I wonder if it's something with converting the param to `Number()`? If you console log senderId what does it give you?
Spectacled bearOP
In this case I'm just ensuring that my senderId is of type number, as the api expects to receive this type
@joulev I think you should do /api/messages/29 instead of /api/messages?senderId=29
Spectacled bearOP
when doing this my error conditional is executed

http://localhost:3000/api/messages/29
@Spectacled bear when doing this my error conditional is executed http://localhost:3000/api/messages/29
Well so the dynamic route part is working, you just have to check the error and fix it
You most likely have api/messages/route.ts whose GET returns all messages unfiltered, leading to the original questkon
Now it’s no longer a routing thing just a logic bug, time to fix
@Spectacled bear In this case I'm just ensuring that my senderId is of type number, as the api expects to receive this type
btw - this would cause the value of senderId to be NaN and wouldn't reject the query. It'd pass NaN to your query
Might want to use parseInt with a radix there as well