> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# Local Secrets

During local development, tsdevstack stores secrets in JSON files and provides them to services through a consistent interface. This page covers how to work with secrets in your local environment.

## The Secrets Files

After running `npx tsdevstack generate-secrets`, you will have these files in your project root:

```
.secrets.tsdevstack.json  # Framework-generated secrets (do not edit)
.secrets.user.json        # Your custom secrets (edit this one)
.secrets.local.json       # Merged output (do not edit)
.env                      # Docker/Kong variables (generated from secrets)
apps/auth-service/.env    # Per-service env (DATABASE_URL for Prisma, etc.)
apps/frontend/.env        # Frontend env (API_URL, token TTLs, etc.)
```

All of these files are gitignored. The per-app `.env` files are generated by `generate-secrets` so that tools like Prisma CLI and Next.js can read environment variables directly. Backend services should still use `SecretsService` at runtime — the `.env` files exist for CLI tools (e.g., `npx prisma studio`) and frontend builds.

## Adding Your Own Secrets

To add a custom secret, edit `.secrets.user.json`. Where you put the value decides which backend services can read it:

```json
{
  "secrets": {
    "SENTRY_DSN": "https://...@sentry.io/123"
  },
  "offers-service": {
    "STRIPE_API_KEY": "sk_test_your_key_here"
  }
}
```

- **The top-level `secrets` object is shared.** Every backend service can read `SENTRY_DSN`.
- **A value in a service's section belongs to that service.** Only `offers-service` reads `STRIPE_API_KEY`, locally and in the cloud.

Then regenerate:

```bash
npx tsdevstack generate-secrets
```

In the cloud, `cloud-secrets:push` asks for each environment's value and puts it in the same scope. Top-level secrets go to shared. A service section's values go to that service's scope. To set one directly:

```bash
npx tsdevstack cloud-secrets:set STRIPE_API_KEY --service offers-service --env prod
```

See [How Secrets Work](/docs/secrets/how-secrets-work.md#each-service-reads-shared-secrets-and-its-own).

In the cloud's secret store, the scope is part of the name: `{projectName}-{scope}-{KEY}`. With a project named `myapp`, `SENTRY_DSN` is stored as `myapp-shared-SENTRY_DSN` and `STRIPE_API_KEY` as `myapp-offers-service-STRIPE_API_KEY` (hyphens instead of underscores on Azure). You only need these names when you create a secret in the cloud console yourself, for example before the first CI deployment. See [Secret Naming in Cloud](/docs/secrets/cloud-secrets.md#secret-naming-in-cloud).

Values in a frontend's or a worker's section stay local. In the cloud, a frontend gets the shared keys listed in its `secrets` array, and a worker reads its base service's scope. `cloud-secrets:push` lists these values so you can move them.

Frontends (Next.js, SPA) work differently. Their section's `secrets` array lists the shared keys they get as environment variables at deploy, for example `"frontend": { "secrets": ["SENTRY_DSN"] }`. Backends ignore this array. They read the shared scope and their own at runtime.

## Overriding Framework Defaults

You can override any framework-generated value by adding it to your user file:

```json
{
  "secrets": {
    "REDIS_HOST": "my-redis.example.com",
    "ACCESS_TOKEN_TTL": "1800"
  }
}
```

Your values always take precedence over framework defaults.

## Accessing Secrets in Backend Services

Backend services (NestJS) use the `SecretsService` to access secrets. Never use `process.env` directly.

```typescript
import { Injectable } from '@nestjs/common';
import { SecretsService } from '@tsdevstack/nest-common';

@Injectable()
export class PaymentService {
  constructor(private readonly secrets: SecretsService) {}

  async processPayment() {
    const stripeKey = await this.secrets.get('STRIPE_API_KEY');
    // Use the key...
  }
}
```

This pattern ensures your code works the same way locally and in production.

## Accessing Secrets in Frontend (Next.js)

Frontend applications receive secrets through generated `.env` files. Access them via `process.env`:

```typescript
const API_URL = process.env.API_URL;
const ACCESS_TOKEN_TTL = parseInt(process.env.ACCESS_TOKEN_TTL || '900', 10);
```

To add a secret to your frontend, update `.secrets.user.json`:

```json
{
  "frontend": {
    "secrets": ["API_URL", "ACCESS_TOKEN_TTL"]
  }
}
```

## Accessing Secrets in SPAs ([Rsbuild](https://rsbuild.dev/))

SPAs receive secrets through generated `.env` files (created by `generate-secrets` based on your secrets configuration) and expose them via build configuration:

```typescript
// In your SPA code
const API_URL = import.meta.env.API_URL;
```

Configure which env vars are bundled in your `rsbuild.config.js`:

```javascript
import { defineConfig, loadEnv } from '@rsbuild/core';

const { publicVars } = loadEnv();

export default defineConfig({
  source: {
    define: {
      ...publicVars,
      'import.meta.env.API_URL': JSON.stringify(process.env.API_URL),
    },
  },
});
```

**Security note**: Any secret exposed to an SPA is visible in the browser. Only expose values that are safe to be public, like API URLs.

## Common Workflows

### Initial Setup

```bash
npx tsdevstack sync
npm run dev
```

The `sync` command generates secrets, Kong configuration, and other required files.

### Adding a New Third-Party Service

1. Add the API key to the section of the service that calls the third party, in `.secrets.user.json`:

```json
{
  "auth-service": {
    "TWILIO_API_KEY": "your_key"
  }
}
```

2. Regenerate:

```bash
npx tsdevstack generate-secrets
```

The service picks the value up within a minute, without a restart. `SecretsService` caches values for a minute locally.

3. Access in your service:

```typescript
const twilioKey = await this.secrets.get('TWILIO_API_KEY');
```

## Troubleshooting

### "SECRETS_PROVIDER not set"

Run `npx tsdevstack generate-secrets` to create the necessary files.

### Secret Not Available in Service

1. Check that the secret is in `.secrets.user.json`, in the top-level `secrets` object (shared) or in this service's section. A service can't read a value in another service's section
2. For a frontend, check that the key is in its `secrets` array
3. Regenerate with `npx tsdevstack generate-secrets`
4. Backends see the change within a minute; restart a frontend

### Changes Not Taking Effect

After modifying `.secrets.user.json`:

1. Run `npx tsdevstack generate-secrets`
2. Wait up to 1 minute for the cache to refresh (SecretsService has a 1-minute TTL)

**Note:** Backend services using `SecretsService` automatically reload secrets from the file when the cache expires. Restarting is only needed if you're using `process.env` directly (which you shouldn't in backend services).
