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:
.envfile at application level.Example:
apps/myReactApp/.envExample: 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:
More about loading environment variable in their doc.