Research
Security News
Quasar RAT Disguised as an npm Package for Detecting Vulnerabilities in Ethereum Smart Contracts
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Verification, sanitization, and type coercion for environment variables in Node.js
The env-var npm package is a utility for accessing and validating environment variables in Node.js applications. It provides a simple and consistent API for retrieving environment variables, ensuring they meet specified criteria, and handling default values.
Accessing Environment Variables
This feature allows you to access environment variables and convert them to the desired type. In this example, the 'PORT' environment variable is retrieved and converted to a positive integer.
const env = require('env-var');
const port = env.get('PORT').asIntPositive();
console.log(`Server running on port: ${port}`);
Default Values
This feature allows you to specify default values for environment variables. If the 'HOST' environment variable is not set, it defaults to 'localhost'.
const env = require('env-var');
const host = env.get('HOST').default('localhost').asString();
console.log(`Server running on host: ${host}`);
Validation
This feature ensures that certain environment variables are set and meet specified criteria. In this example, the 'API_KEY' environment variable is required and must be a string.
const env = require('env-var');
const apiKey = env.get('API_KEY').required().asString();
console.log(`API Key: ${apiKey}`);
Custom Validators
This feature allows you to define custom validation logic for environment variables. In this example, the 'CUSTOM_VAR' environment variable must start with 'custom-'.
const env = require('env-var');
const customValidator = (value) => value.startsWith('custom-');
const customVar = env.get('CUSTOM_VAR').required().asString().validate(customValidator);
console.log(`Custom Var: ${customVar}`);
dotenv is a popular package for loading environment variables from a .env file into process.env. It does not provide validation or type conversion features like env-var, but it is widely used for managing environment variables in development.
joi is a powerful schema description language and data validator for JavaScript. While it is not specifically designed for environment variables, it can be used to validate them. It offers more complex validation rules compared to env-var.
convict is a configuration management tool for Node.js that allows you to define a schema for your configuration, including environment variables. It provides validation and default values, similar to env-var, but also supports nested configurations and different configuration sources.
Verification, sanitization, and type coercion for environment variables in Node.js and web applications. Supports TypeScript!
env-var
env-var
npm install env-var
yarn add env-var
You can use env-var
in both JavaScript and TypeScript!
const env = require('env-var');
// Or using module import syntax:
// import env from 'env-var'
const PASSWORD = env.get('DB_PASSWORD')
// Throws an error if the DB_PASSWORD variable is not set (optional)
.required()
// Decode DB_PASSWORD from base64 to a utf8 string (optional)
.convertFromBase64()
// Call asString (or other APIs) to get the variable value (required)
.asString();
// Read in a port (checks that PORT is in the range 0 to 65535)
// Alternatively, use a default value of 5432 if PORT is not defined
const PORT = env.get('PORT').default('5432').asPortNumber()
import * as env from 'env-var';
// Read a PORT environment variable and ensure it's a positive integer.
// An EnvVarError will be thrown if the variable is not set, or if it
// is not a positive integer.
const PORT: number = env.get('PORT').required().asIntPositive();
When using environment variables in a web application, usually your tooling
such as vite
imposes special conventions and doesn't expose process.env
.
Use from
function to workaround this, and create an env
object like so:
import { from } from 'env-var'
const env = from({
BASE_URL: import.meta.env.BASE_URL,
VITE_CUSTOM_VARIABLE: import.meta.env.CUSTOM_VARIABLE
})
For more examples, refer to the /example
directory and EXAMPLE.md. A summary of the examples available in /example
is written in the 'Other examples' section of EXAMPLE.md.
The examples above only cover a very small set of env-var
API calls. There are many others such as asFloatPositive()
, asJson()
and asRegExp()
. For a full list of env-var
API calls, check out API.md.
You can also create your own custom accessor; refer to the 'extraAccessors' section of API.md.
Logging is disabled by default in env-var
to prevent accidental logging of secrets.
To enable logging, you need to create an env-var
instance using the from()
function that the API provides and pass in a logger.
The built-in logger will print logs only when NODE_ENV
is not set to either prod
or production
.
const { from, logger } = require('env-var')
const env = from(process.env, {}, logger)
const API_KEY = env.get('API_KEY').required().asString()
This is an example output from the built-in logger generated by running example/logging.js:
If you need to filter env-var
logs based on log levels (e.g. trace logging only) or have your own preferred logger, you can use a custom logging solution such as pino
easily.
See the 'Custom logging' section of EXAMPLE.md for more information.
You can optionally use dotenv with env-var.
There is no coupling between dotenv
and env-var
, but you can easily use them both together. This loose coupling reduces package bloat and allows you to start or stop using one without being forced to do the same for the other.
See the 'dotenv' section of EXAMPLE.md for more information.
Contributions are welcomed and discussed in CONTRIBUTING.md. If you would like to discuss an idea, open an issue or a PR with an initial implementation.
7.5.0 (20/05/2024)
AsSet()
accessor (#173)FAQs
Verification, sanitization, and type coercion for environment variables in Node.js
The npm package env-var receives a total of 455,097 weekly downloads. As such, env-var popularity was classified as popular.
We found that env-var demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers uncover a malicious npm package posing as a tool for detecting vulnerabilities in Etherium smart contracts.
Security News
Research
A supply chain attack on Rspack's npm packages injected cryptomining malware, potentially impacting thousands of developers.
Research
Security News
Socket researchers discovered a malware campaign on npm delivering the Skuld infostealer via typosquatted packages, exposing sensitive data.