NX_ environment variables are undefined on a client in Next.js development
Current Behavior
Environment variables that are prefixed with NX_ are undefined during development in Next.js on a client. They work as expected on the server's side. It works correctly in production mode though. Both a client and server show correct environment variables.
Expected Behavior
Environment variables that are prefixed with NX_ should be defined on a client during development.
GitHub Repo
https://github.com/skoob13/nx-next-dev-server-bug
Steps to Reproduce
- Install dependencies (yarn)
- Run the development server using
yarn nx run ui:serve - Open
localhost:4200in a browser - Observe that the server outputs the environment variable correctly and the client outputs undefined in the browser's console.
Nx Report
Node : 18.16.0
OS : darwin-arm64
yarn : 1.22.19
nx : 16.4.3
@nx/js : 16.4.3
@nx/jest : 16.4.3
@nx/linter : 16.4.3
@nx/workspace : 16.4.3
@nx/cypress : 16.4.3
@nx/devkit : 16.4.3
@nx/eslint-plugin : 16.4.3
@nx/next : 16.4.3
@nx/react : 16.4.3
@nrwl/tao : 16.4.3
@nx/web : 16.4.3
typescript : 5.1.6
Failure Logs
No response
Operating System
- [X] macOS
- [ ] Linux
- [ ] Windows
- [ ] Other (Please specify)
Additional Information
I've tested different Next.js versions and environment variables don't work on a client on any 13.4.* version. It works correctly on 13.3.* versions though.
As a temporary solution it's possible to use env in next.config.js defining prefixed with NX_ variables manually.
i am suffering this too.
when is it solved? i need to upgrade to next.js 13.4 :)
Same here with Next 13.4.19 and NX 16.7.3. Env variables are not working anymore..
This probably started occurring when we switched over to use the Next CLI.
Moving forward, we want to keep our package close to Next.js' as such we will deprecate this feature and it will be removed in Nx 18.
The reasoning is that NX_ vars would be available to the client which could expose unwanted information.
The functionality is still available should you want an env variable defined in a .env file on the client side you should use
NEXT_PUBLIC_ prefix otherwise you can use NEXT_ for server-side only.
This issue has been closed for more than 30 days. If this issue is still occuring, please open a new issue with more recent context.