I would like to use the fetch
method on a relative path such as :
export async function getServerSideProps() {
// Fetch data from local API
const res = await fetch(`/api/get_all_prices`)
const data = await res.json()
// Pass data to the page via props
return { props: { data } }
}
function HomePage({props}) {
return (
// use props here
)
}
The reason is as follows : I am testing my code on multiple different computers, sometimes with a different port
I would like this code to work in a dev and in a prod environment in order to have to remember to change the used urls on a per-computer / server basis ( witch introduces a lot of unwanted potential issues )
How can I get the data from my local api route ?
I could not figure out why does the fetch
method not do local routes nor a workaround.
[EDIT]
The solution turned out to be a lib called superjson.
I was attempting to put my code into the API because I could not use getServerSideProps properly with prisma ( it returns Date objects that cannot be serialized in JSON )
Thus I was trying to use the API paths as the response there is properly serialized but ran into the issues that made me write this question
The complete solution is to write the method in a common file ( this allows for the factorisation ), use the lib superjson to properly serialize the object and call that method in the getServerSideProps method
This allows for clean code that is nextjs compatible