Get Parameter From URL in Next.js Page using 'getInitialProps' and Query API

Get Parameter From URL in Next.js Page using 'getInitialProps' and Query API
Photo by Joshua Woroniecki / Unsplash

In Next.js, the getInitialProps function allows you to retrieve data on the server before the component is rendered, and then pass that data to the component as props. This is useful when you need to retrieve data from an external API or the backend, and then display that data in your component.

To retrieve the query parameters from the URL, you can access the query object that is passed to the getInitialProps function as an argument. Here's an example of how you might use getInitialProps to fetch data from an external API based on the query parameters in the URL:

import axios from 'axios';

function MyPage({ data }) {
  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}

MyPage.getInitialProps = async ({ query }) => {
  const res = await axios.get(`https://my-api.com/items?id=${query.id}`);
  const data = await res.data;
  return { data };
};

export default MyPage;

In this example, the MyPage component receives data via props that it maps to list of items with name. getInitialProps function is called on server and passed with the query object that contains the query parameters from the URL.

It is important to note that the getInitialProps function is only called on the server and not on the client, so if the query parameters change after the component is first rendered, you will need to handle updating the component's props manually.