I want to pass nested object data from one page to the next page. I want to pass the object. We can not use localStorage or sessionStorage because we have to consume object values from getServerSideProps. We do not use here router query as it passes a query that takes key pair value.
-
Have you considering adding this data into a context provider? https://reactjs.org/docs/context.html – Mario Perez Jan 24 '23 at 14:28
3 Answers
getServerSideProps
and getStaticProps
run on the server so they do not have any relation with your components and your hooks, so there is no way that they have access to any provider
or any hook
.
but since getServerSideProps
runs on every request
you can use the request to pass data to it. one solution is to pass data in the url
.
We do not use here router query as it passes a query that takes key pair value
you can pass an object with router query you just have to stringify
it before passing it then parse
data when you recieve it
let suppose that you have page A
with getServerSideProps
you can call it like this :
const router = useRouter();
router.push({
pathname: '/url_of_page_A',
query: {
data: JSON.stringify( { a: 'value', b: 'another value'} ) ;
},
});
Now in your page A
inside getServerSideProps
you can access data
via context query :
export async function getServerSideProps(context) {
const data = JSON.parse(context.query.data);
}

- 10,695
- 9
- 19
- 38
You can use the Link component from next/link
, something like:
<Link
href={{
pathname: 'path-to-your-page',
query: 'data you want to pass'
}}
>
You other page
</ Link>
From your other page, you can then benefit form the useRouter
nextjs hook:
const router = useRouter();
const dataFromPreviousPage = router.query;

- 139
- 1
- 5
Thanks, @Smaiil I am coming up with a solution. We can not send an object through localStorage. We can work through it via query.
const queryData = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
}
router.push({
pathname: 'pathname',
query: queryData,
},
'pathname' // use this to clear query strings like key value from URL
);
This way we can send query data and do getServerSideProps implementation to the respective page. refer below
export async function getServerSideProps({ query }) {
try {
const response = await wretch(
`API URL`
)
.post(query)
.json();
const scheme = response.data;
return {
props: { scheme },
};
} catch (error) {
return {
props: {},
};
}
}

- 168
- 3
- 12