Error message: Unable to destructure the 'q' property from 'req.query' due to its undefined value

I encountered a problem while working on a console project and attempting to create a handler for the GET method in Next.js 14:

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

Below is the code snippet from \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 });
    }
}

And this is the code snippet from \app\find\page:

Answer №1

After thorough investigation, I managed to troubleshoot the issue by opting for code designed for pages router rather than the 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", // Performing a case-insensitive search
            },
        },
    });
    return Response.json(products);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Expanding a JSON type in Typescript to accommodate interfaces

Expanding on discussions about passing interfaces to functions expecting JSON types in Typescript, this question delves into the complexities surrounding JSON TypeScript type. The scenario involves a JSONValue type that encompasses various data types like ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...

Exploring the possibilities of TypeScript/angularJS in HTTP GET requests

I am a beginner in typescript and angular.js, and I am facing difficulties with an http get request. I rely on DefinitelyTyped for angular's type definitions. This is what my controller code looks like: module game.Controller { 'use strict& ...

Dynamic class/interface in Typescript (using Angular)

Is there a way to achieve intellisense for an object created with a dynamic class by passing parameters? Here is the code snippet: Main: let ita: any = new DynamicClass('ITA'); let deu: any = new DynamicClass('DEU'); The DynamicClass ...

Master the Art of Scrolling Lists in Ionic 2

I am currently using Ionic2 for my project. One of the challenges I'm facing is scrolling to the top of a list when a specific event, called messageSend, occurs. Let me show you the code for this: <ion-content padding class="messages-page-conten ...

Using WebSockets in Angular 4

Currently in the process of developing a chat application using Angular 4 and WebSocket. I found guidance from this Angular WebSocket tutorial This is the source code for the WebsocketService: import { Injectable } from '@angular/core'; import ...

Looking for a way to configure webpack with typescript and style loaders for your project template

I recently set up a Vue project using Webpack and typescript, but I ran into some errors when trying to add a <template> element in my .vue file along with a <style> element that caused issues with my webpack watcher displaying errors. Below i ...

Angular Error: Potential security risk detected in resource URL context due to unsafe value being used

Hey there, I'm looking to display a dynamic pdf file. Initially, I encountered a CORS error, but managed to resolve it by using DOM Sanitizer. However, now I'm facing an issue with unsafe URLs. Any assistance would be greatly appreciated. Below ...

Encountered a problem when attempting to include a specialized heading on pages using next.js version

I'm encountering difficulties when attempting to add custom titles to my pages in my app. I am using Next.js version 13. Here is the code snippet: "use client"; export const metadata = { title: `Login - ${process.env.NEXT_PUBLIC_APP_NAME} ...

Discovering the optimum route within a 2D array given specific limitations using Dynamic Programming

Hey, I have a query related to dynamic programming (dp) that goes like this: Input: A 2D array of numbers Output: The maximum sum of a path from (0,0) to (n-1,n-1) with the following conditions: You can only move down and right i.e. from (A[i-1][j]) t ...

When is it advisable to utilize the strategy of Headless CMS coupled with a distinct frontend system?

I need to create a website with the following requirements: 10,000 views per month 5-6 different types of content posts 100-200 total entries numerous images the client will manage and update entries approximately once a week Up until now, I have been us ...

Retrieving information from a data file by implementing a GraphQL Apollo Server within a NextJS application route

Currently working with Next.js 14 (app route), React, and the GraphQL Apollo framework. I have a JSON file containing data saved locally that I'd like to display using the server API. How can I make this happen? Below is the JSON structure I need to r ...

What is the best way to mock a Typescript interface or type definition?

In my current project, I am working with Typescript on an AngularJS 1.X application. I make use of various Javascript libraries for different functionalities. While unit testing my code, I am interested in stubbing some dependencies using the Typings (inte ...

Is it feasible to access a service instance within a parameter decorator in nest.js?

I am looking to replicate the functionality of Spring framework in nest.js with a similar code snippet like this: @Controller('/test') class TestController { @Get() get(@Principal() principal: Principal) { } } After spending countless ho ...

JavaScript Tutorial: Adding Custom Metadata to PDFs

Does anyone know of a JavaScript package that can assist in adding custom metadata to a PDF file? ...

What is the best way to determine groupings for a Fluent UI DetailList in a Next.js application?

I'm currently in the process of learning react, and I've encountered an issue with utilizing SWR for fetching items from an API and displaying them in groups using fluentui's DetailedList. The problem arises when trying to collapse/uncollaps ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

How to override or redefine a TypeScript class with generics

Presently, I am immersed in a project involving three.js and TypeScript. It has come to my attention that for organizing elements, the Group class is highly recommended. However, I have noticed that the type definitions for Group do not include a feature l ...

Ways to improve the feedback for Typescript when dealing with the potential existence of a nested method

Recently encountered a critical bug that I believe could have been identified with the right TypeScript setup. Struggling to come up with a suitable title, so please bear with me. While initializing a widget app, similar to a chat app loaded by a parent a ...

Utilize PrimeNG's async pipe for lazy loading data efficiently

I have a significant amount of data (400,000 records) that I need to display in a PrimeNG data table. In order to prevent browser crashes, I am looking to implement lazy loading functionality for the table which allows the data to be loaded gradually. The ...