# FreeLLMAPI Environment Variable for API Key Encryption: ENCRYPTION_KEY Setup Guide

> Learn how to set up the ENCRYPTION_KEY environment variable for FreeLLMAPI to securely encrypt your provider API keys at runtime. Follow our simple setup guide.

- Repository: [Tashfeen/freellmapi](https://github.com/tashfeenahmed/freellmapi)
- Tags: how-to-guide
- Published: 2026-06-27

---

**FreeLLMAPI requires the `ENCRYPTION_KEY` environment variable—a 64-character hexadecimal string—to symmetrically encrypt stored provider API keys at runtime.**

The **ENCRYPTION_KEY** environment variable is mandatory for securing API credentials in the FreeLLMAPI open-source project. This variable supplies the raw 32-byte encryption key used by the server’s cryptographic utilities to protect sensitive provider tokens at rest. Production deployments will fail to start if this variable is missing or improperly formatted, ensuring no unencrypted keys persist in the database.

## Why ENCRYPTION_KEY is Required

FreeLLMAPI stores provider API keys (such as OpenAI, Anthropic, or Google keys) in an encrypted format to prevent unauthorized access. The encryption relies on a symmetric key that must be supplied via the **ENCRYPTION_KEY** environment variable at startup.

According to the source code in [`server/src/lib/crypto.ts`](https://github.com/tashfeenahmed/freellmapi/blob/main/server/src/lib/crypto.ts), the application reads `process.env.ENCRYPTION_KEY` during initialization to create the cipher key used for AES-256-GCM operations. Without this variable, the cryptographic utilities cannot initialize, leaving the system unable to securely store or retrieve provider credentials.

## Validating the ENCRYPTION_KEY Format

The environment variable must adhere to strict formatting rules to ensure cryptographic strength:

- **Length**: Exactly 64 characters (representing 32 bytes in hexadecimal)
- **Format**: Valid hexadecimal characters (`0-9`, `a-f`, `A-F`)
- **Validation**: The `initEncryptionKey()` function in [`server/src/lib/crypto.ts`](https://github.com/tashfeenahmed/freellmapi/blob/main/server/src/lib/crypto.ts) validates these constraints using regex and length checks

If the variable is unset or contains an invalid format in production, the server throws an error and exits immediately to prevent insecure operation.

## How to Generate a Production-Ready ENCRYPTION_KEY

You can generate a valid 64-character hex key using OpenSSL or Node.js. Both methods create cryptographically secure random bytes suitable for production use.

Using OpenSSL (recommended):

```bash
ENCRYPTION_KEY=$(openssl rand -hex 32)
printf "ENCRYPTION_KEY=%s\nPORT=3001\n" "$ENCRYPTION_KEY" > .env

```

Using Node.js:

```bash
ENCRYPTION_KEY=$(node -e 'console.log(require("crypto").randomBytes(32).toString("hex"))')
printf "ENCRYPTION_KEY=%s\nPORT=3001\n" "$ENCRYPTION_KEY" > .env

```

The `.env.example` file in the repository root provides a template showing the required variable name:

```bash
ENCRYPTION_KEY=your-64-char-hex-key-here

```

## Implementation Details in the Source Code

### server/src/lib/crypto.ts

The core encryption logic resides in [`server/src/lib/crypto.ts`](https://github.com/tashfeenahmed/freellmapi/blob/main/server/src/lib/crypto.ts), where the `initEncryptionKey()` function handles validation and conversion:

```typescript
// server/src/lib/crypto.ts (excerpt)
const KEY_HEX_LEN = 64; // 32 bytes * 2 hex chars

function initEncryptionKey(): Buffer {
  const envKey = process.env.ENCRYPTION_KEY;
  if (!envKey) {
    // In dev we may auto-generate, but production must have it
    throw new Error('ENCRYPTION_KEY is required in production for API key encryption.');
  }
  if (envKey.length !== KEY_HEX_LEN || !/^[0-9a-f]+$/i.test(envKey)) {
    throw new Error(`Invalid ENCRYPTION_KEY: expected ${KEY_HEX_LEN} hex chars.`);
  }
  return Buffer.from(envKey, 'hex');
}

```

This function converts the hex string into a binary `Buffer` used by the AES-256-GCM cipher. The encryption utility then uses this key to encrypt provider tokens before database storage.

### server/src/index.ts Startup Validation

The application entry point in [`server/src/index.ts`](https://github.com/tashfeenahmed/freellmapi/blob/main/server/src/index.ts) validates the encryption key during startup. If validation fails in production, the process exits immediately to prevent the server from running with insecure encryption settings. This ensures that no API keys can be stored or accessed without proper cryptographic protection.

## Configuration Examples

When deploying FreeLLMAPI, export the variable in your environment or include it in a `.env` file:

```bash

# .env file

ENCRYPTION_KEY=abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890
PORT=3001

```

For Docker deployments, pass the variable through the environment section of your compose file or use the `--env-file` flag, as documented in [`docker/README.md`](https://github.com/tashfeenahmed/freellmapi/blob/main/docker/README.md).

## Summary

- **ENCRYPTION_KEY** is the mandatory environment variable for API key encryption in FreeLLMAPI.
- Must contain exactly **64 hexadecimal characters** (32 bytes) representing the raw encryption key.
- The server validates the format in [`server/src/lib/crypto.ts`](https://github.com/tashfeenahmed/freellmapi/blob/main/server/src/lib/crypto.ts) and exits if invalid in production.
- Generate secure keys using **OpenSSL** (`openssl rand -hex 32`) or **Node.js** (`crypto.randomBytes(32).toString('hex')`).
- Store the key in a `.env` file or export it before starting the server to ensure provider credentials encrypt at rest.

## Frequently Asked Questions

### What happens if ENCRYPTION_KEY is not set?

In production environments, the server checks `process.env.ENCRYPTION_KEY` during startup in [`server/src/index.ts`](https://github.com/tashfeenahmed/freellmapi/blob/main/server/src/index.ts) and aborts immediately if the variable is missing. This prevents the application from running without encryption capabilities. In development environments, the code may fall back to a temporary generated key, but this is insecure and unsuitable for production use.

### What format must ENCRYPTION_KEY follow?

The variable must be a **64-character hexadecimal string** (representing 32 bytes). The validation logic in [`server/src/lib/crypto.ts`](https://github.com/tashfeenahmed/freellmapi/blob/main/server/src/lib/crypto.ts) checks that the length equals 64 and that all characters match the hex pattern `/^[0-9a-f]+$/i`. Any deviation causes the server to throw an error and exit.

### Can I use the same key across multiple FreeLLMAPI instances?

Yes, you can use the same `ENCRYPTION_KEY` across multiple instances if you need them to share encrypted data or if you operate a multi-instance deployment. However, treat this key as highly sensitive—anyone with access to the key can decrypt stored API keys. Rotate keys according to your security policies and never commit the key to version control.

### Is ENCRYPTION_KEY required for development environments?

While the production startup sequence requires the variable, development environments may auto-generate a temporary key if `ENCRYPTION_KEY` is unset. However, using a persistent key even in development is recommended to ensure consistent behavior and to avoid accidental credential exposure if development databases persist between sessions.