What is the method for acquiring a dynamic segment in the router of a Next.js 13 application?

Currently in my project, I am using the new App Router in Next.js 13 and MongoDB as the DBMS to fetch data via API. When trying to retrieve all data from a collection, it is successful. However, fetching only one data results in failure.

The error message received is:

TypeError: Cannot read properties of undefined (reading 'id')
    at GET (webpack-internal:///(sc_server)/./app/api/shop/[id]/route.tsx:14:30)
    // Additional lines of error messages...

Below is the code being used:

/app/api/shop/[id]/route.tsx

import { connectToDatabase } from "@/lib/mongo";
import { NextRequest, NextResponse } from "next/server";
import { ObjectId } from "mongodb";

export async function GET(req: NextRequest, res: NextResponse) {
  try {
    const id = req.query.id;
    const client = await connectToDatabase();
    const db = client.db("MyShopDB");
  
    const oneProduct = await db.collection("Products").findOne({ _id: ObjectId(id) });
  
    if(oneProduct)
      return NextResponse.json(oneProduct)
    else 
      return res.status(404).json({message: "Products Not Found"})
  } catch (error) {
    console.log(error);
    return new Response("Failed to fetch all prompts", { status: 500 })
  }
}

For fetching all products, you can refer to the following code:

/app/api/shop/route.tsx

import { connectToDatabase } from "@/lib/mongo";
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest, res: NextResponse) {
  try {
    const client = await connectToDatabase();
    const db = client.db("MyShopDB");

    const allProducts = await db.collection("Products").find().toArray();

    return NextResponse.json(allProducts);
  } catch (error) {
    return new Response("Failed to fetch all prompts", { status: 500 })
  }
}

Answer №1

The issue likely stems from attempting to access req.query.id, which is not valid within a dynamic API route in the app directory.

When working with dynamic segment routes inside the app folder, you can retrieve the dynamic parameter from the params property within the second parameter of your route handler function.

// `/app/api/shop/[id]/route.tsx`

import { type NextRequest } from 'next/server';

export async function GET(request: Request, { params }: { params: { id: string } }) {
    const id = params.id;
    console.log(id);
    // Implement the remaining logic of your API function
}

To learn more, refer to the Route Handlers, Dynamic Route Segments section in the documentation.

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

Optimizing Angular for requireJS deletion

We recently developed an Angular directive that utilizes blueimp-fileupload. Everything seems to be working fine until we decided to optimize our code using requireJs. After running the optimizer, we encountered the following error: Error: cannot call m ...

Update all Vue component imports to include the .vue extension at the end

The Vue CLI has decided to no longer support extensionless imports, causing compatibility issues with certain VS Code extensions like Vetur. In order to address this issue, I require all default component imports from a .vue file to include the file exten ...

Using THREE.js in the pre-render function

I am encountering difficulties with updating the positions of my enemies before rendering them. Instead of creating a separate update() function, I attempted to use an onBeforeRender() function attached to each enemy object. However, nothing seems to be ...

What is the correct way to add a library to webpack configuration?

Currently, I am working with Rails 6 and webpack in my project. I am interested in integrating the library jquery-textcomplete, but I am unsure about how to properly include it in the application.js file. Here are the steps I have taken so far: I instal ...

How can you determine the specific type of "display" utilized by CSS Bootstrap for a particular element?

When manipulating the "display" property of a bootstrap element like "row" or "col-md-3" using JavaScript, how can I determine the default value set by Bootstrap CSS? For instance, the Bootstrap source code likely sets the "display" value for the "row" cl ...

Tips for triggering a JavaScript function within WordPress using an inline function call

While setting up my plugin in the WordPress admin area, I encountered an issue with a form that stores user information. In my file input type, there is a JavaScript function call to my custom JavaScript that I have linked. Here is the line of code causing ...

Issue found: Passing a non-string value to the `ts.resolveTypeReferenceDirective` function

Encountering the following error: Module build failed (from ./node_modules/ts-loader/index.js): Error: Debug Failure. False expression: Non-string value passed to ts.resolveTypeReferenceDirective, likely by a wrapping package working with an outdated res ...

Exploring the World of NoSQL and Mongoose: Crafting Innovative

In my personal project, I focus on writing articles using NoSQL with Mongoose. My API is built with Node.js + Express, but I am more comfortable with SQL and still a beginner in NoSQL... My main issue revolves around organizing my articles into categories ...

What is the process for transferring an image from the main page to another?

For days, I have been searching for an answer without any luck. It seems that I just can't wrap my head around it and apply it to what I am working on. Currently, I am using PHP to store images on the server when a user hits submit. My goal is to dis ...

Contrasting WebSQL and SQLite in terms of their utility in mobile applications and web browsers

Could you confirm if WebSQL and SQLite are the same? Are both WebSQL and SQLite available in PhoneGap? Will the JavaScript code used for WebSQL in a web browser be the same for a mobile app, or will we need different code? What advantages does WebSQL ha ...

Is there a way to determine if a website is utilizing javascript?

Currently, I am in the process of developing a web scraping tool using beautifulsoup. Some of the websites I am targeting contain JavaScript elements that prevent me from using urllib3 efficiently. As a workaround, I have incorporated selenium into my sc ...

Searching for JSON data in JavaScript

Is there a more efficient approach for searching data in JSON other than using loops? This is specifically for editing and deleting purposes. for(var k in objJsonResp) { if (objJsonResp[k].txtId == id) { if (action == 'delete') { obj ...

Attempting to generate a nested array structure in order to produce a JSON object for output

I am currently working on a JavaScript script that interacts with the Netsuite ERP platform to retrieve data. Currently, the script is returning data in an array format, specifically product information. While this is functional, I would prefer it to retu ...

Menu is not functioning properly as it is not staying fixed in place

I am trying to create a fixed menu that sticks to the browser window as it scrolls. However, I am encountering an issue where the transition from sticky to fixed is not smooth when I remove position: relative; from navbar__box. window.onscroll = functio ...

Distinguishing between creating controllers in AngularJS

I am a beginner in the world of AngularJS and I have come across two different examples when it comes to creating a controller. However, the one that is more commonly used doesn't seem to be working for me. The problem with the first example is that ...

Guide to displaying radio button value when updating a record

When updating a record in Node.js, I encounter an issue where the values for text input fields are rendered correctly, but the values for radio buttons and textarea in the update form do not appear. Can someone please advise on how to implement this? I am ...

Instructions on adding a class to the parent element when the child has a particular class

Here is the html structure I am working with: <section> <div class="v-middle"> <div class="row"> <h5 class="heading">Heading goes here</h5> </div> </div> </section> ...

Utilize React Material UI to elegantly envelop your TableRows

Currently, I am faced with a challenge involving a table that utilizes Material UI and React-table. My goal is to wrap text within the TableRow element, but all my attempts have not been successful so far. Is there anyone who knows the best approach to a ...

Is it possible to have the Target='_blank' attribute open the link in a new window instead of a new tab?

Is there a way to achieve this? When using Firefox, the link opens in a new tab, which I prefer to avoid users having to adjust settings in their browsers. I am looking for a solution where a pop-up contact form appears whenever a user clicks on 'co ...

Harness the power of React Material-UI with pure javascript styling

I am currently attempting to implement Material-UI in pure javascript without the use of babel, modules, jsx, or similar tools. <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8 ...