Encountering an error when accessing dynamically routed pages in Next JS

When I click on a link within the web app to navigate to a dynamically routed page for a product (http://localhost/1), everything works as intended.

However, if I manually input a specific product number in the search bar to navigate directly to that page (http://localhost/2), I encounter the following error:

Server Error
TypeError: Cannot read property 'image' of undefined 

> | <Image src={"/../public/images/" + p.image}
                                        ^

I have attempted to ensure that the types match and have thoroughly reviewed the Next JS documentation on dynamic routing.

I even tried removing the array zero from the filter, but the issue persists without resolution.

I am now considering whether the routing only functions correctly when clicking on a link within Next JS. Could there be a missing setting or configuration that I have overlooked?

pages/[pid].js

import { useRouter } from 'next/router'
import Image from 'next/image'

import data from '../products.json'

export default function Template() {
  const router = useRouter()
  const { pid } = router.query

  const p = data.filter(product => product._id == pid)[0]  // Choose one result

  return (
    <Image src={"/../public/images/" + p.image}
           height="500px"
           width="500px" />
  )
}

products.json

[
  {
    "_id": 1,
    "name": "Toyota",
    "image": "toyota.png"
  },
  {
    "_id": 2,
    "name": "BMW",
    "image": "bmw.png"
  }
]

Update: After attempting to hardcode the src attribute in the Image tag, I received a new error pointing to other references as the issue. It appears that the problem lies in not receiving an object when calling the data object.

Answer №1

Hurray! I finally resolved the issue at hand!

Simply using Dynamic Routes with the 'useRouter()' function was not sufficient. I also needed to implement these two essential functions:

export async function getStaticProps(context) {
  // A placeholder function calls getStaticProps for getStaticPaths.
  return { props: {} }
}

export async function getStaticPaths() {
  const dynamicFiles = products.map(product => (
    {
      params: { pid: String(product._id) },  // Product IDs are integers in JSON file
    }
  ))

  return {
    paths: dynamicFiles,
    fallback: false
  }
}

This approach is logical as it prevents unauthorized path access by users. For instance, a user would not be able to manipulate http://localhost/1234 when 1234 is an invalid parameter.

Discover more about implementing getStaticProps in dynamic routes on Next.js 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

Steps for serving a "noop" document via HTTP

I am in the process of creating a CGI script that performs various functions. I am striving to maintain simplicity and portability within the script. My main objective is to provide users with a way to send a message to the server without losing the curren ...

Monitoring and recording user's browsing activities while excluding server-side scripting

Currently, I am working on creating a registration form which will direct users to a "Thank you" page once completed. However, I want to include a button on this confirmation page that will take users back to the previous page they were on before registeri ...

How can I trigger an Onclick event from an <a tag without text in a Javascript form using Selenium?

Here is my original source code: <a onclick="pd(event);" tabindex="0" issprite="true" data-ctl="Icon" style="overflow: hidden; background: transparent url("webwb/pygridicons_12892877635.png!!.png") no-repeat scroll 0px top; width: 16px; height: 16px ...

Fade-in effect applied to images upon exposure

Is there a way to fade in an image based on the percentage scrolled, rather than a set number of pixels? I want my website to be responsive and adjust to all screen resolutions. Or perhaps is there a method to have the image fade in when it enters the fiel ...

Utilize the double parsing of JSON information (or opt for an alternative technique for dividing the data

Looking for the most effective approach to breaking down a large data object retrieved from AJAX. When sending just one part (like paths), I typically use JSON.parse(data). However, my goal is to split the object into individual blocks first and then parse ...

Error 56 EROFS encountered when trying to save a file in Node.js filesystem every 2 seconds

I've set up a node.js environment on my raspbian system and I'm attempting to save/update a file every 2/3 seconds using the code below: var saveFileSaving = false; function loop() { mainLoop = setTimeout(function() { // update data ...

Utilize jQuery and JSP (or PHP) to showcase detailed information about a specific item when a user clicks on it within an HTML page

For my upcoming college project, I am tasked with developing a movie library. The main page of the library will feature various movie posters. Upon clicking on a poster, users will be directed to a dedicated page displaying detailed information about the ...

Getting a specific index from an array using the Angular ng-repeat Directive: A step-by-step guide

I am trying to retrieve a specific index in an array using the ng-repeat directive. Currently, it is displaying information for all indexes... I only want to display the information for the second index as an example... This is my main.js: app.controll ...

"ng2-file-uploader necessitates a browser refresh in order to function

I am currently utilizing ng2-file-upload within my Angular 10 project to allow users to upload their photos. The upload process is functioning correctly, but the issue arises when the newly uploaded photo does not automatically appear in the photo list wit ...

How can I include a JSON object in an angularjs $scope variable?

How can I effectively inject my JSON Object into my angular $scope during the create() function? Sample HTML: <input type="text" class="title" placeholder="hold" ng-model="formData.text"/> <input type="text" class="desc" placeholder="description ...

Events related to key press timing in HTML 5 canvas

Currently, I am developing a game similar to Stick Hero for Android using HTML5. I am working on the code that will capture the time of key press (specifically the right arrow key with ASCII 39) in JavaScript and expand a stick accordingly. <!doctype h ...

JavaScript - convert the values of an array within a JSON object into separate strings

I am receiving a JSON object from an API, and my next step involves some string analysis of each key value. This process works perfectly for 90% of the objects I receive because the key values are strings. { ID: '0012784', utm_source: 'webs ...

Unexpected error encountered when passing a query string as props to a random component in Next.js version 12.4

As a beginner in Next.js, I have just started diving into routing and query params. My goal was to pass query params down as props to a component in order to sort my list based on those params. However, when I attempted to retrieve my query string using th ...

Having difficulty deleting cookies in a Next.js production environment

I'm currently building an application using NextJs and I've implemented cookie authorization when a user logs in: res.setHeader("Set-Cookie", [ cookie.serialize("authorization", `Bearer ${jwtGenerated}`, { ht ...

Issue encountered while transforming the data buffer into the video within a Node.js environment

I am attempting to create a buffer from the mp4 video, and then convert that buffer back into the video. The buffer is being generated as follows: const buffer = Buffer.from("Cat.mp4"); console.log(buffer); The output I receive is <Buffer 43 61 74 2e ...

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 best way to align an element next to another using id or class?

I am looking to align the search element next to either "Media Heading 1" or "Media Heading 2" based on their id/class. For instance: Assume I have an element with the class of "media-item-1" and I aim to position the search div alongside that element us ...

What is the best way to send user input text to a Vue method using v-on:change?

I am trying to pass the input value from my HTML to a Vue method called checkExist(). I need to get this value within the checkExist() method. Can anyone provide advice on how I can achieve this? I am new to Vue and could use some guidance. HTML: <inp ...

Utilizing HTML5's geolocation API to construct a geofence

Is there a way to utilize the HTML5 geolocation API to determine if a user is located in a specific area? I'm considering setting a central latitude and longitude and creating a radius around it, so the site will function as long as the user is within ...

A Vue.js trick to modify the element's class within a v-for loop when hovering in and out

I'm having trouble changing the class of a single element within a v-for loop based on mouseenter/mouseleave events. I want only the hovered element to change its class, but currently, all elements in the list are affected. I attempted binding the cl ...