Is there a way to use the fetch
method with a relative path like this:
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
)
}
I need this code to be able to work in both development and production environments without having to change the URLs for different computers or servers, as it can lead to unnecessary issues.
Any tips on how I can retrieve data from my local API route?
I've noticed that the fetch
method doesn't seem to work with local routes. Is there any workaround for this issue?
[EDIT]
After some research, I found a solution using a library called superjson.
I was originally trying to use the API directly because of serialization issues with Prisma when using getServerSideProps (it returns Date objects that can't be serialized in JSON).
The best approach was to write a common file for the method, utilize superjson for proper serialization, and then call that method within getServerSideProps.
This results in clean code that is compatible with Next.js.