Next.js Discord

Discord Forum

Calling api route from another

Answered
Broad-snouted Caiman posted this in #help-forum
Open in Discord
Broad-snouted CaimanOP
Hi

I'm trying to call an api route i created under the api directory from another api route. However i am getting an error

- error TypeError: Failed to parse URL from /api/asset/signed_url
    at Object.fetch (node:internal/deps/undici/undici:11576:11) {
  [cause]: TypeError [ERR_INVALID_URL]: Invalid URL
      at new NodeError (node:internal/errors:405:5)
      at new URL (node:internal/url:743:13)
      at new Request (node:internal/deps/undici/undici:7132:25)
      at fetch2 (node:internal/deps/undici/undici:10715:25)
      at Object.fetch (node:internal/deps/undici/undici:11574:18)
      at fetch (node:internal/process/pre_execution:239:25)
      at doOriginalFetch (webpack-internal:///(sc_server)/./node_modules/next/dist/server/lib/patch-fetch.js:247:24)


am i missing something?

  const signedUrlResponse = await fetch("/api/asset/signed_url", {
    method: 'GET',
    body: JSON.stringify({ filename: filename }),
  })
Answered by alfon
just put the logic of GET: /signed_url inside your server component
View full answer

13 Replies

Broad-snouted CaimanOP
server component @alfon
@Broad-snouted Caiman server component <@194128415954173952>
you need to provide the full path if ure using fetch in server components
Furthermore, if ure already in server component, there is little to no need to call fetch to your own API.
just put the logic of GET: /signed_url inside your server component
Answer
Broad-snouted CaimanOP
Thanks
i just thought there was a simple way for the apis to be shared among each other
You can do that, but you dont call your own api inside a server component..
@alfon You can do that, but you dont call your own api inside a server component..
cc @Broad-snouted Caiman you shouldn't fetch an api route from another api route, because both run on the server. you just abstract the logic to a function and use them in both api routes
Belgian Hare
I was a victim of calling a domain api from my same domain api. Was getting "code":"ERR_BAD_REQUEST","status":401
Spent a few hours digging into CORS and HTTPS, thinking mis config there was my issue.... and maybe it is. But i guess why try to make middleman api calls work if calling a function is faster.

@joulev Is there no benefit on any dimension to using api fetch from inside another api?
Also, i am curious why it didnt even work?