I have a node config according to the environment. https://github.com/lorenwest/node-config
default.json
{
"server": {
"host": "localhost",
"protocol": "http",
"port": 9011
}
}
I want to get this in the index.html
inside <script>
tag. Does anyone know what is the way to do this ?
I am able to get this config in js file like below
app.js
var config = require('config');
console.log(config.server.host);
I'm a maintainer of node-config
. In a complex app you'll probably have some secrets you want only visible on the backend, and some values you want to share with the frontend.
Put all values you want to share with the frontend under frontend
config key.
Then create an express
route which serves the frontend
config at /config.js
:
router.get('/config.js', _configjs);
// Cache the config, don't recompute it on every request
var configJavascript = 'window.CONFIG='+JSON.stringify(config.get('frontend'));
function _configjs (req, res) {
res.setHeader("Content-Type", "text/javascript");
// Last modified now
res.setHeader('Last-Modified', (new Date()).toUTCString());
// Cache the config for 5 minutes
res.setHeader('Cache-Control', 'max-age='+(60*5));
res.writeHead(200);
res.end(configJavascript);
}
Now after loading /config.js
from the frontend, you can access the frontend configuration through the