api calls don't work in vercel
I'm trying to call my NextJS API:
If I try to write
const res = await fetch("/api/commands");
I get the error 'failed to parse URL' despite the API endpoint clearly existing and being accessible via http://localhost:3000/api/commands
.
To get around this, I declared a base URL variable so I could at least make it work in localhost and hopefully Vercel too (according to Vercel's docs they have a VERCEL_URL that points to the deployment's URL):
and then calling the api like so:
This works in localhost but not Vercel.
How do you properly specify the base URL when calling your API handler?2 Replies
Have you looked from "Network" tab where it tries to get the data when deployed to vercel?
I think you should do:
Ok, a few things were wrong.
After digging a bit, it looks like the correct variable name is actually
NEXT_PUBLIC_VERCEL_URL
.
Moreover, i dug into my api handler and found an unhandled case where i didn't send a response.
I also converted my server component to a client component and fetched the data with a useEffect. ugly but works
I'm not sure about my last solution, feels more like a bandaid, but at least it works.