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):
export const BASE_URL =
process.env.NODE_ENV === 'development'
? 'http://localhost:3000'
: `https://${process.env.VERCEL_URL}`;
export const BASE_URL =
process.env.NODE_ENV === 'development'
? 'http://localhost:3000'
: `https://${process.env.VERCEL_URL}`;
and then calling the api like so:
const res = await fetch(`${BASE_URL}/api/commands`);
const res = await fetch(`${BASE_URL}/api/commands`);
This works in localhost but not Vercel. How do you properly specify the base URL when calling your API handler?
2 Replies
rocawear
rocawear2y ago
Have you looked from "Network" tab where it tries to get the data when deployed to vercel? I think you should do:
export const BASE_URL =
process.env.VERCEL_URL
? 'https://${process.env.VERCEL_URL}'
: `http://localhost:3000`;
export const BASE_URL =
process.env.VERCEL_URL
? 'https://${process.env.VERCEL_URL}'
: `http://localhost:3000`;
functionthatreturnsfalse
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.
Want results from more Discord servers?
Add your server