Ruby
Ruby

Reputation: 2889

Set and get URL parameters in Next.js

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

Upvotes: 6

Views: 19740

Answers (2)

JBS
JBS

Reputation: 686

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

Upvotes: 1

Darryl RN
Darryl RN

Reputation: 8228

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

Upvotes: 3

Related Questions