← coderrocketfuel.com

Retrieve Query String Parameters From A URL In Next.js

A query string is the portion of a URL that assigns values to specified parameters.

Typically, a URL containing a query string will look something like this:

https://example.com/path/to/the/page?id=1234567

In that URL, the query string value is id=1234567.

You can also add multiple query string parameters to a page's URL like this:

https://example.com/path/to/the/page?id=1234567&name=nick

Notice that each parameter is separated by the ampersand (&) symbol.

Ok great. But how do you retrieve query string parameter values in your Next.js web application?

Using the example URL with multiple query parameters from above, you can use the getInitialProps() function (included with the Next.js framework) like this:

import React, { Component } from "react"

export default class extends Component {
  static async getInitialProps ({ query }) {
    const id = query.id
    const name = query.name

    return {
      id: id,
      name: name
    }
  }

  render () {
    return (
      <>
        <div>ID: {this.props.id}</div>
        <div>Name: {this.props.name}</div>
      </>
    )
  }
}

The getInitialProps() function is called before the rest of the page is loaded and allows you to do initial data population. And it also receives a single argument called context, which includes the query string section of the URL parsed as an object.

As a result, this makes the query string parameters in our code example accessible in an object like this:

{
  id: "1234567",
  name: "nick"
}

Then, you can pass the two values to the page as props values via the return {} object. This makes the query string parameters available in the page via this.props.id and this.props.name.

There you have it! That's how you retrieve query string parameter values from a URL in your Next.js application.