Env variable = Backend
Since you are talking about env variables (which is good instead hard coded values), react should discarded for simplicity. I mean the variable set should be performed at the backed layer (nodejs). In your example, the API_URL and API_KEY should not be used at the react layer, instead of that, at the backend layer. Something like:

So the next.js backend should use the env variables to do whatever is needed and then return the data to the react layer using the same endpoint. So if you deploy to another server, just change the env variables at backend and assign another domain.
AJAX
Remember that at the frontend layer (react) for security you should not use static variables because as you mentioned, they will be inside of the js build. Only short live tokens (oauth2) should ve used at the frontend layer
Anyway, if you are forced to use the API_URL and API_KEY at the frontend layer (react), you can use these approach:
- Create one endpoint in the next.js backend called /spa-settings
- This endpoint have access to the os in the backend so is able to read any env variable
- Return the required env variables as a json response of /spa-settings
{
"API_URL":"www.foo-api.com/productos",
"API_KEY":"e3c06b64-f242-4ca7"
}
- If you will have several en variables to be exposed you could use the approach of CRA in which all the prefixed variables with REACT_APP_ are exposed.
- Read these value at the entrypoint of react application and expose the values to all the react files (javascript) using any strategy like localstorage, state , global variables, etc
import axios from "axios";
import { createRoot } from 'react-dom/client';
import React from "react";
import App from "./App";
import "./index.css";
import "bootstrap/dist/css/bootstrap.css";
axios.get("./settings.json").then(response => response.data)
.then((data) => {
console.log("settings:", JSON.stringify(data))
localStorage.setItem('settings', JSON.stringify(data));
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
});
- Then on any react file you will be able to access the variables
1 build, N deploys
With these approaches you will need to build your application just one time and the deploy anywhere just setting the required env variables before the startup
References