Encountering a 404 error in a Next.js application while utilizing path parameters

Embarking on my journey into web development, I am trying to grasp the concept of server-side rendering using next.js and react within a lambda function. When running the code on a lambda, the result is somewhat functional as it displays the parameter value like "shepard," but I encounter a 404 error in the console. Running the code locally presents a different issue; the page returns a complete 404 error, indicating that the parameters are not being passed through at all. Here is the structure of my project:

index.js
server.js
pages/
     index.js
     dogs/
          index.js
          _breed.js

The following files seem to be essential:

server.js

const express = require('express')
const path = require('path')
const next = require('next')
const pathMatch = require('path-match')
const isLocalEnvironment = process.env.NODE_ENV !== 'lambda'
const app = next({ isLocalEnvironment })
const handle = app.getRequestHandler()
const { parse } = require('url')

const server = express()
const route = pathMatch()

server.use(async(req, res, next) => {
  await app.prepare();
  next();
})

server.use('/_next', express.static(path.join(__dirname, '.next')))
server.get('/', (req, res) => app.render(req, res, '/'))
server.get('/dogs', (req, res) => app.render(req, res, '/dogs'))

server.get('/dogs/:breed', (req, res) => {
  const params = route('/dogs/:breed')(parse(req.url).pathname)
  return app.render(req, res, '/dogs/_breed', params)
})


server.get('*', (req, res) => handle(req, res))

module.exports = server

dogs/index.js

import React from 'react'
import Default from '../../layouts/default'
const meta = { title: 'Dogs', description: 'Dogs' }

class DogsPage extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      loading: true,
    }
    this.fetchData = this.fetchData.bind(this)
  }
  async componentDidMount () {
    await this.fetchData()
  }
  async fetchData () {
    this.setState({
        loading: false
    })
  }
  render () {
    return (
      <Default meta={meta}>
        <div>
          <h1>Please select a dog from the menu bar.</h1>
        </div>
      </Default>
    )
  }
}

export default DogsPage

_breed.js

import React from 'react'
import Default from '../../layouts/default'
const meta = { title: 'Breed', description: 'Specific Breed' }

class BreedPage extends React.Component {
  static getInitialProps ({ query: { breed } }) {
    return { breed }
  }
  constructor (props) {
    super(props)
    this.state = {
      loading: true,
    }
    this.fetchData = this.fetchData.bind(this)
  }
  async componentDidMount () {
    await this.fetchData()
  }
  async fetchData () {
    this.setState({
      breed: this.props.breed,
      loading: false
    })

  }
  render () {
    return (
      <Default meta={meta}>
        <div>
        <h1>This breed is {this.props.breed}!</h1>
        </div>
      </Default>
    )
  }
}

export default BreedPage

If I initiate the application and proceed to navigate to http://localhost:3000/dogs, everything functions correctly.

However, upon attempting to reach: http://localhost:3000/dogs/sheppard

I receive a 404 error, stating that the page does not exist.

Is there something crucial that I'm overlooking in my server routing?

Answer №1

execute app.render(req, res, '/dogs/_breed', params)

To resolve the issue, ensure that _breed.js is located within the dogs directory. If your app cannot locate _breed within dogs, it will redirect to a 404 error page.

I trust this information proves beneficial.

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

Determine if a webpage forwards to a new link with the help of phantomjs, flagging any issues exclusively for designated websites

As a beginner in frontend development, I have a question that may seem simple. Please be patient with me. var page = require('webpage').create(), system = require('system'); if (system.args.length === 1) { console.log('Usage: ...

Prevent clicking here

I'm attempting to only prevent the click event on the current item with a certain class. $(document).on('click', '.item', function() { $(".item").removeClass('is-expanded'); $(this).addClass('is-expanded'); ...

Is there a distinction in invoking a service through reference or directly in Dependency Injection?

QUERY: Are there any discernible differences between the two instances of utilizing a factory service? Instance 1: angular.module('ramenBattleNetworkApp') .controller('MainCtrl', function ($scope, Helpers) { var testArray = [1 ...

Tips for preserving scroll position within a division following the redisplay of a division in Vue.js

Within my Laravel and Vue project, I have set up a feature to display posts in a scrollable area. This area is only visible when the 'showFeed' variable is true. <div v-show="showFeed" class="scroll-container" v-scroll=&quo ...

Using AngularJS and the ng-show directive, you can set a <div> element to

Objective: My aim is to show the content of a div according to the status of checkboxes, while also ensuring that these divs are visible by default If I have this code snippet: <html> <head> <script src="https://ajax.googleapis.com/ajax/li ...

What are the drawbacks of relying on a dependent dependency in software development?

In a recent discussion on Stack Overflow, it was suggested that the best practice is to install packages from sub-dependencies for future use in the app, rather than directly from the dependencies node_modules folder. However, my scenario is a bit unique. ...

When trying to access $model.show() in Vue.js, the returned model is showing as undefined

I'm running into a console error message every time I try to click the button for $model.show('demo-login'): TypeError: Cannot read property 'show' of undefined Error output when the button is clicked: TypeError: Cannot read prop ...

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

What could be causing my browser to display twice the height value?

After running the code below on my browser, I noticed that the height value is rendered double. To start off, I tested the following code in about:blank. In the HTML: ... <canvas id="canvasArea" style=" width: 500px; height: ...

The XMLHttpRequest function successfully logs data in the console, but does not return the data within the function itself

I find it puzzling that the console.log statement at the end of the code snippet displays the data as expected, while the return optiondata line does not. function populate_selectbox() { var ajaxRequest; try { // Opera 8.0+, Firefox, S ...

Using jQuery to toggle the visibility of table data cells across various tables on a single webpage

On my webpage, I have multiple tables and I'm trying to add more rows or close table data cells using jQuery. However, I seem to be encountering an issue as it's not working properly. <table class="table" ><tr> < ...

Displaying and hiding the top menu when the div is scrolled

I have developed a script that is designed to display the menu in a shaking motion and hide it as you scroll down. It functions properly when scrolling within the body of the webpage, but I am facing issues when attempting to do so with a div that has an o ...

Mapping an object in ReactJS: The ultimate guide

When I fetch user information from an API, the data (object) that I receive looks something like this: { "id":"1111", "name":"abcd", "xyz":[ { "a":"a", "b":"b", "c":"c" ...

Issue with the positioning of the datepicker is not functioning properly

I'm currently facing an issue with the position of a date picker plugin from jquery. The search box on my website allows users to select a range of dates using the date picker, but when enabled, the date picker appears at the bottom left corner of the ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

A guide on sending multiple input values using the same class name or id through ajax

My goal is to send multiple input values through AJAX to my PHP script. Everything works smoothly when I use getElementById. However, I have the functionality to add a child. The issue arises when it only retrieves values from the first child while iterati ...

Transferring data to a Component as properties in Next.js

I've encountered an issue while trying to pass editvalues as props to my EditForm component, resulting in the error 'editvalues is not defined'. Important note: editvalues is an object Upon using console.log(editvalues), I can see the valu ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Repurposing JavaScript objects after clearing their contents

Here's my issue. I'm working with a Javascript object, initialized as var stack = {}. This object is used in my project to store arrays. When the user clicks the add button, an array is added to the object with a specific key that is inputted in ...

What is the method for obtaining the input value of an input type number in HTML?

Within my form, there is a number field where users can input scores: <input type="number" min="0" max="100" class="form-control" name="total_score" id='total_score' value="<?php echo $total_score;?>" >(Please input a score from 0-10 ...