Skip to content

Commit

Permalink
feat(nextjs): expose environment variables prefixed with NX_ (#7193)
Browse files Browse the repository at this point in the history
  • Loading branch information
kirjai committed Oct 1, 2021
1 parent 2d93409 commit 61bcab3
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
7 changes: 6 additions & 1 deletion e2e/next/src/next.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ describe('Next.js Applications', () => {
},
};
updateFile(`apps/${appName}/proxy.conf.json`, JSON.stringify(proxyConf));
updateFile('.env.local', 'NX_CUSTOM_VAR=test value from a file');

updateFile(
`apps/${appName}/pages/index.tsx`,
Expand All @@ -53,7 +54,10 @@ describe('Next.js Applications', () => {
.then(setGreeting);
}, []);
return <h1>{greeting}</h1>;
return <>
<h1>{greeting}</h1>
<h2>{process.env.NX_CUSTOM_VAR}</h2>
</>;
};
export default Index;
`
Expand All @@ -78,6 +82,7 @@ describe('Next.js Applications', () => {

const data = await getData(port);
expect(data).toContain(`Welcome to ${appName}`);
expect(data).toContain(`test value from a file`);

try {
await promisifiedTreeKill(p.pid, 'SIGKILL');
Expand Down
33 changes: 32 additions & 1 deletion packages/next/plugins/with-nx.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// ignoring while we support both Next 11.1.0 and versions before it
// @ts-ignore
import type { NextConfig } from 'next/dist/server/config';
import { WebpackConfigOptions } from '../src/utils/types';
import type { WebpackConfigOptions } from '../src/utils/types';

const { join } = require('path');
const { appRootPath } = require('@nrwl/tao/src/utils/app-root');
Expand Down Expand Up @@ -126,9 +126,40 @@ function withNx(nextConfig = {} as WithNxOptions) {
delete nextGlobalCssLoader.issuer.and;
}

/**
* 5. Add env variables prefixed with NX_
*/
addNxEnvVariables(config);

return userWebpack(config, options);
},
};
}

function getNxEnvironmentVariables() {
return Object.keys(process.env)
.filter((env) => /^NX_/i.test(env))
.reduce((env, key) => {
env[key] = process.env[key];
return env;
}, {});
}

function addNxEnvVariables(config: any) {
const maybeDefinePlugin = config.plugins.find((plugin) => {
return plugin.definitions?.['process.env.NODE_ENV'];
});

if (maybeDefinePlugin) {
const env = getNxEnvironmentVariables();

Object.entries(env)
.map(([name, value]) => [`process.env.${name}`, `"${value}"`])
.filter(([name]) => !maybeDefinePlugin.definitions[name])
.forEach(
([name, value]) => (maybeDefinePlugin.definitions[name] = value)
);
}
}

module.exports = withNx;

0 comments on commit 61bcab3

Please sign in to comment.