I am using React and Express together for my web application where Express will serve static files of React build.
I am required to pass the environment-specific react URLs at the time of deployment.
So for this, I have created a .env.template file where I have a template like below
REACT_APP_PRIORITY_DATASET_LAST_X_DAYS=<%REACT_APP_PRIORITY_DATASET_LAST_X_DAYS%>
REACT_APP_PRIORITY_ISSUE_ROWS_NO=<%REACT_APP_PRIORITY_ISSUE_ROWS_NO%>
REACT_APP_STUDYDATASET_API_ENDPOINT=<%REACT_APP_STUDYDATASET_API_ENDPOINT%>
REACT_APP_ASSIGNED_STUDIES_API_ENDPOINT=<%REACT_APP_ASSIGNED_STUDIES_API_ENDPOINT%>
So my build command would be
"build": "env-cmd -f .env.template react-scripts --max_old_space_size=4096 build",
So once the build is created, it will have a template reference.
Now I want to replace the keys with actual values based on my env.
So the approach is
inside my server/.env file
keeping the key with actual values.
Now In server/app.js
Before serving the build, I am writing a function to replace the content using the replace-in file package.
Any help would be appreciated
Code snippet is below
function getReactEnvVariable() {
console.info('object', Object.entries(process.env));
return Object.entries(process.env).reduce(
(accumulator, [key, value]) => {
if (key.startsWith('REACT_APP')) {
accumulator.from.push(
new RegExp(`<%[ ]{0,}${key.trim()}[ ]{0,}%>`, 'gi')
);
accumulator.to.push(value.trim());
}
return accumulator;
},
{from: [], to: []}
);
}
function replaceValueWithEnvSync() {
const REACT_APP_ENVIRONMENTAL_VARIABLE = getReactEnvVariable();
console.log(
'REACT_APP_ENVIRONMENTAL_VARIABLE',
REACT_APP_ENVIRONMENTAL_VARIABLE
);
try {
return replace.sync({
files: '../build/static/js/*.js',
from: REACT_APP_ENVIRONMENTAL_VARIABLE.from,
to: REACT_APP_ENVIRONMENTAL_VARIABLE.to,
countMatches: true,
});
} catch (e) {
console.log('@@@@@@@@@@@@@@@@@@error', e);
return [];
}
}
const file = replaceValueWithEnvSync();
// add middlewares
app.use(express.static(path.join(__dirname, '..', 'build')));
app.use(express.static('public'));
app.use((req, res) => {
res.sendFile(path.join(__dirname, '..', 'build',
'index.html'));
});
so with this logic, my build folder static files get updated, and it restarts my node server locally. It worked fine. But the same code is when we are deploying to the Linux remote server, we are not replacing it. On Linux, we have pm2 installed which restarts the server once the deployment is completed.