I would like to use the fetch method on a relative path such as :.
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. The solution turned out to be a lib called superjson.
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.
11 gold badge1616 silver badges3333 bronze badges. 3333 bronze badges.
You can do it like this fetch('http://localhost:3000/api/get_all_prices')or replace the base URL with a variable fetch(baseUrl + 'api/get_all_prices') which might cause error: Only absolute paths are supported.However, you should only call local API for testing because..
You should not use fetch() to call an API route in getServerSideProps.
this is mentioned in the documentation. It is recommended to write your logic directly inside getServerSideProps.This applies to getStaticProps too.