I have a middleware page on a route that first makes a check against the backend server.
In that middleware I'm trying to call a next.js api
page using the fetch
API, which in turn communicates with the backend. This flow works as expected in the local development environment, but when deployed to vercel, this fails.
The caught error displayed in vercel is: TypeError: Fetch API cannot load: /api/make-check-at-backend/]
.
The URL used is a relative path: fetch("/api/make-check-at-backend/", ...)
.
What is the issue there? Do I need to include the fully qualified URL value where the next.js app is hosted, including domain, protocol, etc? If that's the case, how can the server/host name be retrieved from Vercel? Should I use env variables?
This is the fetch
code used in the middleware:
const retrievedValue = await fetch("/api/make-check-at-backend/", {
method: "POST",
headers: headers,
body: JSON.stringify({ someKey: 'someValue' }),
});
P.S. I've also tried using axios
to make the http call directly to the backend, but this failed with an axios adapter known issue. This same backend call works as expected from any api/*
page. Is all this due to middleware functionality being still in Beta?
Turns out that the Vercel setup has a number of system environment variables which are available in their corresponding deployed sites.
From my experience, in those deployed sites, the fetch
API needs to have the full URL, including protocol, host, pathname, etc.
After some trial and error, I have found the code that works in the deployed sites is:
const retrievedValue = await fetch(`https://${process.env.VERCEL_URL}/api/make-check-at-backend/`, {
method: "POST",
headers: headers,
body: JSON.stringify({ someKey: 'someValue' }),
});
Below follows a screenshot of the Vercel's environment variables documentaiton, in case the link above becomes broken over time.