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

Unexpected behavior: JQuery Ajax request not displaying Json object following recent update to JQuery version 1.10.2

Currently facing an issue with a project I am working on. The previous programmer used jquery 1.4.4, and I have updated it to 1.10.2 due to the designer using Bootstrap. However, after running it in version 1.10.2, one of the objects that was functional i ...

A step-by-step guide to displaying image upload previews using React

I am currently working on developing an image upload form with the use of Next.js/React.js. The goal is to allow users to assign tags to each uploaded image and display a preview of the image using 'URL.createObjectURL'. Although the uploading pr ...

Saving solely the content of an HTML list element in a JavaScript array, excluding the image source

One issue I am facing is with an unordered list in HTML which contains items like <ul id="sortable"> <li class="ui-state-default"><img src="images/john.jpg">John</li> <li class="ui-state-default"><img src="images/lisa.jpg ...

Dynamic table in Vue.js updates with saved data when button is clicked

I am looking for assistance on how to work with two or more parameters using Vue.js. I have a data-saving functionality where three inputs are used and the data is saved to a table upon button click. There is an $.ajax() function involved, but I need help ...

Is it possible to utilize *.localhost as hostnames in Docker for developing intricate applications such as Next/Nuxt?

My current task involves setting up a Docker environment using the *.localhost format (like front.localhost and sdk.localhost), which browsers recognize as pointing to 127.0.0.1 without requiring manual host modifications. The issue I'm facing is wit ...

Utilizing child component HTTP responses within a parent component in Angular: a comprehensive guide

As a newcomer to Angular, I find myself struggling with http requests in my application. The issue arises when I have component A responsible for retrieving a list of IDs that need to be accessed by multiple other components. In component B, I attempted t ...

Received the following error message: "Build optimization failed: discovered a page without a default export of a React Component in the pages directory."

When I run yarn build, I encountered the following error: > Build optimization failed: found page without a React Component as default export in pages/ See https://nextjs.org/docs/messages/page-without-valid-component for more info. error Command fai ...

"Exploring the world of Skeletal Animation with Three.js

I'm struggling with animating in Three.js and I can't figure out if the issue lies in my code or my blender file. Below is the code that I'm using to load and animate the model. Please review it and let me know if you spot any errors. load ...

The AJAX call was successful with a return code of 200, however an error

HTML code snippet: <a href="javascript:void(0)" onclick="$.join_group(<?=$USER_ID?>, <?=$groups[$i]["id"]?>)"><?=$language["join"]?></a> JavaScript function: $.join_group = function(user_id, group_id) { var input = "u ...

Check that EACH radio button has been either selected or left unselected when the button is clicked

I'm still learning Javascript and currently working on a function triggered by a button click. My goal is to display an alert if NONE of the radio buttons have been selected, regardless of whether they are "Yes" or "No." If ALL radio buttons have been ...

Enhance your Vue.js 3 tables with sorting, filtering, and pagination capabilities using this custom component

After extensive research, I am still unable to find an updated Vue.js 3 component that offers sorting, filtering, and pagination for tables without the need for additional requests to a backend API. The options I have come across either seem outdated, are ...

React.js: The specified element type is not valid:

I am currently working on a sample project using react.js in Visual Studio 2019 Here is my Index.js file: import 'bootstrap/dist/css/bootstrap.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provi ...

Utilizing a window.onload function in Microsoft Edge

After trying to run some code post-loading and rendering on the target page, I was recommended to use the Window.load function. This method worked flawlessly in Firefox and Chrome, but unfortunately, I couldn't get it to function in IE. Is there an al ...

variety of provider setups available in Angular

Trying to learn Angular from various online sources can be quite confusing, as different people use different patterns when writing functions. Can someone please explain the .provider concept in Angular? I have experimented with the .provider method using ...

Prevent users from clicking by using a CSS class in HTML and JavaScript

,hey there buddy 1° Can you help me figure out how to prevent click behavior using the CSS class? 2° I'm unable to add an ID to the HTML element, so I need to use the Class to achieve this. 3° None of my attempts have been successful so far. El ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Separate each item in the list and display them across multiple pages within a table

I'm looking to display a list of 37 items across four separate pages within a table. Can anyone suggest a way to split these items and showcase them in four different pages using either javascript or vue.js? ...

I am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

What is the best way to implement date range filtering in vue js?

Currently, I am delving into the realm of vue.js and experimenting with a filtering feature that involves date ranges. The process goes like this: initially filter by type, then proceed to filter by a specified date range, consisting of start and end dat ...

Tips for displaying a modal to a user only once

I've developed a Flask application that enables multiple users to register and log in. To achieve this, I have incorporated sessions into my code. When new users land on the initial page, they are greeted with a modal introducing them to the platform. ...