next-plugin-node-config v1.0.2
next-plugin-node-config
Next.js and node-config, together at last.
Install with npm:
npm install next-plugin-node-configInstall with Yarn:
yarn add next-plugin-node-configWhy?
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:
- Merging of (potentially many) different configuration files (including multiple supported formats) depending on the environment. This is useful for managing different configurations in staging, production, etc.
- Nice error messages with
config.get(). Instead of an unhelpful message about accessing a property ofundefined, or silent bugs caused by using missing values,config.get()will throw an error with the full key path being requested. - It works in places where
next/configdoesn’t – for example, server files that have not been built by Next.js. In these situations,next/configwill supply an undefined configuration because it has not performed its setup phase that populates these values – butconfigwill still work.
How?
When called, this plugin imports config and uses the result to define
serverRuntimeConfig and publicRuntimeConfig in the Next.js config that it
returns.
serverRuntimeConfigwill come fromconfig.serverRuntimeConfig, or a key of your choosing defined bynodeConfigServerKey. For example, a value ofserverwill selectconfig.server. If any existingserverRuntimeConfigvalue exists, it will be merged.publicRuntimeConfigwill come fromconfig.publicRuntimeConfig, or a key of your choosing defined bynodeConfigPublicKey. For example, a value ofpublicwill selectconfig.public. If any existingpublicRuntimeConfigvalue exists, it will be merged.- A webpack alias is added for the
configmodule that points to a browser shim provided by this plugin. It exports an object containing the configuration values retrieved fromnext/config, and compatibleget()andhas()methods.
Usage
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"
});