Combine node-config with Next.js' built-in support for runtime configuration
MIT License
Next.js and node-config, together at last.
Install with npm:
npm install next-plugin-node-config
Install with Yarn:
yarn add next-plugin-node-config
Next.js already has built-in support for runtime configuration (in fact, this plugin is implemented using that) – so why involve node-config as well?
node-config provides some features that are nicer for large applications:
config.get()
. Instead of an unhelpfulundefined
, or silent bugs caused byconfig.get()
will throw an error with the full keynext/config
doesn’t – for example, server filesnext/config
willconfig
will still work.When called, this plugin imports config
and uses the result to define
serverRuntimeConfig
and publicRuntimeConfig
in the Next.js config that it
returns.
serverRuntimeConfig
will come from config.serverRuntimeConfig
, or a key ofnodeConfigServerKey
. For example, a value ofserver
will select config.server
. If any existing serverRuntimeConfig
publicRuntimeConfig
will come from config.publicRuntimeConfig
, or a key ofnodeConfigPublicKey
. For example, a value ofpublic
will select config.public
. If any existing publicRuntimeConfig
config
module that points to a browser shimnext/config
, and compatible get()
and has()
Add some configuration files, for example config/default.js
, then add this
plugin to next.config.js
.
Simplest usage with no existing Next.js config:
const withNodeConfig = require('next-plugin-node-config');
module.exports = withNodeConfig();
With existing Next.js config:
const withNodeConfig = require('next-plugin-node-config');
module.exports = withNodeConfig({
// These will be merged on top of anything that comes from `config`!
serverRuntimeConfig: {
secret: 'entropy9'
},
publicRuntimeConfig: {
api: '/graphql'
},
webpack(config, options) {
// ...
return config;
}
});
Using the nodeConfigServerKey
and nodeConfigPublicKey
options,
serverRuntimeConfig
and publicRuntimeConfig
can be named something nicer in
your config files:
const withNodeConfig = require('next-plugin-node-config');
module.exports = withNodeConfig({
nodeConfigServerKey: 'server',
nodeConfigPublicKey: 'public'
});
In your application, you’re still free to use the next/config
module directly:
import getConfig from 'next/config';
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
…but you can now use config
as well!
import config from 'config';
const secret = config.get('serverRuntimeConfig.secret');
const api = config.get('publicRuntimeConfig.api');
// …or if using the custom keys as in the example above:
const secret = config.get('server.secret');
const api = config.get('public.api');