npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@modulbank/nuxtjs-env

v1.0.0-alpha

Published

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

Downloads

12

Readme

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.