> ## Documentation Index
> Fetch the complete documentation index at: https://encryptd.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# encryptd API Reference: config, encryptEnv, decryptEnv

> Complete reference for @vernonthedev/encryptd exports: config(), encryptEnv(), and decryptEnv(). Covers parameters, return types, and error handling.

`@vernonthedev/encryptd` exports three public functions. The high-level `config()` function covers the common case of loading an encrypted `.env.enc` file into your Node.js process. The lower-level `encryptEnv()` and `decryptEnv()` functions are thin TypeScript wrappers around the Rust native addon (napi-rs) and give you direct access to the AES-256-GCM primitives when you need programmatic control over encryption without involving the filesystem.

***

## `config(options?)`

`config()` reads the encrypted env file at `options.path`, decrypts it using the supplied passphrase, writes all parsed key/value pairs into `process.env`, and returns them as a plain object.

Parsing follows standard `.env` conventions: blank lines and `#` comments are ignored, quoted values have their surrounding quotes stripped, and keys that already exist in `process.env` are left untouched unless you set `override: true`.

### Parameters

<ParamField path="options" type="ConfigOptions">
  Configuration object. All fields are optional sensible defaults apply when omitted.

  <ParamField path="options.path" default=".env.enc" type="string">
    Path to the encrypted env file, resolved relative to `process.cwd()`. Accepts both relative and absolute paths.
  </ParamField>

  <ParamField path="options.passphrase" type="string">
    Passphrase used for PBKDF2 key derivation and AES-256-GCM decryption. Falls back to `process.env.ENV_PASSPHRASE` when omitted. An error is thrown if neither source provides a value.
  </ParamField>

  <ParamField path="options.override" default="false" type="boolean">
    When `false`, keys that already exist in `process.env` are preserved. Set to `true` to overwrite existing values with those from the encrypted file.
  </ParamField>
</ParamField>

### Return value

<ResponseField name="envVars" type="Record<string, string>">
  A plain object containing every key/value pair parsed from the decrypted file. All values are strings. The same pairs are also written into `process.env`.
</ResponseField>

### TypeScript example

<CodeGroup>
  ```typescript Basic call theme={null}
  import { config } from '@vernonthedev/encryptd';

  // Reads .env.enc in process.cwd(), uses ENV_PASSPHRASE from the environment
  const env = config();

  console.log(env.DATABASE_URL);
  ```

  ```typescript All options theme={null}
  import { config } from '@vernonthedev/encryptd';

  const env = config({
    path: '.env.enc',
    passphrase: process.env.MY_SECRET,
    override: false,
  });

  console.log(env.DATABASE_URL);
  ```
</CodeGroup>

***

## `encryptEnv(plainText, passphrase)`

`encryptEnv()` is a low-level Rust bridge that encrypts an arbitrary string with AES-256-GCM. It generates a fresh random 16-byte PBKDF2 salt and a fresh random 96-bit nonce on every call, so the same input always produces different ciphertext.

<Note>
  Most users will not call this function directly. Prefer the `secure-env encrypt` CLI command to produce `.env.enc` files, or call `config()` in application code. `encryptEnv()` is useful when you need to encrypt programmatically for example, in a key-rotation script.
</Note>

<CodeGroup>
  ```typescript Basic usage theme={null}
  import { encryptEnv } from '@vernonthedev/encryptd';

  const payload = encryptEnv(
    'DATABASE_URL=postgres://localhost/mydb\nAPI_KEY=abc123',
    'my-passphrase'
  );
  console.log(payload);
  // { version: 1, salt: '...', iv: '...', content: '...', tag: '...' }
  ```

  ```typescript Serialize to disk theme={null}
  import { encryptEnv } from '@vernonthedev/encryptd';
  import { writeFileSync } from 'fs';

  const payload = encryptEnv(plaintext, passphrase);
  writeFileSync('.env.enc', JSON.stringify(payload, null, 2), 'utf-8');
  ```
</CodeGroup>

### Parameters

<ParamField path="plainText" type="string" required>
  The plaintext string to encrypt. For `.env` use-cases this is the raw contents of your `.env` file, but the function accepts any UTF-8 string.
</ParamField>

<ParamField path="passphrase" type="string" required>
  Passphrase passed to PBKDF2-HMAC-SHA256 (100,000 iterations) to derive the 256-bit AES key.
</ParamField>

### Return value

<ResponseField name="payload" type="EnvPayload">
  An [`EnvPayload`](/reference/env-payload) object containing the hex-encoded salt, IV, ciphertext, and authentication tag. See the [EnvPayload reference](/reference/env-payload) for the full field listing.
</ResponseField>

***

## `decryptEnv(payload, passphrase)`

`decryptEnv()` is a low-level Rust bridge that decrypts an `EnvPayload` produced by `encryptEnv()` or by the `secure-env encrypt` CLI. The GCM authentication tag is verified automatically; if the tag does not match meaning either the wrong passphrase was supplied or the file was tampered with the function throws.

<CodeGroup>
  ```typescript Basic usage theme={null}
  import { decryptEnv } from '@vernonthedev/encryptd';
  import { readFileSync } from 'fs';

  const payload = JSON.parse(readFileSync('.env.enc', 'utf-8'));
  const plainText = decryptEnv(payload, 'my-passphrase');
  console.log(plainText);
  // DATABASE_URL=postgres://localhost/mydb
  // API_KEY=abc123
  ```

  ```typescript Round-trip example theme={null}
  import { encryptEnv, decryptEnv } from '@vernonthedev/encryptd';

  const original = 'SECRET=hunter2';
  const payload  = encryptEnv(original, 'passphrase');
  const restored = decryptEnv(payload, 'passphrase');

  console.log(original === restored); // true
  ```
</CodeGroup>

### Parameters

<ParamField path="payload" type="EnvPayload" required>
  The [`EnvPayload`](/reference/env-payload) object to decrypt. All four required fields (`salt`, `iv`, `content`, `tag`) must be present and hex-encoded.
</ParamField>

<ParamField path="passphrase" type="string" required>
  The passphrase that was used when the payload was originally encrypted. Must match exactly.
</ParamField>

### Return value

<ResponseField name="plainText" type="string">
  The decrypted UTF-8 string the original content that was passed to `encryptEnv()`.
</ResponseField>

***

## Errors

All errors thrown by `@vernonthedev/encryptd` are standard JavaScript `Error` objects. The message always starts with a source prefix `[SrcIndex]` for TypeScript-layer errors and `[RustLib]` for errors originating in the Rust native addon to make stack traces easier to read.

| Error message                                                                                  | Cause                                                                                                         |
| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `[SrcIndex] ENV_PASSPHRASE not set. Pass it via options.passphrase or ENV_PASSPHRASE env var.` | `config()` was called without a passphrase and `process.env.ENV_PASSPHRASE` is not set.                       |
| `[SrcIndex] Encrypted env file not found at <path>`                                            | The resolved file path does not exist. Check `options.path` and your working directory.                       |
| `[SrcIndex] Invalid encrypted env file at <path>. Expected valid JSON.`                        | The file exists but could not be parsed as JSON. The file may be corrupt or not an `EnvPayload`.              |
| `[RustLib] Decryption failed. Wrong key or tampered file.`                                     | The GCM authentication tag did not verify. Either the passphrase is wrong or the ciphertext was modified.     |
| `[RustLib] Invalid salt hex: ...`                                                              | The `salt` field in the payload is not valid hexadecimal. The file may be corrupt or hand-edited incorrectly. |
| `[RustLib] Invalid IV hex: ...`                                                                | The `iv` field in the payload is not valid hexadecimal. The file may be corrupt or hand-edited incorrectly.   |

<Warning>
  The `[RustLib] Decryption failed` error intentionally does not distinguish between a wrong passphrase and a tampered file. This is by design leaking which condition occurred would weaken the authentication guarantee provided by AES-GCM.
</Warning>
