2.0.1 • Published 5 years ago

@moxy/next-env v2.0.1

Weekly downloads
11
License
MIT
Repository
github
Last release
5 years ago

next-env

NPM version Downloads Build Status Coverage Status Dependency status Dev Dependency status

Next.js plugin to pass environment variables to Next.js' configuration.

By default, Next.js does not make available process.env to the client side. The available solution for this problem is to set a config in next.config.js to pass values which will be available in either server and client or just server.

The way to do it is by passing values to the publicRuntimeConfig, serverRuntimeConfig and env properties of Next.js' config.

More info: https://nextjs.org/docs#build-time-configuration

This plugin does that automatically for all environment variables starting with a certain prefix.

Installation

$ npm i --save @moxy/next-env

Usage

// next.config.js
const withEnv = require('@moxy/next-env');

module.exports = withEnv({ ...options })({ ...nextConfig });

Multiple configurations can be combined together with function composition. For example:

// next.config.js
const withCSS = require('@zeit/next-css');
const withEnv = require('@moxy/next-env');

module.exports = withCSS(
    withEnv({
        removePrefixes: true,
    })({
        cssModules: true, // this options will be passed to withCSS plugin through nextConfig
    }),
);

Application usage:

// next.config.js
const withEnv = require('@moxy/next-env');

module.exports = withEnv({ removePrefixes: true })({ ...nextConfig });
# environment variables definition
NEXT_PUBLIC_FOO="bar"
NEXT_SERVER_FOO="foo"
NEXT_BUILD_BAR="compile-me-please"
// app.js
const { publicRuntimeConfig } = getConfig():

const x = publicRuntimeConfig.FOO; // 'bar'
const y = 'compile-me-please' // original code was `const y = process.env.BAR;


// server.js
const { serverRuntimeConfig } = getConfig():

const x = serverRuntimeConfig.FOO; // 'foo'

Available options

OptionDescriptionTypeDefault
publicPrefixPrefix of variables to lookup and then pass to publicRuntimeConfigStringNEXT_PUBLIC_
serverPrefixPrefix of variables to lookup and then pass to serverRuntimeConfigStringNEXT_SERVER_
buildPrefixPrefix of variables to lookup and then pass to env to be injected in compile-timeStringNEXT_BUILD_
removePrefixesOption to remove prefix when passing variables to configBooleanfalse

Tests

Any parameter passed to the test command, is passed down to Jest.

$ npm t
$ npm t -- --watch # during development

License

Released under the MIT License.