-
Notifications
You must be signed in to change notification settings - Fork 2.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
NX_* Environment Variables not working on prod builds in our test/staging deployments from gitlab, but only sometimes #6891
Comments
I noticed updating from nx 12.6.3 to 12.8.0, dotenv got updated. And looking at the releases, it seems to be in your interest to at least do this update. |
update, we upgraded to the Nx 12.8 releases last week, and the first few deploys were successful. But now a few days later, with no package upgrades at all, we have had the exact same problem pop up again where we know that our gitlab env variables are being set correctly, but every other Nx build in our dev environment has undefined env vars |
Hi, any solution so far? Our team is having the same problem on production builds with env variables being undefined |
Yes, but it is a slow workaround. We added a line in our pipeline scripts to delete node_modules/.cache/nx so that is guaranteed to rerun the entire build step during the build step in our gitlab pipeline. |
Hi, can this be prioritized please? Currently environment variables are not being read and it is a big issue |
+1 |
I'm not certain if it's an identical issue, but it sure seems similar: My project, running Nx v13.0.2 presently, has zero problems whatsoever with environment issues when started or built normally. However, when I run my Cypress e2e tests, they all disappear completely. This makes very little sense to me, since I assumed the same Webpack config was being used to build both versions out... but when I check my variables while running the watcher used to execute Cypress tests, all I see are these:
There are around a dozen environment variables (usually read from my |
have u find any solution? Im also facing this issue right now |
@nurbashanghai - That depends. If you're having Kevin Vandy's problem, I can't help you. However, if you're having the same issue I was having (where the env vars don't populate for Cypress tests), you are in luck my friend! I worked around this issue by manually bootstrapping the environment variables already available in my project, using the env-cmd NPM package. Here's the updated package.json command I use to launch my end-to-end tests: Eventually, I imagine the Nx team will find and fix this bug. The good news is that regardless of if/when/how they do that, this fix should remain working regardless. |
We're having the same issue right now, using Azure pipelines. All environment variables set with a .env file are gone, it would be great if this gets addressed. |
We have a very similar issue @KevinVandy, the env variables are cached between builds when going through a complete Git flow (push branch for PR review -> merge to dev -> PR dev to main -> merge to main). If we push directly from the local This have a big impact for us because we control the meta robots index/follow through env variables, where we allow some content pages indexation only on production. At the moment, every time we push to main after going through a full Git flow, we have to do an extra & empty "magic" push directly from the We are using Vercel for the deployments and we thought it was an issue on their end with the builds cache, but it might be more complex than that, based on several discussions I could find (including this one):
We are using Nx |
Just FYI, upgrading to the latest NX |
At last, I found a solution by using |
@vsavkin ~ Any thoughts? It looks like env vars are broken for quite a few folks. Is this on the roadmap for a fix? |
Nx why have you forsaken us? |
This is a major problem. I just recently started to use NX and now I'm wondering if I should back out. My prod builds are simply broken atm. It's kind of worst possible case. |
We have a solution to be clear, it just makes the builds go a lot slower.
|
That didn't work for me. Oddly my nestjs app picks up my environment from Kubernetes, but react doesn't. My issue may be different. But I'm not sure what to do either way. |
Same problem here deploying to Vercel. I have multiple CRA & Nextjs apps in the workspace. |
Can confirm that this is a problem for builds. I haven't tested it on Vercel, but running the built version of my app locally shows that the environment variables aren't being passed in. |
This is ridiculous, how has this not been resolved by now |
I have not really had problems with environment variables, but found today that NX_INVOKED_BY_RUNNER doesn't seem to be set in some cases. I can't even find the code that sets it anymore. This breaks a whole bunch of our targets. Is this a known issue? |
Have you all just investigate pure JavaScript files you have? As it's converted during compilation time. |
I was able to get this working using
Maybe this might help someone else |
+1 |
I try to use Runtime Hash Inputs by watching some ENV changed and NX still not invalidate cache. But if I use
NX will invalidate cache, not sure this is proper way? |
Any help with this? We still cannot seem to read the env vars on production. |
I was having the same issue as well. My situation is that I'm using environment variables to determine if the environment is a preview or production. I would build out on staging and if the staging build is good to go, I'd rebase that onto production (which triggers a rebuild on Vercel). But, because of Nx caching, the env. vars would still be on staging, even though it was just rebuilt on production. As soon as I implemented #6891 (comment) solution, it now works as expected. |
@l1qu1d I don't think this should be necessary, though nor am I sure what the proper solution is. It's very surprising that such an important issue is open for so long. |
@benjaminhobbs |
Solution from #6891 (comment) works for now. @FrozenPandaz / @vsavkin - this is a fairly important and missing feature, any plans to officially support it soon? NOTE: This also fails for developers on Windows, so we have to have Linux/Mac devs use |
Hope these code help to you, it works for me
const webpack = require('webpack');
/**
* @type {import('@nrwl/next/plugins/with-nx').WithNxOptions}
**/
const nextConfig = {
webpack(config) {
// add bellow code
if (process.env.NODE_ENV === 'production') {
config.plugins.push(
new webpack.DefinePlugin({
'process.env': JSON.stringify(process.env),
})
);
}
return config;
},
}; |
I believe the issue is that the builds are cached from other environments where it was run. Environment variables are generally not included in the hash of a task. But in cases like when using the To add an environment variable to the input of a task, add the following:
We currently don't have a built in way to add a group of environment variables. You can use a workaround like the following.
cc @jaysoo If this is the default behavior of NextJS/webpack should we also configure this for them? |
Thank you for this part, this helped me hopefully resolve an issue I had. I just have one more question. If these inputs are defined in project.json, do I have to repeat defaults set in nx.json or are these project specific ones just appended to those defaults? In docs I've found (https://nx.dev/reference/project-configuration#using-^), I see "default" and "^production" defined again on project level so I wasn't really sure. So my question is, do we have to do this (JSON below) or is repeating those redundant and even potentially problematic? "build" {
"inputs": [
"production",
"^production",
{ "env": "ENV_VAR_1" },
{ "env": "ENV_VAR_2" },
]
} |
NX environment variables for a project are ignored for me only in the CI (github actions) with For your const path = require('path');
require('dotenv').config({ path: path.resolve(__dirname, '.env') }); If your application accesses env vars via
export default {
...
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
if (process.env['NX_INVOKED_BY_RUNNER']) {
config({ path: __dirname + '/.env' });
} |
Any updates on this one ? |
I consistently experience something similar with any environment variables, not just NX_*: This sequence of events happens every time with 4 separate next.js projects within an NX monorepo. It happens whether deploying with the CLI or by triggering deployments by pushing commit(s). I'll use the vercel CLI for this example:
I compared the Vercel build logs, scrolling backwards through the last 2000 lines of each, and found that the first build used the nx cache while 2nd (the redeploy) did not.
I'm going to try this workaround. nx.json:{
"$schema": "./node_modules/nx/schemas/nx-schema.json",
"npmScope": "instant-roofer-nx-monorepo",
"affected": {
"defaultBase": "main"
},
"tasksRunnerOptions": {
"default": {
"runner": "nx-cloud",
"options": {
"cacheableOperations": [
"build",
"lint",
"test",
"e2e"
],
"accessToken": "**************************************************************="
}
}
},
"targetDefaults": {
"build": {
"dependsOn": [
"^build"
],
"inputs": [
"production",
"^production"
]
},
"test": {
"inputs": [
"default",
"^production",
"{workspaceRoot}/jest.preset.js"
]
},
"e2e": {
"inputs": [
"default",
"^production"
]
},
"lint": {
"inputs": [
"default",
"{workspaceRoot}/.eslintrc.json"
]
}
},
"namedInputs": {
"default": [
"{projectRoot}/**/*",
"sharedGlobals"
],
"production": [
"default",
"!{projectRoot}/**/?(*.)+(spec|test).[jt]s?(x)?(.snap)",
"!{projectRoot}/tsconfig.spec.json",
"!{projectRoot}/jest.config.[jt]s",
"!{projectRoot}/.eslintrc.json",
"!{projectRoot}/src/test-setup.[jt]s"
],
"sharedGlobals": [
"{workspaceRoot}/babel.config.json"
]
},
"generators": {
"@nx/react": {
"application": {
"babel": true
},
"library": {
"unitTestRunner": "jest"
}
},
"@nx/next": {
"application": {
"style": "@emotion/styled",
"linter": "eslint"
}
}
},
"defaultProject": "booking"
} the project.json for one of the projects:{
"name": "admin",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/admin",
"projectType": "application",
"targets": {
"build": {
"executor": "@nx/next:build",
"outputs": [
"{options.outputPath}"
],
"defaultConfiguration": "production",
"options": {
"outputPath": "dist/apps/admin"
},
"configurations": {
"development": {
"outputPath": "apps/admin"
},
"production": {}
}
},
"serve": {
"executor": "@nx/next:server",
"defaultConfiguration": "development",
"options": {
"buildTarget": "admin:build",
"dev": true
},
"configurations": {
"development": {
"buildTarget": "admin:build:development",
"dev": true,
"port": 4500
},
"production": {
"buildTarget": "admin:build:production",
"dev": false
}
}
},
"export": {
"executor": "@nx/next:export",
"options": {
"buildTarget": "admin:build:production"
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": [
"{workspaceRoot}/coverage/{projectRoot}"
],
"options": {
"jestConfig": "apps/admin/jest.config.ts",
"passWithNoTests": true
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": [
"{options.outputFile}"
],
"options": {
"lintFilePatterns": [
"apps/admin/**/*.{ts,tsx,js,jsx}"
]
}
}
},
"tags": [
"scope:admin"
]
} |
@charleskoehl your problem is propably related to not havin ENV variables defined as an inputs in your nx.json. See: #6891 (comment) |
Please take a look at this issue when you have the chance. I'm going to relabel this as |
Sorry for taking a while to get to this. tl:dr; is that being more explicit should help to prevent unwanted values (like secrets) to be available in the bundle. Similarly, |
Current Behavior
We use environment variables to point to different aws resources in our dev, test, and prod environments.
Locally, we use a .env file, and prefix all of the environment variables with NX_, like we are supposed to, and it all works fine.
In a Dev environment deployment that we set up that is built in a gitlab pipeline, and deployed to an S3 bucket, it also works fine with the env variables we set up in our gitlab CI/CD settings that are scoped to the dev environments.
However, in the exact same kind of pipeline for our Test (Staging) environment, it seems as if the NX build just simply won't recognize our environmental variables from our gitlab CI/CD settings that we have set there, but sometimes it does. We've tried adding the --skip-nx-cache to see if that was messing it up or not. Lately it seems like if we commit and push directly to our main branch, the build will include our env variables just fine, but if we make a merge request, and have a merge commit that results in the pipeline, none of our env variables get used and they are all undefined.
Here are our gitlab-ci steps for both of those pipelines. In the pipeline, we echo some of the variables that have been set as a sanity check to make sure gitlab itself is not misconfigured during the pipeline.
package.json build scripts are kept simple, the pipeline adds the flags we need above
Other things from googling around, we've tried making sure our environment.prod.ts is like this:
Might this be related to some kind of Nx caching issue that gets stored in our node_modules cache for our pipelines?
Expected Behavior
Nx environment variables should work in all environments (dev, test, prod) when all of them have the same build command.
Steps to Reproduce
Failure Logs
When we download the artifacts from the build to look to see if the variables got used by Nx, we don't see them in a grep, is this normal?
Environment
env for my local machine, but problem happens in our pipelines that run on a node:15.14 docker image
The text was updated successfully, but these errors were encountered: