简体   繁体   中英

How to pass env variable to client side in a nx workspace?

I'm running a nextJS app in a NX workspace and I need to get access to env variables on client side.

/apps/myproject/.local.env

NEXT_PUBLIC_PROJECT=my-super-project

/apps/myproject/next.config.tsx

module.exports = {
  publicRuntimeConfig: {
    PROJECT: process.env.NEXT_PUBLIC_PROJECT
  }
}

In my nextJS app I'm trying several things:

/apps/myproject/pages/_app.tsx

import nextConfig from 'next/config'
const { publicRuntimeConfig } = nextConfig()
// ...
console.log(process, publicRuntimeConfig)

Running the app via nx serve myproject does not give me any output on client, but on server side I do see the NEXT_PUBLIC_PROJECT value. I'm not quite sure if my next.config.js file is read by nx at all...

For anyone who is still having this issue.
For loading the env variables in react project, followings are required:

  1. Create a .env file at application level.
    Example: apps/myReactApp/.env
  2. Add the variable ther with prefix NX
    Example: If you can variable called "APP_NAME" , then add "NX_APP_NAME" in it. NX loads only those variables which are prefixed with "NX" .

If you want to load different env files for different configuration, then you can do it like this:

For QA: `npx env-cmd -f apps/web-client/.env.qa nx run web-client:build:qa`,  
For staging: `npx env-cmd -f apps/web-client/.env.staging nx run web-client:build:staging`, 
NOTE: you need to install env-cmd package 

More about loading environment variable in their doc .

When you are running npm build or npm start , nx - under the hood gets your environmental variables and writes them into compiled code. Therefore you don't need to have any special logic to access them.

Therefore in your frontend files just access.env through process.env.SOME_CONST .

Also, an interesting fact about compiled code is that if you have loggers during debugging like these:

if(environment === 'development') {
  console.log('Log sample');
}

Then this code is omitted totally from compiled code which shrinks your dist files.


This may be useful to you: https://create-react-app.dev/docs/adding-custom-environment-variables/


Best wishes, Eugene.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM