{"id":22428370,"url":"https://github.com/momsfriendlydevco/dotenv","last_synced_at":"2025-06-28T17:07:29.458Z","repository":{"id":63788045,"uuid":"570035112","full_name":"MomsFriendlyDevCo/dotenv","owner":"MomsFriendlyDevCo","description":"DotEnv with schema, validation, expiring keys and multi-input support","archived":false,"fork":false,"pushed_at":"2023-04-11T22:57:25.000Z","size":571,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-06-22T14:49:49.478Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","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/MomsFriendlyDevCo.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":"2022-11-24T07:30:43.000Z","updated_at":"2024-02-28T18:54:31.000Z","dependencies_parsed_at":"2024-10-20T19:48:08.806Z","dependency_job_id":null,"html_url":"https://github.com/MomsFriendlyDevCo/dotenv","commit_stats":{"total_commits":84,"total_committers":1,"mean_commits":84.0,"dds":0.0,"last_synced_commit":"ad33d85d2b81fb88b3a48ecae4349042a8b4d859"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/MomsFriendlyDevCo/dotenv","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fdotenv","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fdotenv/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fdotenv/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fdotenv/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MomsFriendlyDevCo","download_url":"https://codeload.github.com/MomsFriendlyDevCo/dotenv/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MomsFriendlyDevCo%2Fdotenv/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262465750,"owners_count":23315638,"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":[],"created_at":"2024-12-05T20:14:34.715Z","updated_at":"2025-06-28T17:07:29.441Z","avatar_url":"https://github.com/MomsFriendlyDevCo.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"@MomsFriendlyDevCo/DotEnv\n=========================\nDotEnv with schema, validation, expiring keys and multi-input support.\n\nFeatures:\n\n* All standard DotEnv parser / reader\n* Mongo like Schema support\n* Entirely synchronous - config is available immediately, no waiting on promises or fixing up race conditions\n* Easy config key rewriting via `.map(fn)` / `.camelCase()` / `.startCase()` etc. to make config compatible with other systems\n* Support for destructing config - wipe values like passwords or API-keys after a set interval\n\n\n```javascript\nimport dotenv from '@momsfriendlydevco/dotenv';\n\nlet config = dotenv\n    .parse(['.env.example', '.env']) // Import from one or more files in order of precidence\n    .importEnv({prefix: 'MY_APP_'}) // Import from process.env\n    .schema({ // Apply a schema\n        port: Number, // Simple schemas (`required` is implied for these)\n        host: {required: true, type: String}, // ...or be more explicit\n        password: {\n            type: 'string', // Custom support also for your own types\n            cast: v =\u003e v.toLowerCase(), // Case incoming values\n            destruct: '10s', // Variables not allowed to be read after this time from start (timestring)\n        },\n    })\n    .value() //= {host: String, port: Number, password: String}\n```\n\n\nAPI\n===\n\n\nDotEnv (default export)\n-----------------------\nReturns an instance of the DotEnv class.\n\n\nDotEnv.parse(source, options)\n----------------------\nRead files from path (or relative to current directory) in presidence order.\nSource can be a path (string with no '='), paths (an array of strings) or raw blob data (string || buffer).\n\nLater files with keys will overwrite earlier ones.\n\nOptions are:\n\n| Option              | Type                       | Default | Description                                               |\n|---------------------|----------------------------|---------|-----------------------------------------------------------|\n| `from`              | `String` / `Buffer`        |         | Source to parse instead of a file path                    |\n| `path`              | `String` / `Array\u003cString\u003e` |         | Source file(s) to parse in order (later overrides former) |\n| `allowMissing=true` | `Boolean`                  | `true`  | Skip over missing files, if falsy will throw instead      |\n\nReturns the chainable DotEnv instance.\n\n\nDotEnv.importEnv(options)\n-------------------------\nImport environment variables (from `process.env` by default).\n\nReturns the chainable DotEnv instance.\n\nValid options are:\n\n\n| Option       | Type       | Default         | Description                                                                                         |\n|--------------|------------|-----------------|-----------------------------------------------------------------------------------------------------|\n| `source`     | `Object`   | `process.env`   | Source object to import from                                                                        |\n| `prefix`     | `String`   | `''`            | Optional prefix to limit imports to                                                                 |\n| `filter`     | `Function` | `(k, v)=\u003e true` | Optional function to filter by. Called as `(key, val)`                                              |\n| `replace`    | `Function` | `(k, v)=\u003e v`    | Optional function to rewrite the value. Called as `(key, val)` and expected to return the new value |\n| `trim`       | `Boolean`  | `true`          | Try to trum whitespace from variables, if any                                                       |\n| `trimPrefix` | `Boolean`  | `true`          | If using a prefix, remove this from the final keys to merge                                         |\n\n\nDotEnv.schema(schema, options)\n------------------------------\nApply a schema to the existing internal config state.\n\nA schema is a object mapping each key to a FieldSchema.\n\nReturns the chainable DotEnv instance.\n\nFieldSchemas are made up of any of the following properties. If a simple string or built-in type is provided instead it is assumed as the `type` subkey.\n\n| Option          | Type                         | Default | Description                                                                                                                                                                                                                           |\n|-----------------|------------------------------|---------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `required`      | `Boolean`                    | `true`  | Whether the field is required                                                                                                                                                                                                         |\n| `type`          | `Array\u003c*\u003e` / `*`             |         | Either a instance of class the object (lookup table via `aliases`) or the string representation of any key in `types`                                                                                                                 |\n| `default`       | `*`                          |         | Default value to use if none is specified. If a function it is run as `(fieldSchema)` and the result used.                                                                                                                            |\n| `defaultRaw`    | `*`                          |         | Default value to use without attempting evaluate functions or perform any casting if its a string. Set this as the default and don't ask any questions                                                                                |\n| `validate`      | `Function` / `String`        |         | Function to validate an input, must return true. If a string is given the cast function is retrieved from the type instead. Called as `(value, fieldSchema)`                                                                          |\n| `cast`          | `Function` / `String`        |         | Optional function to convert user input to a native type. If a string is given the validate is retrieved from that type instead. Called as `(value, fieldSchema)` and expected to either throw or return falsy - undefined is ignored |\n| `destruct`      | `Object` / `String` / `Date` |         | Optional destruction config. See `ConfigDestruct` for details                                                                                                                                                                         |\n\nSchema options can contain:\n\n| Option   | Type      | Default | Description                                          |\n|----------|-----------|---------|------------------------------------------------------|\n| `reject` | `Boolean` | `true`  | Reject unknown fields that arn't defined in a Schema |\n\n\n### Required\nThe required boolean has the following logic:\n1. If we have a value that isn't undefined or an empty string stop here\n2. If any `default` / `defaultRaw` is specified - apply those (see next section)\n3. If no value is still set - return `undefined`\n\n\n### Defaults\nDefaults are applied with the following logic:\n1. If we have a value that isn't undefined or an empty string stop here\n2. If `defaultRaw` exists - use that\n3. If `default` exists and is a function - evaluate it first, if not contiue with the `default` value\n4. If the value from step 3 is NOT a string - assume the return value should be used as is, stop any further checks (e.g. casting, validation)\n5. If the value from step 3 is a string - assume this is the same as what would be set in the .env file and continue on to cast + validate etc.\n\n\nDotEnv.schemaGlob(glob, schema)\n-------------------------------\nApply a schema to all config keys matching a glob, array of globs or a RegExp.\n\n\nDotEnv.export(options)\n----------------------\nExport the current config to a string.\n\nOptions are:\n\n| Option          | Type       | Description                                                                        |\n|-----------------|------------|------------------------------------------------------------------------------------|\n| `header`        | `RegExp`   | How to extract section headers as a RegExp with a capture group or null to disable |\n| `headerFormat`  | `Function` | Function to format headers. Called as `(headerTitle)`                              |\n| `headerSpacing` | `Number`   | How many lines of spacing should be inserted before each (new) header              |\n| `rewritePair`   | `Function` | Function to rewrite a single `key=val` set                                         |\n\n\nDotEnv.exportFile(path, options)\n--------------------------------\nUtility function to call `.export()` and dump the contents into a file.\n\n\nDotEnv.deep(value)\n------------------\nIndicates that key mutation functions (see below) should operate on nested objects.\nSet to any falsy value to revert to only applying mutations to top level keys only.\nReturns the DotEnv instance.\n\n\nDotEnv.mutateKeys(alias, args)\n------------------------------\nApply `camelCase`, `startCase` or `envCase` (with options) to all keys, returning the DotEnv instance.\n\n\nDotEnv.camelCase() / DotEnv.startCase(spacing=false) / DotEnv.envCase()\n-----------------------------------------------------------------------\nMutate the config keys by applying a common string mutator, returning the DotEnv instance.\n\n\nDotEnv.replace(match, replacement)\n----------------------------------\nApply a replacement to all config keys, returning the DotEnv instance.\n\n\nDotEnv.filter(match)\n------------------\nRemove all config keys that either dont have the string prefix or don't match a given RegEx, returning the DotEnv instance.\n\n\nDotEnv.trim(match)\n------------------\nApply a replacement to all config keys removing a given String prefix / RegExp match, returning the DotEnv instance.\n\n\nDotEnv.filterAndTrim(match, replacement)\n----------------------------------------\nApply both a filter + trim to a config keys - removing all config that doesnt match the string prefix (or RegEx) whilst also removing the given prefix (or RegExp).\nReturns the DotEnv instance.\n\n\nDotEnv.template(context)\n------------------------\nApplies a JavaScript string template (via [@MomsFriendlyDevCo/Template](https://github.com/MomsFriendlyDevCo/template)) to all values with the given context.\nIf no context is provided the current state is used.\nReturns the DotEnv instance.\n\n\nDotEnv.map(func)\n----------------\nRun a function on all state config keys, potencially mutating the key / value. Returns the DotEnv instance afterwards.\n\n* If the function returns a tuple array its assumed to mutate the key+val of the input config key+val combo\n* If the function returns a object, that object return (all keys) replace the state for that config key\n* If the function returns boolean `false` the key is removed completely\n* If the funciton returns boolean `true` OR undefined, no action or mutation is taken\n\n\nDotEnv.tap(fn)\n--------------\nRun an arbitrary function passing in this DotEnv instance as the first argument and context.\nReturns the chainable DotEnv instance.\n\n```javascript\nnew DotEnv()\n    .parse(...)\n    .tap(dotEnv =\u003e console.log('Raw config:', dotEnv.value())\n    .toTree(/_/)\n    .tap(dotEnv =\u003e console.log('Config as a tree:', dotEnv.value())\n    .value()\n```\n\nNote that if you intend to copy the state inside `tap()` it is advisable to use `.value({clone: true})` as functions such as `.toTree()` mutate sub-keys which can change state.\n\n\nDotEnv.thru(fn)\n---------------\nLike `DotEnv.tap(fn)` only the return value is used as the new state.\nReturns the chainable DotEnv instance.\n\n\nDotEnv.toTree(options)\n----------------------\nTransform a flat key/val config item a hierarchical object-of-objects based on rules.\nReturns the chainable DotEnv instance.\n\n```javascript\nlet result = new DotEnv()\n    .parse([\n        'FOO_BAR_FOO=Foo!',\n        'FOO_BAR_BAR=123',\n        'FOO_BAR_BAZ=true',\n        'BAR_BAR_FOO=Foo2!',\n        'BAR_BAR_BAR=456',\n        'BAR_BAR_BAZ=false',\n    ].join('\\n'))\n    .toTree(/_/)\n    .value()\n\n/**\n// Will return\n{\n    FOO: {\n        BAR: {\n            FOO: 'Foo!',\n            BAR: '123',\n            BAZ: 'true',\n        },\n    },\n    BAR: {\n        BAR: {\n            FOO: 'Foo2!',\n            BAR: '456',\n            BAZ: 'false',\n        },\n    },\n}\n```\n\nOptions are:\n\n| Option        | Type                       | Default    | Description                                                                                 |\n|---------------|----------------------------|------------|---------------------------------------------------------------------------------------------|\n| `branches`    | `Function`                 |            | A RegExp where each capture group denotes a branch of a tree                                |\n| `splitter`    | `Function`                 |            | A RegExp to split keys by a given string                                                    |\n| `rewrite`     | `Function` / `RegExp`      |            | Run a given funciton (or replacement RegExp) over each extracted key segment                |\n| `matching`    | `String`                   | `'remove'` | Operation to perform on matching keys. ENUM: `'keep'`, `'remove'`     |\n| `nonMatching` | `String`                   | `'remove'` | Operation to perform on non-matching keys (branching method only). ENUM: `'keep'`, `'remove'` |\n| `prefix`      | `String` / `Array\u003cString\u003e` | `''`       | Optional path segment prefix when setting keys                                              |\n| `clear`       | `Boolean`                  | `false`    | Start with a blank tree, if falsey will instead muatete the existing state                  |\n\n\nDotEnv.value(options)\n---------------------\nReturn the final, computed config object.\n\n\nOptions are:\n\n| Option  | Type      | Default | Description                                                                   |\n|---------|-----------|---------|-------------------------------------------------------------------------------|\n| `clone` | `Boolean` | `false` | Return a deep clone of the value - this prevents future mangling via toTree() |\n\n\nBuilt in types\n--------------\nThe following is a list of built in types which provide a handy shorthand for various functionality.\n\n\n| Type       | Example                                                     | Notes                                               | Additional properties                                                                                                                                                                                                                                                  |\n|------------|-------------------------------------------------------------|-----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| `any`      | `KEY=something `                                            | Any type is valid                                   |                                                                                                                                                                                                                                                                        |\n| `array`    | `KEY=foo,Bar, Baz`                                          | CSV of string values                                | `min` / `max` for array length                                                                                                                                                                                                                                         |\n| `boolean`  | `KEY=yes` / `KEY=true`                                      | Parse common 'truthy' strings into a boolean        | `true=[...]`, `false=[]` (accepted strings to validate true / false                                                                                                                                                                                                    |\n| `date`     | `KEY=2022-12-06` / `KEY=2022-12-06T13:20+10:00`             | Parse Date-like or ISO dates into a Date object `   | `min` / `max` for date period                                                                                                                                                                                                                                          |\n| `duration` | `KEY=2h37m`                                                 | Parse a valid timestring duration into milliseconds | `unit=ms` for the unit to parse to                                                                                                                                                                                                                                     |\n| `email`    | `KEY=a@b.com` / `KEY=Simon Jones \u003csimon@thing.com\u003e`         | A single email in short or long form                | `name=true` to allow a long form address                                                                                                                                                                                                                               |\n| `emails`   | `KEY=a@b.com, someone@somewhere.com, J Smith \u003cj@smith.com\u003e` | A CSV of email addreses                             | `name=true` to allow a long form address                                                                                                                                                                                                                               |\n| `file`     | `KEY=/some/path/file.txt`                                   | A file on disk, read into the value                 | `buffer=true` or `string=true` to describe how to read the file                                                                                                                                                                                                        |\n| `float`    | `KEY=3.1415`                                                | Any floating value                                  | `min` / `max` for value                                                                                                                                                                                                                                                |\n| `keyvals`  | `KEY=key1=val1, key2 = val 2, key3=val3`                    | An object composed of key=vals                      | `min` / `max` for key count, `noValue` to specify the content if only the key portion of the spec is given but not a value (e.g. `key4`)                                                                                                                               |\n| `mongoUri` | `KEY=mongodb+src://URL...`                                  | A valid MongoDB URI                                 |                                                                                                                                                                                                                                                                        |\n| `number`   | `KEY=123`                                                   | A string parsed into a number                       | `float` to accept floating values, `min` / `max` for value                                                                                                                                                                                                             |\n| `object`   |                                                             | Alias for `keyvals`                                 |                                                                                                                                                                                                                                                                        |\n| `percent`  | `KEY=10%`, `KEY=10`                                         | A string parsed into a number (with suffix removed) | `float` to accept floating values, `min` / `max` for value                                                                                                                                                                                                             |\n| `regexp`   | `KEY=/^a(.)c$/i`                                            | RegExp with surrounding slashes                     | `surrounds=true` to accept raw strings without '/' surroundings, `flags` to set default flags (e.g. `flags=i`), `allowPlain=true` (with `surrounds=true`) to parse non-surround strings as plain-text, `plainPrefix` + `plainSuffix` to decorate the plain text RegExp |\n| `set`      | `KEY=foo, bar, baz`                                         | CSV of values cast into a Set                       | `min` / `max` for value count                                                                                                                                                                                                                                          |\n| `string`   | `KEY=some long string`                                      | Any valid string                                    | `enum` for an array of values, `min` / `max` for string length                                                                                                                                                                                                         |\n| `style`    | `KEY=bold red` / `KEY=bgwhite + yellow`                     | Chalk compatible color styling                      |                                                                                                                                                                                                                                                                        |\n| `uri`      | `KEY=https://somewhere.com`                                 | A valid URI                                         | `parse=false` to specify that the parsed URL object should be returned rather than the string                                                                                                                                                                          |\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmomsfriendlydevco%2Fdotenv","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmomsfriendlydevco%2Fdotenv","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmomsfriendlydevco%2Fdotenv/lists"}