I’m using NX for management of my monorepo which houses a React app and a NestJS app.
The NestJS app can read the environment variables locally and deployed. The React app however is always showing undefined.
I have read the documentation for NX which hasn’t seemed to help me work this out.
My structure is:
/nx-monorepo
/apps
/react-app
/src
/environments
environment.ts
environment.prod.ts
.env
...
webpack.config.js
/nest-app
/src
.env
nx.json
package.json
If I log the environment variables in the webpack config, these show up correctly at build time.
webpack.config.js
const { composePlugins, withNx } = require('@nx/webpack');
const { withReact } = require('@nx/react');
module.exports = composePlugins(withNx(), withReact(), (config) => {
console.log('Environment Variables:')
console.log('NX_FLYOUT_SERVICE_URL: ', process.env.NX_FLYOUT_SERVICE_URL);
console.log('NX_IS_PRE_RELEASE: ', process.env.NX_IS_PRE_RELEASE);
console.log('NX_GOOGLE_MAPS_API_KEY: ', process.env.NX_GOOGLE_MAPS_API_KEY);
return config;
});
I use NX’s environment files to leverage the replacement of these files during build time.
environment.ts
type Environment = {
production: boolean;
flyoutServiceUrl: string | undefined;
isPreRelease: boolean;
}
export const environment: Environment = {
production: false,
flyoutServiceUrl: process.env.NX_FLYOUT_SERVICE_URL,
isPreRelease: process.env.NX_IS_PRE_RELEASE === 'true'
};
When I try to log either the environment
or process.env
within the react app, the variables are not correct. process.env
gives me an empty object, whereas environment
gives me the {production: false, flyoutServiceUrl: undefined, isPreRelease: false}
. I uderstand both of these results if the variables are not working properly.
app.tsx
import { environment } from '../environments/environment';
export const App = () => {
console.log(environment);
console.log(process.env);
return <AppMain />
};
Is my setup wrong or am I missing something for the environment variables to be readable within the React app?