Conditionally setup proxy based on environment variable #742
-
I am using create-react-app and I'm trying to setup the proxy only if my custom environment variable $ENVIRONMENT_MODE is "production".
I see the environment variables are correctly detected in the setupProxy.js because the proxy works correctly without the if statement (PUBLIC_URL is detected correctly). However, if I set ENVIRONMENT_MODE=production and add the if statement to this configuration, the proxy doesn't work anymore. I have also tried putting the conditional in the outer scope (wrapping up all the code) without success. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Hi. I'm not a As alternative you can try the const { createProxyMiddleware } = require("http-proxy-middleware");
module.exports = function (app) {
// it works without this condition
app.use(
"/static",
continueWhen(process.env.ENVIRONMENT_MODE === 'production'),
createProxyMiddleware({
target: "http://localhost:3000",
pathRewrite: {
"/static": `${process.env.PUBLIC_URL}/static`,
},
})
);
};
function continueWhen(condition) {
return (req, res, next) => {
if (condition) {
next(); // pass control to the next middleware function in this stack
} else {
next("route"); // otherwise skip to the next router
}
};
} |
Beta Was this translation helpful? Give feedback.
-
From what I see;
|
Beta Was this translation helpful? Give feedback.
-
As suspected, it wasn't a problem with CRA but it wasn't a problem with the proxy either. The environment variable was not available, I had to set it right before
|
Beta Was this translation helpful? Give feedback.
As suspected, it wasn't a problem with CRA but it wasn't a problem with the proxy either. The environment variable was not available, I had to set it right before
npm start
: