How to pass additional data to getserversideprops from another page in Nextjs?

Viewed 6048

I want to pass projectID from the previous page(/projects) to the (/project/[projectName]). Therefore, in order to fetch a project details, i have to fire an API endpoint with projectID.

What is the right way to pass projectID from the previous page and also how to access it in the getServersideProps method.

In the /project/[projectName] page,

export async function getServerSideProps(){
// Here i want to access the projectID sent from the previous page
const data = await fetchData();
return {
    props: data,
  };
}

Query/param prop will have access to the projectName but not projectID.

1 Answers

As serverSideProps will run each time the page is loaded, you can't pass data from one page to another.

What you can do, is either pass data using useContext or if it's general data that you are going to use on all your pages you can fetch it directly on to the _app.js and pass it for all the children components.

This is an example using useContext.

This are the docs fetching on the _app.js. (check the commented code)

You can even combine both techniques and set the data on the _app.js and the consume it on any page or component.

Related