Skip to content

Commit

Permalink
Get dynamic config from process.env.REACT_SERVER_CONFIGS (#871)
Browse files Browse the repository at this point in the history
* Get dynamic config from process.env.REACT_SERVER_CONFIGS.

* Update config.js

Add Object.freeze() and remove duplicate declaration of configFilePath so it passes eslint checks.

* Update config.js
  • Loading branch information
mocheng authored and gigabo committed Mar 9, 2017
1 parent b827706 commit 9f68b0f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
9 changes: 9 additions & 0 deletions docs/guides/production.md
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,15 @@ into your application. One example of the file `_configs/production/config.json
}
```

If dynamic config is preferred, just replace `config.json` with file `config.js`. One example of `config.js` might look like this:

```js
module.exports = {
APP_ENV: process.env.NODE_ENV === "production" ? "prod" : "dev",
MY_GLOBAL_VARIABLE: process.env.NODE_ENV === "production" ? "foo" : "bar"
}
```

To use these config variables inside your application, just use the `config()` function inside `react-server` and
you're all set! This works reliably on both server and client sides of the application--fully isomorphic!
Here's an example:
Expand Down
17 changes: 10 additions & 7 deletions packages/react-server/core/config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

/**
* Thin wrapper around the environment-specific configuration file
*/
Expand All @@ -10,13 +9,17 @@ if (SERVER_SIDE) {
module.exports = function () {
// only read out the config once, and then cache it. -sra.
if (null === config) {
/*eslint-disable no-process-env */

//eslint-disable-next-line no-process-env
if (process.env.REACT_SERVER_CONFIGS) {
var fs = require("fs");
/*eslint-disable no-process-env */
var configFile = fs.readFileSync(process.env.REACT_SERVER_CONFIGS + "/config.json");
/*eslint-disable no-process-env */
config = Object.freeze(JSON.parse(configFile));
var path = require('path');
//eslint-disable-next-line no-process-env
var configFilePath = process.env.REACT_SERVER_CONFIGS;

// Node.js tries to load `config.js` file first. If `config.js` doesn't exist, Node.js
// then try to load `config.json`.
configFilePath = path.join(process.cwd(), configFilePath + "/config");
config = Object.freeze(require(configFilePath));
} else {
config = Object.freeze({});
}
Expand Down

0 comments on commit 9f68b0f

Please sign in to comment.