3

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

3 Answers3

5

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.

amo
  • 123
  • 3
2

Only absolute paths are supported - this type of error you will have in prod

You need to set up your environment variables.

Your path must be something like:

const res = await fetch(process.env.APIpath + `/api/get_all_prices`)

Also, don't forget to set up variables on Vercel

illia chill
  • 1,652
  • 7
  • 11
-1

When you use default next.js API there is no need to be concerned about port, domain, or other things next.js will recognize automatically. if it works correctly on development mode there will be no error on production even if domain or port changes.

and also next.js build-in route is good if you want to mask actual URL or pure node implementation, for example, you have a route api/posts but in posts, you send request to another API like https://backend if you see your network console it shows request send to api.

Paiman Rasoli
  • 1,088
  • 1
  • 5
  • 15