@moxy/next-envdeprecated

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

Usage no npm install needed!

<script type="module">
  import moxyNextEnv from 'https://cdn.skypack.dev/@moxy/next-env';
</script>

README

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

Option Description Type Default
publicPrefix Prefix of variables to lookup and then pass to publicRuntimeConfig String NEXT_PUBLIC_
serverPrefix Prefix of variables to lookup and then pass to serverRuntimeConfig String NEXT_SERVER_
buildPrefix Prefix of variables to lookup and then pass to env to be injected in compile-time String NEXT_BUILD_
removePrefixes Option to remove prefix when passing variables to config Boolean false

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.