# Netlify

Inject KeyEnv secrets into your Netlify builds using the CLI.

Source: https://keyenv.dev/docs/sdks/netlify/

Inject KeyEnv secrets into your Netlify builds using the KeyEnv CLI.

## How It Works

The KeyEnv CLI pulls your secrets into a `.env` file before your build runs. Netlify automatically loads `.env` files during builds, making your secrets available as environment variables throughout the build process.

## Setup

### 1. Add Your Service Token to Netlify

1. Go to your KeyEnv dashboard
2. Navigate to **Settings > Service Tokens**
3. Create a new token with:
   - **Scope**: Select your project (recommended)
   - **Permissions**: `secrets:read`
4. Add the token to Netlify:
   - Go to **Site settings > Environment variables**
   - Click **Add a variable**
   - Key: `KEYENV_TOKEN`
   - Value: Your service token
   - Scopes: Select all (or specific contexts)

Also add `KEYENV_PROJECT` with your project ID if your token is not project-scoped.

### 2. Install the CLI During Build

Update your build command in `netlify.toml` to install the KeyEnv CLI and pull secrets before building:

```toml
# netlify.toml
[build]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e production -o .env && npm run build"
  publish = "dist"
```

That's it. The `keyenv pull` command writes a `.env` file that your build framework picks up automatically.

## Examples

### React / Vite

```toml
# netlify.toml
[build]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e production -o .env && npm run build"
  publish = "dist"
```

### Next.js

```toml
# netlify.toml
[build]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e production -o .env && npm run build"
  publish = ".next"

[[plugins]]
  package = "@netlify/plugin-nextjs"
```

### Gatsby

```toml
# netlify.toml
[build]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e production -o .env && gatsby build"
  publish = "public"
```

### Astro

```toml
# netlify.toml
[build]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e production -o .env && npm run build"
  publish = "dist"

[[plugins]]
  package = "@netlify/plugin-astro"
```

## Using a Build Script

For more control, create a build script:

```bash
#!/bin/bash
# scripts/netlify-build.sh
set -euo pipefail

# Install KeyEnv CLI
curl -fsSL https://keyenv.dev/install.sh | bash

# Pull secrets for the current environment
# Uses KEYENV_TOKEN and KEYENV_PROJECT from Netlify env vars
keyenv pull -e "${KEYENV_ENV:-production}" -o .env

echo "Loaded secrets from KeyEnv"

# Run the actual build
npm run build
```

Then reference it in `netlify.toml`:

```toml
[build]
  command = "bash scripts/netlify-build.sh"
  publish = "dist"
```

## Environment-Specific Builds

Use Netlify's deploy context environment variables to pull the right KeyEnv environment:

```toml
# netlify.toml
[build]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e production -o .env && npm run build"
  publish = "dist"

# Override for deploy previews
[context.deploy-preview]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e staging -o .env && npm run build"

# Override for branch deploys
[context.branch-deploy]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e development -o .env && npm run build"
```

Or use a single command with a variable:

```toml
[build]
  command = "curl -fsSL https://keyenv.dev/install.sh | bash && keyenv pull -e $KEYENV_ENV -o .env && npm run build"

[context.production.environment]
  KEYENV_ENV = "production"

[context.deploy-preview.environment]
  KEYENV_ENV = "staging"

[context.branch-deploy.environment]
  KEYENV_ENV = "development"
```

## Netlify Functions

Secrets pulled into `.env` are available to Netlify Functions at build time via `process.env`:

```javascript
// netlify/functions/api.js
export async function handler(event, context) {
  const apiKey = process.env.API_KEY;

  const response = await fetch('https://api.example.com', {
    headers: { Authorization: `Bearer ${apiKey}` }
  });

  return {
    statusCode: 200,
    body: JSON.stringify(await response.json())
  };
}
```

## Security

- The service token is stored securely in Netlify's environment variables
- Secrets are fetched over HTTPS
- The `.env` file is only present during the build and is not deployed
- Service tokens can be scoped to specific projects and environments

## Troubleshooting

### "Authentication failed"

- Verify `KEYENV_TOKEN` is set in Netlify environment variables
- Check the token has not expired
- Ensure the token is available in the deploy context you are using

### "Access denied"

- The token may not have access to the specified project
- The token may not have access to the target environment
- Check token permissions in the KeyEnv dashboard

### "Project or environment not found"

- Verify the project ID is correct
- Check that the environment name matches exactly (case-sensitive)
- Ensure the environment exists in your KeyEnv project

### Secrets not available during build

- Make sure `keyenv pull` runs **before** your build command
- Verify the `.env` file is being written to the project root
- Check the build logs for errors from the `keyenv pull` command
