kyun
kyun

Reputation: 10264

Next.js Dynamic URL with _error

[id].tsx

const Home:NextPage<any> = (props) => {
  return (
    <div>
      {JSON.stringify(props)}
    </div>
  )
}
Home.getInitialProps = async (props) => {
  // getting data from Database if we have an item which matched props.query.id;

  const response = await axios.get('https://MY_API.com/'+props.query.id);''
  // response format is like this
  /*
    response: {
      status: 200 | 500,
      item: Item | undefined
    }
  */
  //If response has no item, I would like to show _error.tsx instead [id].tsx
  return { ...props, response };
}
export default Home;

_error.tsx

const Error:NextPage<any> = (props) => {
  return <div>ERROR PAGE</div>
}
export default Error;

I've found one solution, it is redirecting to /_error but I don't want to change the URL.

localhost:3000/EXIST_ID => show [id].tsx and keep URL

localhost:3000/NOT_EXIST_ID => show _error.tsx and keep URL

Upvotes: 0

Views: 955

Answers (1)

felixmosh
felixmosh

Reputation: 35503

You will need to use custom server, and render the "error" page when the id is not exists.

const express = require('express')
const next = require('next')

const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express()

  server.get('/:id', (req, res) => {
    const page = IS_ID_EXISTS? '/posts' : '/_error';
    return app.render(req, res, page, { id: req.params.id })
  })

  server.all('*', (req, res) => {
    return handle(req, res)
  })

  server.listen(port, err => {
    if (err) throw err
    console.log(`> Ready on http://localhost:${port}`)
  })
})

Upvotes: 0

Related Questions