# How to Configure AGENTMEMORY_SECRET for REST API Authentication

> Secure your AgentMemory REST API by configuring AGENTMEMORY_SECRET. Learn how to set this crucial environment variable and use it as a Bearer token for authentication.

- Repository: [Rohit Ghumare/agentmemory](https://github.com/rohitg00/agentmemory)
- Tags: how-to-guide
- Published: 2026-05-10

---

**To configure AGENTMEMORY_SECRET for REST API authentication, set the environment variable on your AgentMemory server and include it as a Bearer token in the `Authorization` header of every protected request.**

The `rohitg00/agentmemory` repository uses `AGENTMEMORY_SECRET` as a shared secret to secure its HTTP endpoints. When properly configured, the server requires this token for privileged operations, rejecting requests that lack the header or present a mismatched value. This guide covers the server configuration, client implementation, and validation logic based on the actual source code.

## Setting the AGENTMEMORY_SECRET Environment Variable

The server reads `AGENTMEMORY_SECRET` from the environment during startup. This value must be set before the process begins to ensure all authenticated endpoints are properly protected.

### Server Startup Configuration

In [`src/index.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/index.ts) at line 173, the server initializes the secret using a utility function:

```typescript
const secret = getEnvVar("AGENTMEMORY_SECRET");

```

Set the variable in your shell before launching the service:

```bash
export AGENTMEMORY_SECRET="my-strong-random-token"
npm start

```

The MCP REST proxy in [`src/mcp/rest-proxy.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/mcp/rest-proxy.ts) (line 27) also accesses this value directly:

```typescript
const secret = process.env["AGENTMEMORY_SECRET"];

```

### Using a .env File for Development

For local development, persist the secret in a `.env` file in your project root. The AgentMemory server loads environment variables automatically via `dotenv`.

```dotenv

# .env - Do not commit this file to version control

AGENTMEMORY_SECRET=my-strong-random-token

```

## Authenticating API Requests

Once the server requires `AGENTMEMORY_SECRET`, every client request to protected endpoints must include the token in the HTTP headers.

### Authorization Header Format

The server expects the following header structure:

```http
Authorization: Bearer <your-AGENTMEMORY_SECRET>

```

If this header is missing or the secret does not match the server's configuration, the API returns a 401 error with the message defined in [`src/triggers/api.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/triggers/api.ts) at line 55: `"${feature} requires AGENTMEMORY_SECRET"`.

### Client Implementation Examples

**Using curl:**

```bash
curl -X POST https://my-agentmemory.example.com/agentmemory/remember \
     -H "Authorization: Bearer my-strong-random-token" \
     -H "Content-Type: application/json" \
     -d '{"content":"hello world"}'

```

**Using JavaScript fetch:**

```javascript
const secret = "my-strong-random-token";

await fetch("https://my-agentmemory.example.com/agentmemory/remember", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    "Authorization": `Bearer ${secret}`,
  },
  body: JSON.stringify({ content: "hello world" }),
});

```

Hook scripts within the repository, such as those in [`src/hooks/session-start.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/hooks/session-start.ts), construct headers using a pattern that checks for the environment variable:

```typescript
function authHeaders(): Record<string, string> {
  const SECRET = process.env["AGENTMEMORY_SECRET"] || "";
  return SECRET ? { Authorization: `Bearer ${SECRET}` } : {};
}

```

## Server-Side Validation Logic

The authentication check compares the incoming header against the stored secret. The validation logic in the API layer performs a strict equality check:

```typescript
if (secret && req.headers.authorization !== `Bearer ${secret}`) {
  // Returns 401 with error message
}

```

This validation appears consistently across the codebase. For example, [`src/functions/mesh.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/functions/mesh.ts) at line 201 enforces this requirement with the specific error message `"mesh sync requires AGENTMEMORY_SECRET"`.

The integration test suite in [`test/integration.test.ts`](https://github.com/rohitg00/agentmemory/blob/main/test/integration.test.ts) (lines 17-18 and 230-259) verifies this behavior, ensuring that requests without the proper `Authorization: Bearer` header are rejected.

## Common Configuration Errors

Misconfiguration typically manifests as `401 Unauthorized` errors. Review these specific causes when troubleshooting:

- **Secret Mismatch**: If the client sends a different value than what the server loaded from `AGENTMEMORY_SECRET`, the request fails. Verify both sides use identical strings.
- **Missing Environment Variable**: If the server starts without `AGENTMEMORY_SECRET` exported, it may deny all privileged requests. Check that the variable is available in the server's environment before startup.
- **CI/Test Failures**: Automated test environments often lack the secret. Set `AGENTMEMORY_SECRET` in your CI configuration (via secrets management) before running `npm test`, as the integration tests expect this variable to be present.

## Summary

- Set `AGENTMEMORY_SECRET` as an environment variable before starting the AgentMemory server, or store it in a `.env` file for development.
- The server loads the secret at startup via `getEnvVar("AGENTMEMORY_SECRET")` in [`src/index.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/index.ts) (line 173).
- Include the header `Authorization: Bearer <secret>` in every HTTP request to protected endpoints.
- Ensure the client and server use the exact same secret string to avoid `401 Unauthorized` errors.
- Protected features like mesh sync explicitly require this token and return specific error messages if authentication fails.

## Frequently Asked Questions

### What happens if I don't set AGENTMEMORY_SECRET?

If `AGENTMEMORY_SECRET` is not defined in the environment, the server may start but will reject requests to protected endpoints with a `401 Unauthorized` error. According to the source code in [`src/triggers/api.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/triggers/api.ts), these endpoints return an error message stating that the feature requires `AGENTMEMORY_SECRET`.

### Can I change the AGENTMEMORY_SECRET without restarting the server?

No, the server reads `AGENTMEMORY_SECRET` during startup in [`src/index.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/index.ts) (line 173) and the MCP REST proxy loads it at line 27 of [`src/mcp/rest-proxy.ts`](https://github.com/rohitg00/agentmemory/blob/main/src/mcp/rest-proxy.ts). To apply a new secret, you must restart the AgentMemory service so it can load the updated environment variable.

### How do I debug a 401 Unauthorized error when I know the secret is set?

Verify that the value sent in the `Authorization: Bearer` header exactly matches the server's `AGENTMEMORY_SECRET`, including case sensitivity. Check that the client is not adding extra whitespace or newline characters. You can also inspect the server logs to confirm the secret was loaded at startup and that the request headers are being parsed correctly in the validation logic found in the API triggers.