Home > Net >  nextjs: how can I do a fetch on a local path?
nextjs: how can I do a fetch on a local path?

Time:12-28

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.

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

You can do it like this fetch('http://localhost:3000/api/get_all_prices') but you should only do this 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.

  • Related