# n8n Integration with your app database

This guide shows how to connect n8n workflows to your Vibecarbon application's database.

## Overview

n8n is pre-configured with:
- Dedicated PostgreSQL database (`n8n`) for workflow storage
- Environment variables for connecting workflows to your app's database
- Network access to your app's services

## Quick Start

### 1. Access n8n

```bash
# Start services (if not already running)
pnpm docker:up

# Open n8n
open http://n8n.localhost
```

**Login:** Use your admin email and the password set during project creation. In development, n8n uses its own built-in authentication (ForwardAuth SSO only applies in production).

### 2. Use your app database in workflows

On Docker Compose, n8n has these environment variables available:

```bash
APP_DB_HOST=db
APP_DB_PORT=5432
APP_DB_NAME=postgres
APP_DB_USER=n8n
APP_DB_PASSWORD=your N8N_DB_PASSWORD
```

They connect as n8n's own `n8n` role, never the `postgres` superuser. The role bypasses row-level security, so a workflow sees and can change every row of your business tables (read, insert, update, delete). It cannot read or write the server-only tables (row-level security on and no policies: the auth tables `"user"`, `session`, `account`, `verification`, `two_factor`, and `failed_login_attempts`), so passwords, sessions and tokens stay out of your workflows, and it cannot run anything a superuser can, such as shell commands through `COPY ... TO PROGRAM`. The role has its own password, `N8N_DB_PASSWORD` (generated by `vibecarbon add n8n`), never the superuser's. `volumes/db/n8n-init.sh` sets this up at the database's first boot and on every `vibecarbon up` in development, and business tables a later migration adds get the same grants. Treat any workflow that uses it as trusted code all the same: it can change any business row, including ones that steer security, such as `app_settings` (`mfa_enabled`) and `memberships.role`.

n8n encrypts the credentials it stores with `N8N_ENCRYPTION_KEY` (generated by `vibecarbon add n8n`, one per environment, shared by every server), so a promoted standby can read them. Keep a copy: without the key, saved credentials cannot be decrypted.

On Kubernetes these variables are not set. Add a Postgres credential in n8n yourself (host `db`, port `5432`), ideally with a role that has only the access your workflows need.

## Example Workflows

### Example 1: Query the database

Use the **Postgres** node:

```
Connection Settings:
- Host: {{$env.APP_DB_HOST}}
- Port: {{$env.APP_DB_PORT}}
- Database: {{$env.APP_DB_NAME}}
- User: {{$env.APP_DB_USER}}
- Password: {{$env.APP_DB_PASSWORD}}

Query:
SELECT id, name, created_at FROM organizations WHERE created_at > NOW() - INTERVAL '1 day';
```

### Example 2: Call your app's API

Use the **HTTP Request** node. `/api/todos` is a placeholder: replace it with a
route your app actually has. Your app's API routes sign people in with a
session cookie, which n8n doesn't have, so give n8n a route of its own that
checks who is calling, for example one under `/api/webhooks/` that compares a
shared secret header against a value in your app's `.env.local` (keep the same
secret in an n8n credential). Never open an unauthenticated route for this.

```
Method: POST
URL: http://app:3000/api/todos   (placeholder: your route here)

Headers:
- Content-Type: application/json

Body (JSON):
{
  "title": "New todo from n8n",
  "completed": false
}
```

### Example 3: Receive webhooks

1. Create a **Webhook** node in n8n
2. Copy the webhook URL (e.g., `http://localhost:5678/webhook/my-webhook`)
3. In your app, configure a webhook to call this URL

### Example 4: Trigger on Database Changes

Use **Postgres Trigger** node:

```
Connection Settings: (use environment variables as above)

Trigger: On Row Insert
Table: users

Returns:
- NEW row data
```

## Common Use Cases

### User Onboarding

```
Trigger: Postgres Trigger (users table insert)
Action 1: Send welcome email (Email node)
Action 2: Create user profile (HTTP Request to your API)
Action 3: Add to analytics (HTTP Request to analytics service)
```

### Scheduled Reports

```
Trigger: Cron (daily at 9 AM)
Action 1: Query database for metrics (Postgres node)
Action 2: Generate report (Code node)
Action 3: Send email (Email node)
```

### API Integration

```
Trigger: Webhook (from external service)
Action 1: Transform data (Code node)
Action 2: Insert into your database (Postgres node)
Action 3: Notify users (Push notification)
```

## Best Practices

### 1. Use Environment Variables

Instead of hardcoding credentials, always use:
```
{{$env.APP_DB_USER}}
{{$env.APP_DB_PASSWORD}}
```

### 2. Error Handling

Add **Error Trigger** nodes to handle failures gracefully.

### 3. Testing

Use the **Manual Trigger** node during development.

### 4. Security

- `APP_DB_*` is admin access to your app's data, so keep those workflows private
- Prefer a narrower database role for workflows that only need a few tables
- Never put database credentials in client-facing workflows

## Learn More

- [n8n Documentation](https://docs.n8n.io/)
