Unspecified parameter for Next.js dynamic route

Currently, I am developing an e-commerce application using next.js with Typescript and MongoDB. To better understand my project, let's take a look at my existing file structure:

https://i.stack.imgur.com/tZqVm.png

The mainPage.tsx file is responsible for rendering all products in card format. By utilizing products.map and Link, each product is linked to its respective product page as shown below:

          {products.map((product: ProductModel) => (
            <Link
              key={product._id.toString()}
              href={{
                pathname: "/product",
                query: {
                  id: `${product._id.toString()}`,
                },
              }}
            >
              <CategoryCard product={product} />
            </Link>
          ))}

In the product/page.tsx file, I extract the id from searchParams and establish that it functions correctly up to this point. However, during the product fetching process here:

const { product } = await getProduct(searchParams.id);

An error occurs displaying "Error fetching product details of product id {searchParams.id}" on the page. Below is a snippet of the file:

const getProduct = async (id: string) => {
  try {
    const res = await fetch(
      `http://localhost:3000/api/singleproduct?id=${id}`,
      {
        cache: "no-cache",
      }
    );

    if (!res.ok) {
      throw new Error(`Failed to fetch product with id ${id}`);
    }

    return res.json();
  } catch (err) {
    console.error("Error fetching product:", err);
    throw err;
  }
};

const ProductPage = async ({
  searchParams,
}: {
  searchParams: { id: string };
}) => {
  console.log("This is the id: ", searchParams.id);

  try {
    const { product } = await getProduct(searchParams.id);

    return <div>This is a {product.product_title}</div>;
  } catch (error) {
    console.error("Error fetching product:", error);
    return (
      <div>Error fetching product details of product id {searchParams.id}</div>
    );
  }
};

export default ProductPage;

The issue possibly originates from the api/singleproduct/route.tsx file. Let's examine the code snippet:

import Product from "../../models/Product";
import { NextResponse } from "next/server";
import { NextApiRequest, NextApiResponse } from "next";

export async function GET(req: NextApiRequest, res: NextApiResponse) {
  console.log("Query parameters:", req.query);
  const id = req.query.id as string;
  console.log("this is the id:", id);

  try {
    if (!id) {
      throw new Error("ID parameter is missing.");
    }

    console.log("This is the id:", id);
    const product = await Product.findById(id);

    if (!product) {
      return NextResponse.json({ error: "Product not found" }, { status: 404 });
    }

    console.log("Product from MongoDB:", product);
    return NextResponse.json({ product }, { status: 200 });
  } catch (error) {
    console.log("Something broke:", error);
    return NextResponse.json({ message: "GET request failed.", error });
  }
}

Upon analysis, the console outputs "Query parameters: undefined" along with the error "TypeError: Cannot read properties of undefined (reading 'id')". How can I resolve this issue? Your guidance is greatly appreciated.

Answer №1

To solve this issue, simply modify NextApiRequest to NextRequest.

To implement this change in your code base for the file api/singleProduct/route.tsx, include the following line:

import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest, res: NextResponse) {
    ...
    // Retrieve the search parameter value for "id" (/api/singleProduct?id=12345)
    const productId = req.nextUrl.searchParams.get("id");
    ...
}

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

Accessing the state from a child functional component and then adding it to an array of objects in the parent component

I'm facing a challenge with a parent component that needs to manage the data of its child components stored in an array of objects. My goal is to add new child components and maintain their information within the parent's state as an array of obj ...

Why is Next.js trying to connect to the database while initializing PrismaClient during the build process?

When attempting to build my nextjs application (npm run build), I noticed that the database is being requested during the build process on certain routes where I expect to dynamically query data. However, since the database is not available or live in my b ...

Exploring Angular 4's capability: Incorporating data from Http Post Response into a .js file or highchart

I'm a beginner with Angular 4. I'm trying to create a dashboard that pulls data from an Http Post Response and I want to use this data to create a Chart (Highchart). I have successfully received the response in the console.log and formatted it i ...

Uncovering the Image Orientation in Angular: Is it Possible to Determine the Direction Post-view or Upon Retrieval from Database?

I am currently working on creating centered and cropped thumbnails for images retrieved from a database. I came across some helpful information on how to achieve this: The resource I found is written for JavaScript, but I am using Angular 7. I am facing d ...

Is it necessary to conceal Angular navigation controls when the user is not authenticated?

In Angular, is there a standardized method for hiding controls when the user is not logged in? We already have the CanActivate guard which checks if a user can access a route. Would it be better to hide the route initially if the user is not logged in or l ...

Typescript and Mongoose Schema - Common Design Mistakes

I am encountering two issues while defining a schema using mongoose and typescript. Below is the code snippet I'm having trouble with: import { Document, Schema, Model, model} from "mongoose"; export interface IApplication { id: number; name ...

The functionality of the String prototype is operational in web browsers, but it encounters issues

Version: 8.1.0 The prototype I am working with is as follows: String.prototype.toSlug = function () { return (<string>this) .trim() .toLowerCase() .replace(/\s+/g, '-') .replace(/[^\w\-]+/g, '') ...

Unlocking rotation on a single screen in a react native application can be achieved by altering

I attempted to use react-native-orientation within a webview in order to make it the only view that would rotate. import React, {useEffect} from 'react'; import { WebView } from 'react-native-webview'; import Orientation from "react-na ...

Creating dynamic pages with Next.js/Vercel can be quite sluggish

I am currently working with Next.js and hosting my project on Vercel. The website is powered by WordPress, which provides the data headlessly. Due to the large number of pages, I only generate a few during the build process (the first three for pagination) ...

What is the cause of the error message "property 'map' is undefined"?

I am currently working on a service that looks like this: public getUsers() { return this.httpClient.get(environment.BASE_URL + `api/all`); } In my component, I have implemented the ngx-bootstrap table to display the user data. import { Component, OnI ...

How can I secure my website routes for authenticated users using NextAuth in Next.js?

Ensuring that all routes on my NextJs website are protected for authenticated users with NextAuth, except the login route which should be accessible without authentication, posed a challenge. I attempted to create a middleware to validate user tokens and r ...

There is no corresponding index signature for type 'string' in Type

This is the code snippet I am using as a reference: const MyArray = [ { name: "Alice", age: 15 }, { name: "Bob", age: 23 }, { name: "Eve", age: 38 }, ]; type Name = typeof MyArray[string]["name"]; //throws err ...

What is the expected return type in TypeScript of a function that returns a void function?

I recently received feedback during a code review suggesting that I add return type values to my functions. However, I am unsure of what return type to assign to this particular function: function mysteryTypeFunction(): mysteryType { return function() ...

What could be causing the issue with typing into the Formik and Yup input fields?

Whenever I attempt to enter text into the input fields, no characters show up. Strangely, a similar login page using the same code is functioning perfectly fine. At this moment, I'm baffled as to why it isn't working on this specific one. My susp ...

React Redux Bundle with Hot Reload Feature

Working on a project written in TypeScript with the React and Redux framework, I'm familiar with webpack and its middleware libraries for hot reloading. My question arises when considering how my TypeScript code is first converted to JSX through gulp ...

I'm looking to receive the specific data types for express request arguments. How can I

Currently, I am working on incorporating authentication into an express application using passport and typescript. For defining the user model, I have utilized typegoose. Once the login request passes through the passport strategy, a login method is called ...

Deliver transcluded data to the descendant element of a hierarchical roster

I understand that there have been similar questions asked before, but my situation is slightly different. I am currently constructing a nested list and I want to include custom HTML content in each grandchild element alongside some common HTML. The problem ...

The Next.js server starts up for a moment before abruptly shutting down

When I run next dev, the server starts momentarily and then closes down. > next dev ready - started server on 0.0.0.0:3000, url: http://localhost:3000 and then it shuts off. I'm using Windows and you can see a screenshot of my CLI here I ran this ...

Having trouble implementing catchError in a unit test for an HttpInterceptor in Angular 11

I am facing challenges in completing a unit test for my HttpInterceptor. The interceptor serves as a global error handler and is set to trigger on catchError(httpResponseError). While the interceptor functions perfectly fine on my website, I am struggling ...

Next JS BlockNote Modifications onUpdate

Whenever I input "/" the component continuously re-renders as I try to type, rendering it completely unusable. File A: const update = useMutation(api.documents.updateDocument); const onChange = (content: string) => { update({ id: params.d ...