6

I want to know how to attach an ID for example at the end of the URL in Next.js and how to retrieve it in the destination page like this ...

<Link href={`/about/${id}`}><a>About</a></Link>

To be like this ...

/about/256983649012

And then retrieve it in the about page.

How can I do that?

And please keep in mind that I'm already aware of this approach ...

<Link href={{ pathname: 'about', query: { id: id }}}><a>About</a></Link>

But I don't really want to the link to be like this about?id=256983649012

2 Answers 2

3

You need to define that id inside server.js / app.js (I'm using Express in here):

server.js/app.js

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('/about/:id', (req, res) => {
      return app.render(req, res, '/about', { id: req.params.id })
    })

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

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

Then in your about page:

About.js

import React, { Component } from 'react'

export default class extends Component {
  static getInitialProps ({ query: { id } }) {
    return { aboutId: id }
  }

  render () {
    return <div>
      <h1>About #{this.props.aboutId}</h1>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua.
      </p>
    </div>
  }
}

Complete example: here

Sign up to request clarification or add additional context in comments.

2 Comments

when I reload the page then getInitialProps() function failing to get the value from url. please do you have any solution?
can you provide your code? or try to see the props of getInitialProps() static getInitialProps (props) { console.log(props); }
1

You're using Next.js, so the correct way to achieve this is via Next.js's routing system. This is done with a folder structure. Yours would look something like this:

/pages/   (this is provided by Next.js)
-- /about/  
---- [id].js
index.js   (homepage, provided by Next.js)

This would allow you to achieve /about/256983649012, where the id parameter is 256983649012. All the logic for your page goes into [id].js.

The documentation on Next.js is really good. Take a look here for further reading on routing: https://nextjs.org/docs/routing/introduction

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.