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?