TypeError: Cannot destructure property 'q' of 'req.query' as it is undefined

171 views Asked by At

I had this issue on console when I tried to make handler for GET in nextjs 14: TypeError: Cannot destructure property 'q' of 'req.query' as it is undefined.

here’s my code in \api\find\route:

import { PrismaClient } from "@prisma/client";
import { NextApiRequest, NextApiResponse } from "next";
import { useRouter } from "next/router";
import { NextRequest, NextResponse } from "next/server";

const prisma = new PrismaClient();
export async function GET(req: NextApiRequest, res: NextApiResponse) {
    const { query } = useRouter();
    try {
        const { q: query } = req.query;
        if (typeof query !== "string") {
            throw new Error("Invalid request");
        }
        const products = await prisma.productCN.findMany({
            where: {
                title: {
                    contains: query,
                    mode: "insensitive",
                },
            },
        });
        return NextResponse.json({ products });
    } catch (error) {
        console.log(error);
        return NextResponse.json({ message: error });
    }
}

here’s my code in \app\find\page:

1

There are 1 answers

0
Mirasayon On

I found how to resolve it, I just used code for pages router instead of app router:

import { PrismaClient } from "@prisma/client";
import { NextRequest, NextResponse } from "next/server";
const prisma = new PrismaClient();
export async function GET(request: NextRequest, response: NextResponse) {
    const searchParams = request.nextUrl.searchParams;
    const query = searchParams.get("query");
    if (typeof query !== "string") {
        throw new Error("Invalid request");
    }
    const products = await prisma.productCN.findMany({
        where: {
            title: {
                contains: query,
                mode: "insensitive", // Case-insensitive search
            },
        },
    });
    return Response.json(products);
}