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

# Environment Variables

> Complete reference for all environment variables in the API and Web packages

The CGIAR Risk Intelligence Tool uses environment variables to configure both the API (NestJS) and Web (Next.js) packages. This guide documents all required and optional variables.

## API Environment Variables

The API package (`packages/api/`) requires environment variables for database connections, AWS service integration, and runtime configuration.

### Local Development (.env file)

For local development, create a `.env` file in `packages/api/`:

```bash theme={null}
cp packages/api/.env.example packages/api/.env
```

> [!WARNING]
>
> Never commit `.env` files to version control. Add `.env` to `.gitignore` to prevent accidental commits of sensitive credentials.

### API Variables Reference

#### Runtime Configuration

| Variable | Required | Default | Description |
| - | - | - | - |
| `NODE_ENV` | No | `development` | Runtime environment (`development`, `production`, `test`) |
| `ENVIRONMENT` | No | `development` | Application environment (`development`, `staging`, `production`) |
| `PORT` | No | `3001` | Port for local NestJS server (not used in Lambda) |

```bash theme={null}
NODE_ENV=development
ENVIRONMENT=development
PORT=3001
```

#### Database

| Variable | Required | Default | Description |
| - | - | - | - |
| `DATABASE_URL` | **Yes** | - | PostgreSQL connection string |

> [!NOTE]
>
> **Local Development:** Point to your local PostgreSQL instance.
>
> **Production:** The Lambda's `DATABASE_URL` is constructed automatically by CloudFormation using Secrets Manager for the password.

```bash Local Development theme={null}
DATABASE_URL=postgresql://postgres:yourpassword@localhost:5432/alliance_risk_dev
```

```bash RDS (Reference Only) theme={null}
# In Lambda, this is auto-constructed by CloudFormation
DATABASE_URL=postgresql://postgres:${PASSWORD}@${RDS_ENDPOINT}:5432/alliance_risk
```

> [!WARNING]
>
> **Critical for Lambda:** Without `DATABASE_URL`, Prisma falls back to `localhost` and the Lambda will fail. The CloudFormation template automatically sets this using `!Sub` with Secrets Manager resolution.

#### AWS Cognito

| Variable | Required | Default | Description |
| - | - | - | - |
| `COGNITO_USER_POOL_ID` | **Yes** | - | Cognito User Pool ID (e.g., `us-east-1_aBcDeF123`) |
| `COGNITO_CLIENT_ID` | **Yes** | - | Cognito App Client ID |
| `AWS_REGION` | **Yes** | `us-east-1` | AWS region for Cognito and other services |

```bash theme={null}
COGNITO_USER_POOL_ID=us-east-1_aBcDeF123
COGNITO_CLIENT_ID=1a2b3c4d5e6f7g8h9i0j1k2l3m
AWS_REGION=us-east-1
```

> [!NOTE]
>
> Get these values from the AWS Console → Cognito → User Pools after deploying infrastructure.

#### CORS Configuration

| Variable | Required | Default | Description |
| - | - | - | - |
| `CORS_ORIGIN` | No | `http://localhost:3000` | Comma-separated allowed origins for CORS |

```bash Local Development theme={null}
CORS_ORIGIN=http://localhost:3000
```

```bash Production theme={null}
CORS_ORIGIN=https://your-cloudfront-domain.cloudfront.net
```

```bash Multiple Origins theme={null}
CORS_ORIGIN=http://localhost:3000,https://dev.example.com,https://example.com
```

#### S3 File Storage

| Variable | Required | Default | Description |
| - | - | - | - |
| `S3_BUCKET_NAME` | **Yes** | - | S3 bucket name for file uploads |

```bash theme={null}
S3_BUCKET_NAME=alliance-risk-files-dev
```

> [!NOTE]
>
> The bucket is created by the CloudFormation stack. Reference the bucket name from the stack outputs.

#### Worker Lambda

| Variable | Required | Default | Description |
| - | - | - | - |
| `WORKER_FUNCTION_NAME` | **Yes** | - | Worker Lambda function name for async job processing |

```bash theme={null}
WORKER_FUNCTION_NAME=alliance-risk-worker
```

> [!NOTE]
>
> The API Lambda invokes the Worker Lambda asynchronously for long-running Bedrock operations. The function name is set by CloudFormation.

### Complete API .env Example

```bash theme={null}
# Environment
NODE_ENV=development
ENVIRONMENT=development
PORT=3001

# Database (replace with your local or dev connection string)
DATABASE_URL=postgresql://postgres:your_password@localhost:5432/alliance_risk_dev

# AWS Cognito
COGNITO_USER_POOL_ID=us-east-1_aBcDeF123
COGNITO_CLIENT_ID=1a2b3c4d5e6f7g8h9i0j1k2l3m
AWS_REGION=us-east-1

# CORS (comma-separated for multiple origins)
CORS_ORIGIN=http://localhost:3000

# S3
S3_BUCKET_NAME=alliance-risk-files-dev

# Worker Lambda
WORKER_FUNCTION_NAME=alliance-risk-worker
```

## Web Environment Variables

The Web package (`packages/web/`) uses Next.js and supports environment variables prefixed with `NEXT_PUBLIC_` for client-side access.

### Web Variables Reference

#### API Configuration

| Variable | Required | Default | Description |
| - | - | - | - |
| `NEXT_PUBLIC_API_URL` | No | `http://localhost:3001` | Base URL for the API backend |

```bash Local Development theme={null}
NEXT_PUBLIC_API_URL=http://localhost:3001
```

```bash Production theme={null}
NEXT_PUBLIC_API_URL=https://api.your-domain.com
```

> [!NOTE]
>
> **Client-Side Access:** Variables prefixed with `NEXT_PUBLIC_` are embedded in the browser bundle. Do NOT use this prefix for sensitive credentials.

### Complete Web .env Example

```bash theme={null}
# API Backend URL
NEXT_PUBLIC_API_URL=http://localhost:3001
```

> [!NOTE]
>
> The Web package has minimal environment configuration since it's a static export deployed to S3. Most configuration happens on the API side.

## Lambda Environment Variables (Production)

In production, Lambda functions receive environment variables through CloudFormation. You don't need to set these manually—they're configured in the infrastructure stack.

### API Lambda Environment

```yaml theme={null}
Environment:
  Variables:
    NODE_ENV: production
    ENVIRONMENT: !Ref Environment  # dev|staging|production
    DATABASE_URL: !Sub
      - "postgresql://${Username}:${Password}@${Host}:5432/alliance_risk"
      - Username: postgres
        Password: !Sub "{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"
        Host: !GetAtt Database.Endpoint.Address
    COGNITO_USER_POOL_ID: !Ref UserPool
    COGNITO_CLIENT_ID: !Ref UserPoolClient
    AWS_REGION: !Ref AWS::Region
    CORS_ORIGIN: !Ref CorsOrigin
    S3_BUCKET_NAME: !Ref FileBucket
    WORKER_FUNCTION_NAME: !Ref WorkerLambda
    AWS_ACCOUNT_ID: !Ref AWS::AccountId
```

### Worker Lambda Environment

```yaml theme={null}
Environment:
  Variables:
    NODE_ENV: production
    ENVIRONMENT: !Ref Environment
    DATABASE_URL: !Sub
      - "postgresql://${Username}:${Password}@${Host}:5432/alliance_risk"
      - Username: postgres
        Password: !Sub "{{resolve:secretsmanager:${DbSecret}:SecretString:password}}"
        Host: !GetAtt Database.Endpoint.Address
    AWS_ACCOUNT_ID: !Ref AWS::AccountId
```

> [!WARNING]
>
> **`DATABASE_URL` is critical:** Both Lambdas must have this environment variable. Without it, Prisma defaults to `localhost` and the Lambda will fail to connect to RDS.

## Environment-Specific Configuration

### Development

* Local PostgreSQL database
* API on `http://localhost:3001`
* Web on `http://localhost:3000`
* Mock AWS services or use dev AWS account

### Staging

* RDS PostgreSQL in private VPC
* API Lambda behind API Gateway
* Web static export on S3 + CloudFront
* Separate Cognito User Pool
* AWS Bedrock with dev model access

### Production

* Production RDS instance
* High-performance Lambda configurations
* Production Cognito User Pool
* CloudFront with custom domain
* Production Bedrock access

## Security Best Practices

> [!WARNING]
>
> **Never commit secrets to version control:**
>
> * Add `.env` to `.gitignore`
> * Use `.env.example` files as templates (with placeholder values)
> * Rotate credentials regularly
> * Use AWS Secrets Manager for production credentials

### What NOT to commit:

* `.env` (actual environment variables)
* Database passwords
* AWS access keys
* Cognito client secrets
* API keys or tokens

### What IS safe to commit:

* `.env.example` (template with placeholder values)
* CloudFormation templates (use `!Sub` and Secrets Manager)
* Variable names and descriptions (this documentation)

## Validation

### Check API Configuration

Verify the API can connect to services:

```bash theme={null}
# Start API server
pnpm dev:api

# Check health endpoint
curl http://localhost:3001/api/health

# Should return: {"status":"ok"}
```

### Check Web Configuration

Verify the Web app can reach the API:

```bash theme={null}
# Start both servers
pnpm dev

# Open browser console at http://localhost:3000
# Check Network tab for API calls to http://localhost:3001
```

### Check Database Connection

Test Prisma connection:

```bash theme={null}
cd packages/api
npx prisma db pull

# Should succeed without errors
```

## Troubleshooting

### "Prisma Client could not find your DATABASE\_URL"

**Cause:** `DATABASE_URL` is not set in your `.env` file.

**Solution:**

```bash theme={null}
echo 'DATABASE_URL=postgresql://postgres:password@localhost:5432/alliance_risk_dev' >> packages/api/.env
```

### "Cannot connect to Cognito"

**Cause:** Invalid `COGNITO_USER_POOL_ID` or `COGNITO_CLIENT_ID`.

**Solution:** Get correct values from AWS Console → Cognito → User Pools.

### "CORS error in browser"

**Cause:** `CORS_ORIGIN` doesn't match the frontend URL.

**Solution:** Update `CORS_ORIGIN` in `packages/api/.env`:

```bash theme={null}
CORS_ORIGIN=http://localhost:3000
```

### Lambda "Connection timeout" in production

**Cause:** Lambda can't reach RDS due to missing `DATABASE_URL` or VPC configuration.

**Solution:** Check CloudWatch logs and verify:

1. `DATABASE_URL` is set in Lambda environment
2. Lambda is in the same VPC as RDS
3. Security groups allow traffic on port 5432

## Next Steps

* [Set up local development environment](https://alliancebioversityciat-alliance-risk-analysis-tool.mintlify.site/deployment/local-development.md)
* Deploy infrastructure using CloudFormation
* Configure AWS services (Cognito, RDS, Bedrock)
* Deploy API and Web packages to AWS


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.