Encountering a 404 error with Next.js 13 dynamic routing

Whenever I click on an item, it redirects to the dynamic route "http://localhost:3000/products/{id}" but instead of displaying the data, I get an error.

Here is my file structure:

  • app
    • components
      • Product.js
    • pages
      • Products
        • [id].js
    • layout.js
    • page.js

[id].js

const ProductDetail = () => {
  const router = useRouter();
  const { id } = router.query;
  const [product, setProduct] = useState(null);

  useEffect(() => {
    if (id) {
      fetch(`https://fakestoreapi.com/products/${id}`)
        .then((response) => {
          if (!response.ok) {
            throw new Error('Failed to fetch product');
          }
          return response.json();
        })
        .then((data) => setProduct(data))
        .catch((error) => console.error(error));
    }
  }, [id]);

  if (!product) {
    return <p>Loading...</p>;
  }

  return (
    <div>
      <h1 className="text-3xl font-bold text-center my-4">{product.title}</h1>
      <div className="flex justify-center">
        <img
          src={product.image}
          alt={product.title}
          className="mx-auto w-64 h-64"
        />
      </div>
      <p className="text-lg font-semibold mt-2 text-center">${product.price}</p>
    </div>
  );
};

export default ProductDetail;

Product.js

const Product = ({ product: { image, title, price, id } }) => {
  return (
    <div>
      <Link href={`/products/${id}`}>
        <div className="product-card">
          <h1>Product</h1>
          <img 
            src={image}
            width={250}
            height={250}
            className="product-image"
          />
          <p className="product-name">{title}</p>
          <p className="product-price">₹{price}</p>
        </div>
      </Link>
    </div>
  )
}

page.js

"use client";
const Home = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    fetch('https://fakestoreapi.com/products')
      .then((response) => response.json())
      .then((data) => setProducts(data));
  }, []);

  return (
<>
     <div className="products-container">
      {products?.map((product) => <Product key={product.id} product={product} />}  
    </div>
</>
  );
};
export default Home;

I have attempted changing the folders for dynamic [id] and Product but without any success.

Answer №1

It appears from your structure that you are utilizing the app router, but there is a folder named pages within it which may be causing some confusion.

If you have a file named [id].js, it will function in the "old" pages router setup. However, for this to work, the pages directory should be at the root of your project's source code, not nested inside the app folder.

Since you are using the app folder/router, the proper filename to correspond with

http://localhost:3000/products/{id}
would be /app/products/[id]/page.js

Answer №2

If you're looking to create dynamic routes, using useEffect may not be the best approach. Instead, take advantage of NextJS's data fetching capabilities, like getStaticPaths. You can learn more about it here: https://nextjs.org/docs/pages/building-your-application/data-fetching/get-static-paths

For client-side fetching, check out this link: https://nextjs.org/docs/pages/building-your-application/data-fetching/client-side. It explains why you might be encountering a 404 error with your current approach.

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

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

An advanced password checker that notifies the user of any spaces in their password

I need help fixing my JavaScript code. The program should prompt the user for a password using a dialogue box, and then validate that the input has no spaces. If a space is detected, the program should stop and display an alert saying "Invalid, contains a ...

Encountering issues with Yarn Install during production build. Issue states: "Error - [email protected] : The engine "node" does not align with this module"

Currently facing an issue while deploying a ReactJS Project on the PROD environment. The previous command "Yarn install" was working fine, but now it's failing with an error message. The error that I'm encountering is: info [email protected ...

What could be causing my sticky positioning to not function properly when I scroll outside of the designated

My website is organized into sections, with each section corresponding to a hyperlink in the navigation menu. I've applied the CSS property position: sticky to my navbar, which works as expected within the section bounds. However, I want my red navbar ...

Register when a user signs up or buys a product from stripe's subscription service

Currently, I am in the process of developing an application that allows public users to access a pricing page and choose a plan (utilizing stripe for subscription payments). Once a user selects a plan and proceeds to checkout, my aim is to have them redi ...

Generating consecutive numerical values within the auto table JSPDF column VusJs

columns: [ { header: 'No', dataKey: 'Index', }, { header: 'No Registrasi', dataKey: 'no_register' }, { header: 'Kode Partai', dataKey: 'kode_partai' }, ...

Implement a personalized loading spinner in your Next.js application

What is the process for implementing a custom loader in Next.js instead of using the default option? const loading = true; if (loading) { return <CustomLoading />} ...

Sending data from a PHP array to a JavaScript array within a PHP function

I have been scouring Stack Overflow for a solution to my problem, but I haven't found one that fits my specific issue. I recently took over a project from a former coworker that involves managing all the videos and images for my company. My current di ...

Having trouble selecting a default option in a dynamically populated select dropdown using ng-model in the dropdown

For my Angularjs application, I needed to dynamically return a select drop down with its selected option. To accomplish this, I implemented the following function: function getCellRendererMapping(data) { if (data.order == 6) { return funct ...

How can we insert data at the bottom of a table to begin with?

I am looking to add information retrieved from the iTunes API to the end of a table. The first album I receive will be placed at the very end, with each subsequent album adding on while pushing the previous one up in the hierarchy. Any ideas on how I can ...

The image will come to life with animation as the background position is adjusted using Skrollr

Trying to create a div that switches the background image every X pixels scrolled. Initially experimented with changing the background-image, including using sprites and adjusting background position, but encountered a distracting "flickering" effect. Exa ...

Forcing UTF-8 Encoding in JavaScript

I came across this helpful article: While following the advice of many others suggesting to use unescape(encodeURIComponent(srt)), I encountered issues. Attempting to convert the file obtained through XMLHttpRequest did not yield the desired results. Pri ...

Encountering issues when using array.map with null entries in a react application

Struggling to iterate over the location array and map it? Despite several attempts, handling the null object within the array seems challenging. What am I missing here? While using a for loop resolves the issue, the map function is proving to be a roadbloc ...

What is the best technology to implement for a band website design?

I'm in the process of creating a website for my friend's band, and I need some creative input. The site will feature minimal content such as a bio, news, and embedded audio/visual material. While my web development skills are decent, I'm loo ...

Integrating a Vue application with an OpenId provider using the OpenId Connect library

Currently, I am in the process of developing a Single Page Application with Vue on the client-side and Java Spring REST APIs on the backend. My goal is to add security measures using OpenId Connect, specifically with RapidIdentity as the provider. Unlike ...

Can a Stylus and Node.js with Express project utilize a local image?

Let's talk about using images in a Web app. In my Stylus file, style.styl, I typically set the image using code like this: .background background: url(http://path/to/image) But what if we want to save the image to our local app directory and use ...

HTML - Transforming JSON data into a table

I'm having trouble converting JSON data into a table format. Although everything seems to be in order, I am unable to view the values on my table. Here is the code I am using to convert JSON to a table: $(function() { var my_data = &ap ...

Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading. Here is the factory code I am using: var map = false; var myLatlng = new google.maps.LatLng(48.6908333333 ...

Streamlining the process of implementing click events on elements selected by class using jQuery

Slowly but surely, I am gaining familiarity with jQuery and have reached the point where I desire to abstract my code. However, I am encountering issues when attempting to define click events during page load. Within the provided code snippet, my objectiv ...

Issues with hover functionality in Javascript, CSS, and HTML

Seeking assistance with my JavaScript, HTML, and CSS development, I ran into an issue while trying to create a hovering function for my webpage. Despite my efforts, the links are not displaying anything when hovered over, and the divs meant for specific ho ...