6

I cannot use internal path to fetch my internal api data The error said

TypeError: Failed to parse URL from /api/hello**
------------
export async function getStaticProps() {
  const data = await fetch("/api/hello"
  ...
------------

But it works, if I use full url (hard code) like this

export async function getStaticProps() {
  const data = await fetch("http://localhost:3000/api/hello"
  ...

Anyone know how to use internal path instead of full url?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • You shouldn't be calling an internal API route from inside `getStaticProps`, simply use the logic from the API route directly in `getStaticProps`. See [Fetch error when building Next.js static website in production](https://stackoverflow.com/questions/66202840/fetch-error-when-building-next-js-static-website-in-production). – juliomalves Aug 06 '22 at 13:25
  • Thanks for this comment, now the app Im working is working now. tsk tsk – Forbidden May 30 '23 at 08:01

1 Answers1

2

When I do this, I get

TypeError: Only absolute URLs are supported

So absolute URLs are required.

You can to simplify this with an environment variable

BASE_FETCH_URL=http://localhost:3000

and then call fetch with

const data = await fetch(`${process.env.BASE_FETCH_URL}api/hello`);

See https://codesandbox.io/s/trusting-lamport-z252dl?file=/pages/index.js (might break in the future if the url of the temporary deployment changes)

Samathingamajig
  • 11,839
  • 3
  • 12
  • 34