{"id":13469661,"url":"https://github.com/af/envalid","last_synced_at":"2025-05-12T20:51:53.782Z","repository":{"id":5704980,"uuid":"6915703","full_name":"af/envalid","owner":"af","description":"Environment variable validation for Node.js","archived":false,"fork":false,"pushed_at":"2024-11-18T04:28:50.000Z","size":763,"stargazers_count":1435,"open_issues_count":16,"forks_count":65,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-05-03T16:03:15.471Z","etag":null,"topics":["environment","javascript","node","nodejs","validation"],"latest_commit_sha":null,"homepage":null,"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/af.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2012-11-29T05:24:45.000Z","updated_at":"2025-05-01T18:54:26.000Z","dependencies_parsed_at":"2023-09-24T10:05:37.225Z","dependency_job_id":"79fedd34-e52f-4640-81ef-69375db201f4","html_url":"https://github.com/af/envalid","commit_stats":{"total_commits":312,"total_committers":41,"mean_commits":7.609756097560975,"dds":0.3685897435897436,"last_synced_commit":"6e6f7891bc19ec95fbe92524a44fd08f3c0150f4"},"previous_names":[],"tags_count":52,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/af%2Fenvalid","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/af%2Fenvalid/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/af%2Fenvalid/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/af%2Fenvalid/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/af","download_url":"https://codeload.github.com/af/envalid/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253821330,"owners_count":21969682,"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":["environment","javascript","node","nodejs","validation"],"created_at":"2024-07-31T15:01:49.347Z","updated_at":"2025-05-12T20:51:53.759Z","avatar_url":"https://github.com/af.png","language":"TypeScript","readme":"\u003cp align=\"center\"\u003e\n  \u003cimg\n    src=\"https://raw.githubusercontent.com/af/envalid/main/.github/logo.svg\"\n    width=\"160\"\n    alt=\"Envalid text logo with drop shadow\"\n  /\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cstrong\u003e\n    Envalid is a small library for validating and accessing\u003cbr /\u003e\n    environment variables in Node.js programs\n  \u003c/strong\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/af/envalid/actions/workflows/ci.yml\"\u003e\n    \u003cimg src=\"https://github.com/af/envalid/workflows/continuous-integration/badge.svg\" alt=\"Current GitHub Build Status Badge\" /\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\nEnvalid is a small library for validating and accessing environment variables in\nNode.js programs, aiming to:\n\n- Ensure that your program only runs when all of its environment dependencies are met\n- Give you executable documentation about the environment your program expects to run in\n- Give you an immutable API for your environment variables, so they don't change\n  from under you while the program is running\n\n## Why Envalid?\n\n- Type-safe: written completely in TypeScript, with great support for inference\n- Light: no dependencies besides [tslib](https://github.com/Microsoft/tslib)\n- Modular: customize behavior with custom validators, middleware, and reporters\n\n## API\n\n### `envalid.cleanEnv(environment, validators, options)`\n\n`cleanEnv()` returns a sanitized, immutable environment object, and accepts three\npositional arguments:\n\n- `environment` - An object containing your env vars (eg. `process.env`)\n- `validators` - An object that specifies the format of required vars.\n- `options` - An (optional) object, which supports the following key:\n  - `reporter` - Pass in a function to override the default error handling and\n    console output. See `src/reporter.ts` for the default implementation.\n\nBy default, `cleanEnv()` will log an error message and exit (in Node) or throw (in browser) if any required\nenv vars are missing or invalid. You can override this behavior by writing your own reporter.\n\n```js\nimport { cleanEnv, str, email, json } from 'envalid'\n\nconst env = cleanEnv(process.env, {\n  API_KEY: str(),\n  ADMIN_EMAIL: email({ default: 'admin@example.com' }),\n  EMAIL_CONFIG_JSON: json({ desc: 'Additional email parameters' }),\n  NODE_ENV: str({ choices: ['development', 'test', 'production', 'staging'] }),\n})\n\n// Read an environment variable, which is validated and cleaned during\n// and/or filtering that you specified with cleanEnv().\nenv.ADMIN_EMAIL // -\u003e 'admin@example.com'\n\n// Envalid checks for NODE_ENV automatically, and provides the following\n// shortcut (boolean) properties for checking its value:\nenv.isProduction // true if NODE_ENV === 'production'\nenv.isTest // true if NODE_ENV === 'test'\nenv.isDev // true if NODE_ENV === 'development'\n```\n\nFor an example you can play with, clone this repo and see the `example/` directory.\n\n```\ngit clone https://github.com/af/envalid\ncd envalid\nyarn prepare\nnode example/server.js\n```\n\n## Validator types\n\nNode's `process.env` only stores strings, but sometimes you want to retrieve other types\n(booleans, numbers), or validate that an env var is in a specific format (JSON,\nURL, email address). To these ends, the following validation functions are available:\n\n- `str()` - Passes string values through, will ensure a value is present unless a\n  `default` value is given. Note that an empty string is considered a valid value -\n  if this is undesirable you can easily create your own validator (see below)\n- `bool()` - Parses env var strings `\"1\", \"0\", \"true\", \"false\", \"t\", \"f\", \"yes\", \"no\", \"on\", \"off\"` into booleans\n- `num()` - Parses an env var (eg. `\"42\", \"0.23\", \"1e5\"`) into a Number\n- `email()` - Ensures an env var is an email address\n- `host()` - Ensures an env var is either a domain name or an ip address (v4 or v6)\n- `port()` - Ensures an env var is a TCP port (1-65535)\n- `url()` - Ensures an env var is a URL with a protocol and hostname\n- `json()` - Parses an env var with `JSON.parse`\n\nEach validation function accepts an (optional) object with the following attributes:\n\n- `choices` - An Array that lists the admissible parsed values for the env var.\n- `default` - A fallback value, which will be present in the output if the env var wasn't specified.\n  Providing a default effectively makes the env var optional. Note that `default`\n  values are not passed through validation logic, they are default _output_ values.\n- `devDefault` - A fallback value to use _only_ when `NODE_ENV` is explicitly set and _not_ `'production'`.\n  This is handy for env vars that are required for production environments, but optional\n  for development and testing.\n- `desc` - A string that describes the env var.\n- `example` - An example value for the env var.\n- `docs` - A URL that leads to more detailed documentation about the env var.\n- `requiredWhen` - A function (env -\u003e boolean) specifying when this env var is required. Use With default: undefined (optional value).\n\n## Custom validators\n\n### Basic usage\n\nYou can easily create your own validator functions with `envalid.makeValidator()`. It takes\na function as its only parameter, and should either return a cleaned value, or throw if the\ninput is unacceptable:\n\n```js\nimport { makeValidator, cleanEnv } from 'envalid'\nconst twochars = makeValidator((x) =\u003e {\n  if (/^[A-Za-z]{2}$/.test(x)) return x.toUpperCase()\n  else throw new Error('Expected two letters')\n})\n\nconst env = cleanEnv(process.env, {\n  INITIALS: twochars(),\n})\n```\n\n### TypeScript users\n\nYou can use either one of `makeValidator`, `makeExactValidator` and `makeStructuredValidator`\ndepending on your use case.\n\n#### `makeValidator\u003cBaseT\u003e`\n\nThis validator has the output narrowed down to a subtype of `BaseT` (e.g. `str`).\nExample of a custom integer validator:\n\n```ts\nconst int = makeValidator\u003cnumber\u003e((input: string) =\u003e {\n  const coerced = parseInt(input, 10)\n  if (Number.isNaN(coerced)) throw new EnvError(`Invalid integer input: \"${input}\"`)\n  return coerced\n})\nconst MAX_RETRIES = int({ choices: [1, 2, 3, 4] })\n// Narrows down output type to '1 | 2 | 3 | 4' which is a subtype of 'number'\n```\n\n#### `makeExactValidator\u003cT\u003e`\n\nThis validator has the output widened to `T` (e.g. `bool`). To understand the difference\nwith `makeValidator`, let's use it in the same scenario:\n\n```ts\nconst int = makeExactValidator\u003cnumber\u003e((input: string) =\u003e {\n  const coerced = parseInt(input, 10)\n  if (Number.isNaN(coerced)) throw new EnvError(`Invalid integer input: \"${input}\"`)\n  return coerced\n})\nconst MAX_RETRIES = int({ choices: [1, 2, 3, 4] })\n// Output type is 'number'\n```\n\nAs you can see in this instance, _the output type is exactly `number`, the parameter type of\n`makeExactValidator`_. Also note that here, `int` is not parametrizable.\n\n## Error Reporting\n\nBy default, if any required environment variables are missing or have invalid\nvalues, Envalid will log a message and call `process.exit(1)`. You can override\nthis behavior by passing in your own function as `options.reporter`. For example:\n\n```js\nconst env = cleanEnv(process.env, myValidators, {\n  reporter: ({ errors, env }) =\u003e {\n    emailSiteAdmins('Invalid env vars: ' + Object.keys(errors))\n  },\n})\n```\n\nAdditionally, Envalid exposes `EnvError` and `EnvMissingError`, which can be checked in case specific error handling is desired:\n\n```js\nconst env = cleanEnv(process.env, myValidators, {\n    reporter: ({ errors, env }) =\u003e {\n        for (const [envVar, err] of Object.entries(errors)) {\n            if (err instanceof envalid.EnvError) {\n                ...\n            } else if (err instanceof envalid.EnvMissingError) {\n                ...\n            } else {\n                ...\n            }\n        }\n    }\n})\n```\n\n## Custom Middleware (advanced)\n\nIn addition to `cleanEnv()`, as of v7 there is a new `customCleanEnv()` function,\nwhich allows you to completely replace the processing that Envalid applies after applying\nvalidations. You can use this custom escape hatch to transform the output however you wish.\n\n### `envalid.customCleanEnv(environment, validators, applyMiddleware, options)`\n\n`customCleanEnv()` uses the same API as `cleanEnv()`, but with an additional `applyMiddleware`\nargument required in the third position:\n\n- `applyMiddleware` - A function that can modify the env object after it's\n  validated and cleaned. Envalid ships (and exports) its own default\n  middleware (see src/middleware.ts), which you can mix and match with your own\n  custom logic to get the behavior you desire.\n\n## Utils\n\n### testOnly\n\nThe `testOnly` helper function is available for setting a default value for an env var only when `NODE_ENV=test`. It is recommended to use this function along with `devDefault`. For example:\n\n```js\nconst env = cleanEnv(process.env, {\n  SOME_VAR: envalid.str({ devDefault: testOnly('myTestValue') }),\n})\n```\n\nFor more context see [this issue](https://github.com/af/envalid/issues/32).\n\n## FAQ\n\n### Can I call `structuredClone()` on Envalid's validated output?\n\nSince by default Envalid's output is wrapped in a Proxy, structuredClone [will not work](https://bugzilla.mozilla.org/show_bug.cgi?id=1269327#c1) on it. See [#177](https://github.com/af/envalid/issues/177).\n\n## Related projects\n\n- [dotenv](https://www.npmjs.com/package/dotenv) is a very handy tool for loading env vars from\n  `.env` files. It was previously used as a dependency of Envalid. To use them together, simply\n  call `require('dotenv').config()` before you pass `process.env` to your `envalid.cleanEnv()`.\n\n- [react-native-config](https://www.npmjs.com/package/react-native-config) can be useful for React Native projects for reading env vars from a `.env` file\n\n- [fastify-envalid](https://github.com/alemagio/fastify-envalid) is a wrapper for using Envalid within [Fastify](https://www.fastify.io/)\n\n- [nestjs-envalid](https://github.com/simenandre/nestjs-envalid) is a wrapper for using Envalid with [NestJS](https://nestjs.com/)\n\n- [nuxt-envalid](https://github.com/manuelhenke/nuxt-envalid) is a wrapper for using Envalid with [NuxtJS](https://nuxtjs.org/)\n\n## Motivation\n\nhttp://www.12factor.net/config\n","funding_links":[],"categories":["TypeScript","Input Validation \u0026 Output Encoding","nodejs"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faf%2Fenvalid","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Faf%2Fenvalid","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Faf%2Fenvalid/lists"}