{"id":27132067,"url":"https://github.com/dbstratta/environment","last_synced_at":"2025-04-07T21:41:36.275Z","repository":{"id":38176181,"uuid":"147988925","full_name":"dbstratta/environment","owner":"dbstratta","description":"🌳 Environment variable configuration for Node.js made easy.","archived":false,"fork":false,"pushed_at":"2023-01-07T04:02:17.000Z","size":3077,"stargazers_count":13,"open_issues_count":16,"forks_count":3,"subscribers_count":1,"default_branch":"develop","last_synced_at":"2025-03-18T06:28:30.545Z","etag":null,"topics":["config","configuration","env","environment","nodejs","typescript","variables"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dbstratta.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-09-09T03:10:14.000Z","updated_at":"2022-07-23T10:26:54.000Z","dependencies_parsed_at":"2023-02-06T11:16:45.533Z","dependency_job_id":null,"html_url":"https://github.com/dbstratta/environment","commit_stats":null,"previous_names":["strattadb/environment"],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbstratta%2Fenvironment","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbstratta%2Fenvironment/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbstratta%2Fenvironment/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbstratta%2Fenvironment/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dbstratta","download_url":"https://codeload.github.com/dbstratta/environment/tar.gz/refs/heads/develop","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247735508,"owners_count":20987458,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["config","configuration","env","environment","nodejs","typescript","variables"],"created_at":"2025-04-07T21:41:35.615Z","updated_at":"2025-04-07T21:41:36.252Z","avatar_url":"https://github.com/dbstratta.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# environment\n\n[![Azure Pipelines](https://img.shields.io/azure-devops/build/strattadb/0d9c480f-815f-404d-8d52-50af29a893e6/1/develop.svg?style=for-the-badge)](https://dev.azure.com/strattadb/environment/_build?definitionId=1)\n[![npm](https://img.shields.io/npm/v/@strattadb/environment.svg?style=for-the-badge)](https://www.npmjs.com/package/@strattadb/environment)\n[![Codecov](https://img.shields.io/codecov/c/github/dbstratta/environment/develop.svg?style=for-the-badge)](https://codecov.io/gh/dbstratta/environment)\n[![David](https://img.shields.io/david/dbstratta/environment.svg?style=for-the-badge)](https://david-dm.org/dbstratta/environment)\n[![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=for-the-badge)](CONTRIBUTING.md)\n\nEnvironment variable configuration for Node.js made easy.\n\n## The problem\n\nA lot of applications need to ensure that some environment variables are\nset from the beginning, and checking if the value in `process.env` is `undefined`\nevery time is needed gets tedious very fast.\n\n`environment` allows applications to ensure required env variables are set and are valid according\nto _your_ definition of valid. See [how to use it](#usage).\n\n## Table of Contents\n\n- [environment](#environment)\n  - [The problem](#the-problem)\n  - [Table of Contents](#table-of-contents)\n  - [Installation](#installation)\n  - [Usage](#usage)\n  - [Examples](#examples)\n  - [API](#api)\n    - [`makeEnv(schema: Schema, processEnv?: { [key: string]: string | undefined }): Env`](#makeenvschema-schema-processenv--key-string-string--undefined--env)\n    - [Parsers](#parsers)\n      - [`parsers.string(value: string): string`](#parsersstringvalue-string-string)\n      - [`parsers.boolean(value: string): boolean`](#parsersbooleanvalue-string-boolean)\n      - [`parsers.integer(value: string): number`](#parsersintegervalue-string-number)\n      - [`parsers.float(value: string): number`](#parsersfloatvalue-string-number)\n      - [`parsers.email(value: string): string`](#parsersemailvalue-string-string)\n      - [`parsers.url(value: string): string`](#parsersurlvalue-string-string)\n      - [`parsers.ipAddress(value: string): string`](#parsersipaddressvalue-string-string)\n      - [`parsers.port(value: string): number`](#parsersportvalue-string-number)\n      - [`parsers.whitelist(whitelistedValues: string[]): Parser\u003cstring\u003e`](#parserswhitelistwhitelistedvalues-string-parserstring)\n      - [`parsers.regex(pattern: Regex): Parser\u003cstring\u003e`](#parsersregexpattern-regex-parserstring)\n      - [`parsers.array\u003cT\u003e({ parser: Parser\u003cT\u003e, separator?: string }): Parser\u003cT\u003e`](#parsersarrayt-parser-parsert-separator-string--parsert)\n      - [`parsers.positiveInteger(value: string): number`](#parserspositiveintegervalue-string-number)\n      - [`parsers.nonPositiveInteger(value: string): number`](#parsersnonpositiveintegervalue-string-number)\n      - [`parsers.negativeInteger(value: string): number`](#parsersnegativeintegervalue-string-number)\n      - [`parsers.nonNegativeInteger(value: string): number`](#parsersnonnegativeintegervalue-string-number)\n  - [Recipes](#recipes)\n    - [Making environment variables required](#making-environment-variables-required)\n    - [Specifying a default value for when the env variable is not required](#specifying-a-default-value-for-when-the-env-variable-is-not-required)\n    - [Providing a custom parser](#providing-a-custom-parser)\n    - [Usage with Dotenv](#usage-with-dotenv)\n    - [Providing your own processEnv object](#providing-your-own-processenv-object)\n  - [FAQ](#faq)\n    - [Where should I call `makeEnv` in my application?](#where-should-i-call-makeenv-in-my-application)\n    - [Does it support changing env variables dynamically?](#does-it-support-changing-env-variables-dynamically)\n    - [Can I use the `debug` module with `environment`?](#can-i-use-the-debug-module-with-environment)\n    - [Can I have more than one env object per application?](#can-i-have-more-than-one-env-object-per-application)\n  - [Node.js support](#nodejs-support)\n  - [Contributing](#contributing)\n  - [Maintainers](#maintainers)\n  - [Who's using environment](#whos-using-environment)\n  - [Related libraries](#related-libraries)\n  - [License](#license)\n\n## Installation\n\nWith [Yarn](https://yarnpkg.com/):\n\n```bash\nyarn add @strattadb/environment\n```\n\nor with npm:\n\n```bash\nnpm install @strattadb/environment\n```\n\n## Usage\n\nAn example `env.js` file:\n\n```javascript\n// env.js\n\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv({\n  nodeEnv: {\n    parser: parsers.whitelist(['production', 'development', 'test']),\n    required: true,\n    envVarName: 'NODE_ENV',\n  },\n  port: {\n    parser: parsers.port,\n    required: false,\n    defaultValue: 4000,\n    envVarName: 'PORT',\n  },\n});\n\nexport default env;\n```\n\nNow in a file:\n\n```javascript\n// otherFile.js\n\nimport env from './env';\n\nconsole.log(env.nodeEnv); // development\nconsole.log(typeof env.nodeEnv); // string\n\nconsole.log(env.port); // 4000\nconsole.log(typeof env.port); // number\n```\n\n## Examples\n\n- [Simple HTTP server](examples/server)\n\n## API\n\n### `makeEnv(schema: Schema, processEnv?: { [key: string]: string | undefined }): Env`\n\nEnsures required env variables are present and returns an env object.\n\nSupports passing a processEnv object as the second argument.\nIf it's not passed, it uses `process.env`.\nThis object will be used to look up the environment variables.\n\n- **Schema**:\n\n  - **\\[key: string\\]**: `object` - The `key` will be accessible\n    in the returning env object.\n    - **parser**: `function` - A function that takes a string and can return anything.\n      The return value will be accesible in `env[key]`.\n      If the argument is not valid, it should throw.\n    - **required**: `boolean` - Whether or not the env variable is required.\n      If the value `true` and the env variable is not set, it'll throw.\n      If the value is `false` it'll look for the env variable in `process.env`,\n      if isn't set, it'll use `defaultValue`.\n    - **defaultValue**: `any?` - Only valid if `required: false`.\n      This is the default value of the env variable if it's not set.\n      It won't be parsed or validated.\n    - **envVarName**: `string` - The name of the env variable to look up\n      (`process.env[envVarName]`).\n    - **description**: `string?` - Helper text describing the variable.\n\n- **Env**:\n\n  - **\\[key: string\\]**: `any` - The keys are the same as the ones in the schema.\n\n### Parsers\n\n#### `parsers.string(value: string): string`\n\nTrivial parser. It doesn't do any validation.\n\n#### `parsers.boolean(value: string): boolean`\n\nEnsures the value is a truthy or falsy value.\n\nTruthy values: `'true'`, `'1'`, `'yes'`, `'on'`.\n\nFalsy values: `'false'`, `'0'`, `'no'`, `'off'`.\n\n#### `parsers.integer(value: string): number`\n\nEnsures the value is an integer.\n\n#### `parsers.float(value: string): number`\n\nEnsures the value is a float.\n\n#### `parsers.email(value: string): string`\n\nEnsures the value is an email.\n\n#### `parsers.url(value: string): string`\n\nEnsures the value is a url.\n\n#### `parsers.ipAddress(value: string): string`\n\nEnsures the value is an IP address.\n\n#### `parsers.port(value: string): number`\n\nEnsures the value is a port.\n\n#### `parsers.whitelist(whitelistedValues: string[]): Parser\u003cstring\u003e`\n\nTakes a list of valid values and returns a parser that\nensures the value is in the whitelist.\n\nExample:\n\n```javascript\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv({\n  color: {\n    parser: parsers.whitelilst(['red', 'blue', 'green']),\n    required: true,\n    envVarName: 'COLOR',\n  },\n});\n```\n\n#### `parsers.regex(pattern: Regex): Parser\u003cstring\u003e`\n\nTakes a regex and returns a parser that\nensures the value matches the pattern.\n\nExample:\n\n```javascript\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv({\n  color: {\n    parser: parsers.regex(/^green$/),\n    required: true,\n    envVarName: 'COLOR',\n  },\n});\n```\n\n#### `parsers.array\u003cT\u003e({ parser: Parser\u003cT\u003e, separator?: string }): Parser\u003cT\u003e`\n\nTakes a parser and returns a parser that parses a list of values.\nThe default value separator is `,`.\n\nExample:\n\n```javascript\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv({\n  color: {\n    parser: parsers.array({ parser: parsers.integer }),\n    required: true,\n    envVarName: 'FAVORITE_NUMBERS',\n  },\n});\n```\n\n#### `parsers.positiveInteger(value: string): number`\n\nEnsures the value is a positive integer.\n\n#### `parsers.nonPositiveInteger(value: string): number`\n\nEnsures the value is a non-positive integer.\n\n#### `parsers.negativeInteger(value: string): number`\n\nEnsures the value is a negative integer.\n\n#### `parsers.nonNegativeInteger(value: string): number`\n\nEnsures the value is a non-negative integer.\n\n## Recipes\n\n### Making environment variables required\n\nIf `required` is `true` and the environment variable isn't set,\nit'll throw:\n\n```javascript\n// env.js\n\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv({\n  notSet: {\n    parser: parsers.string,\n    required: true,\n    envVarName: 'NOT_SET',\n  },\n});\n```\n\n```bash\nnode env.js\n\nEnvironmentVariableError: NOT_SET is required but is not set\n    at ...\n    ...\n```\n\n### Specifying a default value for when the env variable is not required\n\nIf the env variable is not required you must specify a default value:\n\n```javascript\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv({\n  port: {\n    parser: parsers.port,\n    required: false,\n    defaultValue: 4000,\n    envVarName: 'PORT',\n  },\n});\n\nconsole.log(env.port); // 4000\n```\n\n### Providing a custom parser\n\nA parser function must take a string value and can return anything.\nThe value you return is what you'll get in the env object.\nIf the value is not valid you should throw an error:\n\n```javascript\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv({\n  someValue: {\n    parser: (value) =\u003e {\n      if (value === 'forbiddenValue') {\n        throw new Error('value is forbidden');\n      }\n\n      return value;\n    },\n    required: true,\n    envVarName: 'SOME_VALUE',\n  },\n});\n```\n\n### Usage with [Dotenv](https://github.com/motdotla/dotenv)\n\nA common pattern is to load the env variables from a file using dotenv\nand then ensuring that the required variables are actually present:\n\n```javascript\nconst dotenv = require('dotenv');\n\ndotenv.config(); // Loads env variables from `.env` file to `process.env`.\n\nconst { makeEnv, parsers } = require('@strattadb/environment');\n\nconst env = makeEnv({\n  secretToken: {\n    parser: parsers.string,\n    required: true,\n    envVarName: 'SECRET_TOKEN',\n  },\n});\n```\n\n### Providing your own processEnv object\n\nBy default, `makeEnv` uses `process.env` to look up and get environment variables,\nbut you can pass you own processEnv object as the second argument that will\nbe used instead of `process.env`:\n\n```javascript\nimport { makeEnv, parsers } from '@strattadb/environment';\n\nconst env = makeEnv(\n  {\n    hello: {\n      parser: parsers.string,\n      required: true,\n      envVarName: 'HELLO',\n    },\n  },\n  {\n    HELLO: 'WORLD',\n  },\n);\n```\n\n## FAQ\n\n### Where should I call `makeEnv` in my application?\n\nThe best place to create the env object is very early\nin your application startup.\nEverything before you call `makeEnv` with your schema will\nnot be guaranteed to have your required env variables.\n\n### Does it support changing env variables dynamically?\n\nNo, when you create an env object it will read the value of\n`process.env` at that time. After that, if anything makes\nchanges to `process.env`, it will not be reflected in the\nenv object.\n\n### Can I use the [`debug`](https://github.com/visionmedia/debug) module with `environment`?\n\nYes! Set `DEBUG=environment`.\n\n### Can I have more than one env object per application?\n\nYes! You can have as many env objects as you want!\n\n## Node.js support\n\nNode.js version 12 or higher. Every version of this library\nis tested in Node.js 12, 14 and 16.\n\n## Contributing\n\nPRs, feature requests, bug reports, and any kind of contributions are welcome!\nSee [CONTRIBUTING.md](CONTRIBUTING.md).\n\n## Maintainers\n\n- [Diego Stratta](https://github.com/strattadb)\n\n## Who's using environment\n\n- [origen](https://github.com/origen-chat/api)\n\n## Related libraries\n\n- [Convict](https://github.com/mozilla/node-convict)\n- [Envalid](https://github.com/af/envalid)\n- [require-environment-variables](https://github.com/bjoshuanoah/require-environment-variables)\n- [Dotenv](https://github.com/motdotla/dotenv)\n\n## License\n\n[MIT](LICENSE)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdbstratta%2Fenvironment","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdbstratta%2Fenvironment","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdbstratta%2Fenvironment/lists"}