@modulbank/nuxtjs-env
TypeScript icon, indicating that this package has built-in type declarations

1.0.0-alpha • Public • Published

ENV module for NuxtJS

A Nuxt.js module that loads your .env file into your context options

Features

The module loads variables from your .env file directly into your nuxt.js application context and process.env.

Setup

  1. Add @modulbank/nuxtjs-env dependency to your project
npm i -D @modulbank/nuxtjs-env
  1. Add @modulbank/nuxtjs-env to the buildModules section of nuxt.config file.
export default {
  buildModules: [
    // Simple usage
    '@modulbank/nuxtjs-env',

    // With options
    ['@modulbank/nuxtjs-env', { /* module options */ }]
  ]
}

Disable env variables loading

If you don't want to load the .env file, but instead would like to simply access environment variables from the runtime environment (as with OS shell exports like export DATABASE_USER=test), set the options object's ignoreEnvFile property to true, as follows:

// nuxt.config.ts
import * as Joi from '@hapi/joi';

const nuxtConfig: Configuration = {
  buildModules: [
    [
      '@modulbank/nuxtjs-env',
      {
        ignoreEnvFile: true,
      },
    ],
  ],
}

export default nuxtConfig;

Schema validation

It is standard practice to throw an exception during application startup if required environment variables haven't been provided or if they don't meet certain validation rules. The @modulbank/nuxtjs-env package enables use of the Joi npm package to support this type of validation. With Joi, you define an object schema and validate JavaScript objects against it.

Install Joi (and its types, for TypeScript users):

npm install --save @hapi/joi
npm install --save-dev @types/hapi__joi

The latest version of @hapi/joi requires you to be running Node v12 or later. For older versions of node, please install v16.1.8. This is mainly after the release of v17.0.2 which causes errors during build time. For more information, please refer to their documentation & this github issue.

Now we can define a Joi validation schema and pass it via the validationSchema property of module options object, as shown below:

// nuxt.config.ts
import * as Joi from '@hapi/joi';

const nuxtConfig: Configuration = {
  buildModules: [
    [
      '@modulbank/nuxtjs-env',
      {
        validationSchema: Joi.object({
          NODE_ENV: Joi.string()
            .valid('development', 'production', 'test', 'provision')
            .default('development'),
          BASE_URL: Joi.string().default('http://localhost:3000'),
        }),
      },
    ],
  ],
}

export default nuxtConfig;

By default, all schema keys are considered optional. Here, we set default values for NODE_ENV and BASE_URL which will be used if we don't provide these variables in the environment (.env file or process environment). Alternatively, we can use the required() validation method to require that a value must be defined in the environment (.env file or process environment). In this case, the validation step will throw an exception if we don't provide the variable in the environment. See Joi validation methods for more on how to construct validation schemas.

By default, unknown environment variables (environment variables whose keys are not present in the schema) are allowed and do not trigger a validation exception. By default, all validation errors are reported. You can alter these behaviors by passing an options object via the validationOptions key of the module options object. This options object can contain any of the standard validation options properties provided by Joi validation options. For example, to reverse the two settings above, pass options like this:

// nuxt.config.ts
import * as Joi from '@hapi/joi';

const nuxtConfig: Configuration = {
  buildModules: [
    [
      '@modulbank/nuxtjs-env',
      {
        validationSchema: Joi.object({
          NODE_ENV: Joi.string()
            .valid('development', 'production', 'test', 'provision')
            .default('development'),
          BASE_URL: Joi.string().default('http://localhost:3000'),
        }),
        validationOptions: {
          allowUnknown: false,
          abortEarly: true,
        },
      },
    ],
  ],
}

export default nuxtConfig;

The @modulbank/nuxtjs-env package uses default settings of:

  • allowUnknown: controls whether or not to allow unknown keys in the environment variables. Default is true
  • abortEarly: if true, stops validation on the first error; if false, returns all errors. Defaults to false.

Note that once you decide to pass a validationOptions object, any settings you do not explicitly pass will default to Joi standard defaults (not the @modulbank/nuxtjs-env defaults). For example, if you leave allowUnknowns unspecified in your custom validationOptions object, it will have the Joi default value of false. Hence, it is probably safest to specify both of these settings in your custom object.

Options

only

  • Type: Array[String]
  • Default: null

If you want to restrict what's accessible into the context, you can pass to the module options an only array with the keys you want to allow.

export default {
  buildModules: [
    ['@modulbank/nuxtjs-env', { only: ['some_key'] }]
  ]
}

path

  • Type: String
  • Default: srcDir

By default, the we'll be loading the .env file from the root of your project. If you want to change the path of the folder where we can find the .env file, then use the path option.

export default {
  buildModules: [
    ['@modulbank/nuxtjs-env', { path: '/path/to/my/global/env/' }]
  ]
}

Note: that this is the path to the folder where the .env file live, not to the .env file itself.

The path can be absolute or relative.

systemvars

  • Type: Boolean
  • Default: false

By default this is false and variables from your system will be ignored. Setting this to true will allow your system set variables to work.

export default {
  buildModules: [
    ['@modulbank/nuxtjs-env', { systemvars: true }]
  ]
}

filename

  • Type: String
  • Default: .env

We can override the filename when we need to use different config files for different environments.

export default {
  buildModules: [
    ['@modulbank/nuxtjs-env', { filename: '.env.prod' }]
  ]
}

Usage

After creating your .env file in the project root, simply run your usual yarn dev or npm run dev. The variable inside the .env file will be added to the context (context.env) and process (process.env).

Using .env file in nuxt.config file

This module won't overload the environment variables of the process running your build.

If you need to use variables from your .env file at this moment, just prepend require('dotenv').config() to your nuxt.config file:

require('dotenv').config()

export default {
  // your usual nuxt config.
}

This will works thanks to the dotenv library provided by this module as a dependency. If you decided to ignore some values from your .env file in the module configuration, this won't apply here.

Readme

Keywords

none

Package Sidebar

Install

npm i @modulbank/nuxtjs-env

Weekly Downloads

0

Version

1.0.0-alpha

License

MIT

Unpacked Size

25.5 kB

Total Files

24

Last publish

Collaborators

  • artem9989
  • artur_ka
  • kossmos
  • lazio_dev