Next.js Discord

Discord Forum

How to use req.query?.id

Answered
Waterman posted this in #help-forum
Open in Discord
I get this error when trying to use query as in the tutorial but I suspect it might be outdated

Error:
Property 'query' does not exist on type 'Request'

I am not sure that this:
  const pathname = usePathname();
  const parts = pathname.split("/");
  const id = parts[parts.length - 1];
  console.log(id);

Is the best way of doing it either, so would be great with some tips

app/basprodukter/redigera/[...]/page.tsx:
"use client";

import BaseLayout from "@/components/baselayout";
import axios from "axios";
import { usePathname } from "next/navigation";
import { useEffect } from "react";

export default function page() {
  const pathname = usePathname();
  const parts = pathname.split("/");
  const id = parts[parts.length - 1];
  console.log(id);

  useEffect(() => {
    if (!id) {
      return;
    }
    axios.get("/api/basproducts?id=" + id).then((response) => {
      console.log(response.data);
    });
  }, [id]);

  return <BaseLayout>rediger produkt</BaseLayout>;
}


app/api/basproducts/route.js:

export const GET = async (req: Request, res: Response) => {
  const { method } = req;

  await mongooseConnect();
  if (method === "GET") {
    if (req.query?.id) {   "<<<<---error---Property 'query' does not exist on type 'Request'"
      return NextResponse.json(await BasProdukt.findOne({ _id: req.query.id }));
    }
  }
};
Answered by Asiatic Lion
welcome
View full answer

9 Replies

the get function should also only have one parameter, which is the request
the response doesnt need to be there
oh okay thanks, do you think you could modify my code just a little in order for me to understand a little better how to do it
would be very nice
Asiatic Lion
export const GET = async (request: Request) => {
  const queryId = request.nextUrl.searchParams.get('id');
  await mongooseConnect();
  if (queryId) {
    return NextResponse.json(await BasProdukt.findOne({ _id: queryId }));
  } else {
    return NextResponse.json({ error: 'No Id' })
  }
};
the function only works for get requests so no point to add the extra if statement
oh okay thats true, thanks alot man
Asiatic Lion
welcome
Answer