Setup:
I have a NextJS application that fetches data from several external APIs and I want its own Next API to act as a gateway to determine which request goes where (that way I can neatly encapsulate the different API configurations and not worry about it). The App sends the request to the /api
and that proxies it to the relevant external service.
I'm using axios
through react-query
to make those requests and on the client side it seems to work just fine but the monent I try to prefetch data on the backend it falls flat. Turns out I need to set the baseURL on the axios instance to the full url, not just the /api
part (because the backend doesn't have a concept of basePath). But I have very little idea how to do that. Here's what I've tried so far.
let apiURL = () => {
if (process.browser) { return '/api' } // this is client side, no issues
const host = process.env.VERCEL_URL || 'localhost';
const port = process.env.NODE_PORT || '443';
const protocol = process.env.NODE_PORT === '443' ? 'https' : 'http';
return `${protocol}://${host}${port === '443' ? '' : `:${port}`}/api`;
}
export const http = axios.create({ baseURL: apiURL() })
Locally (both in the dev and production environments) it works great. Then I try deploying to Vercel and get a 500 error. It seems like the script is not picking up the env part or something or maybe it's completely unrelated since Vercel logs only give me a partial error message.
Does anyone have a better idea?