# Templates — Functions

> 8 ready-made starter templates — REST APIs, WebSocket chat, AI streaming, multiplayer games, and more. One command to start.

Every template is a complete, working project. Run `aerostack init`, pick a template, and you have a deployable app in seconds — with tests, dev server, and all bindings pre-configured.

```bash
aerostack init my-app --template <template-name>
cd my-app && npm install && aerostack dev
```

Or just run `aerostack init` and pick from the interactive menu.

---

## Quick Reference

| Template | What It Builds | DB | WebSocket | AI | Cache | Queue | Streaming |
|---|---|---|---|---|---|---|---|
| `blank` | Minimal Worker starter | D1 | — | Yes | Yes | Yes | — |
| `api` | REST API (Hono) | D1 | — | Yes | Yes | Yes | — |
| `api-neon` | REST API + Postgres | Neon | — | Yes | Yes | Yes | — |
| `ws-chat` | Group chat room | — | Yes | — | Yes | — | — |
| `ws-chat-neon` | Group chat + durable history | Neon | Yes | — | — | — | — |
| `ws-voice-agent` | Conversational AI agent | — | Yes | Yes | Yes | — | — |
| `ws-multiplayer-game` | Multiplayer state sync | — | Yes | — | Yes | — | — |
| `ai-stream` | SSE AI streaming | — | — | Yes | — | — | Yes |

---

## REST & API Templates

### blank — Minimal Worker

The simplest starting point. A single file with demo routes for every platform binding.

```bash
aerostack init my-app --template blank
```

**Routes included:**
- `GET /` — health check
- `GET /test/db` — D1 database CRUD demo (create table, insert, select)
- `GET /test/cache` — KV get/set demo
- `GET /test/ai` — AI inference demo
- `POST /test/queue` — background job enqueue demo

**Bindings:** `DB` (D1), `CACHE` (KV), `QUEUE`

**Best for:** Learning Aerostack, exploring bindings, building from scratch.

---

### api — REST API with Hono

A production-ready REST API server with Hono framework, D1 database, and structured routing.

```bash
aerostack init my-app --template api
```

**Routes included:**
- `GET /` — welcome message
- `GET /health` — JSON health check
- `GET /notes` — list notes from D1
- `POST /notes` — create a note
- `GET /users/:id` — parameterized endpoint
- `GET /test/cache` — KV demo
- `GET /test/ai` — AI proxy
- `POST /test/queue` — queue producer

**Bindings:** `DB` (D1), `CACHE` (KV), `QUEUE`

**Includes:**
- `shared/db.ts` — D1 schema + table initialization
- `shared/tracing.ts` — request/error logging utilities
- Pre-configured Vitest with Workers pool

**Best for:** API backends, CRUD apps, form handlers, any project that needs a database.

---

### api-neon — REST API with Neon PostgreSQL

Same production-ready API server, but backed by Neon (serverless Postgres) instead of D1. Use this when you need full PostgreSQL features.

```bash
aerostack init my-app --template api-neon
```

**Routes included:**
- `GET /` — welcome
- `GET /health` — health check
- `GET /users` — list users from Postgres
- `POST /users` — create a user
- `GET /test/cache` — KV demo
- `GET /test/ai` — AI proxy
- `POST /test/queue` — queue producer

**Bindings:** `PG` (PostgreSQL via Neon HTTP), `CACHE` (KV), `QUEUE`

  This template works with **any Postgres-compatible database** — Supabase, Railway, Render, RDS, Cloud SQL, CockroachDB. Non-Neon databases require [Cloudflare Hyperdrive](https://developers.cloudflare.com/hyperdrive/) in production. Neon uses native HTTP and needs no Hyperdrive.

**Best for:** Projects needing Postgres features (JSON columns, full-text search, stored procedures), migrating existing Postgres apps.

---

## WebSocket Templates

### ws-chat — Group Chat

Real-time group chat rooms. Messages broadcast to all connected clients. Last 20 messages stored in KV and replayed to new joiners.

```bash
aerostack init my-app --template ws-chat
```

**Endpoints:**
- `GET /` — health check
- `WS /ws/<roomId>` — WebSocket group chat

**Message protocol:**

```typescript
// Client → Server
{ "type": "join", "username": "Alice" }
{ "type": "chat", "text": "Hello!" }
{ "type": "ping" }

// Server → Client
{ "type": "joined", "userId": "...", "username": "Alice", "roomId": "general" }
{ "type": "chat", "from": "userId", "username": "Alice", "text": "Hello!", "timestamp": "..." }
{ "type": "system", "message": "Alice joined" }
{ "type": "pong" }
```

**Bindings:** `CACHE` (KV) — last 20 messages per room

**Best for:** Chat apps, notification feeds, live commenting, any real-time messaging.

---

### ws-chat-neon — Group Chat with Durable History

Same group chat, but with full message history stored in Neon PostgreSQL. Messages survive restarts and are SQL-queryable.

```bash
aerostack init my-app --template ws-chat-neon
```

**Endpoints:**
- `GET /` — health check
- `WS /ws/<roomId>` — WebSocket group chat
- `GET /rooms/<roomId>/history` — HTTP endpoint for last 50 messages

**Bindings:** `PG` (PostgreSQL via Neon)

**Key differences from `ws-chat`:**
- Auto-creates `messages` table on first use
- New joiners replay last 50 messages from DB (not 20 from KV)
- HTTP endpoint lets clients fetch history without WebSocket

**Best for:** Chat apps that need message persistence, audit logs, search across history.

---

### ws-voice-agent — Conversational AI Agent

A real-time conversational AI over WebSocket. Conversation history persisted in KV with 1-hour TTL. Reconnecting with the same `sessionId` restores full context.

```bash
aerostack init my-app --template ws-voice-agent
```

**Endpoints:**
- `GET /` — health check + usage info
- `WS /ws?sessionId=<id>` — WebSocket AI conversation

**Message protocol:**

```typescript
// Client → Server
{ "type": "user_text", "text": "What is the capital of France?" }
{ "type": "clear" }    // Reset conversation
{ "type": "ping" }

// Server → Client
{ "type": "status", "historyLength": 5, "sessionId": "abc123" }
{ "type": "assistant_text", "text": "Paris is the capital of France." }
{ "type": "pong" }
```

**Bindings:** `CACHE` (KV) — session history with 1-hour TTL

**Key features:**
- Omit `sessionId` for a fresh session (server generates one)
- Reuse `sessionId` to resume a conversation with full context
- History writes never block AI response (`ctx.waitUntil()`)

**Best for:** AI chatbots, voice agents, copilot interfaces, any conversational AI product.

---

### ws-multiplayer-game — Multiplayer State Sync

Real-time multiplayer state synchronization. Player positions broadcast to all connected clients. Room state snapshotted to KV after every event.

```bash
aerostack init my-app --template ws-multiplayer-game
```

**Endpoints:**
- `GET /` — health check
- `GET /rooms/<roomId>` — HTTP snapshot of current players (pre-load before connecting)
- `WS /ws/<roomId>` — WebSocket state sync

**Message protocol:**

```typescript
// Client → Server
{ "type": "join", "name": "Alice" }
{ "type": "move", "x": 10, "y": 20 }
{ "type": "chat", "text": "hi" }
{ "type": "ping" }

// Server → Client
{ "type": "joined", "playerId": "uuid", "name": "Alice", "roomId": "demo-room" }
{ "type": "state", "players": [{ "id": "...", "name": "Alice", "x": 10, "y": 20 }] }
{ "type": "chat", "from": "playerId", "text": "hi" }
{ "type": "system", "message": "Bob left" }
```

**Bindings:** `CACHE` (KV) — room state snapshots

**Key features:**
- Every join/move/leave updates KV snapshot
- HTTP `GET /rooms/<roomId>` pre-loads full state for new clients
- Snapshots never block broadcasts (`ctx.waitUntil()`)

**Best for:** Multiplayer games, collaborative editors, live cursors, shared whiteboards.

---

## AI Templates

### ai-stream — SSE AI Streaming

Token-by-token AI response streaming over Server-Sent Events (SSE). The standard pattern for chat UIs, copilots, and progressive output.

```bash
aerostack init my-app --template ai-stream
```

**Endpoints:**
- `GET /generate?prompt=...` — non-streaming AI response (for testing)
- `POST /stream` — SSE streaming endpoint

**SSE event format:**

```
event: start
data: {"message":"Generating..."}

event: token
data: {"token":"Paris","text":"Paris"}

event: token
data: {"token":" is","text":"Paris is"}

event: done
data: {"text":"Paris is the capital of France."}
```

| Event | When | Data |
|---|---|---|
| `start` | Before AI call | `{ message }` |
| `token` | Each chunk | `{ token, text }` — `text` is accumulated so far |
| `done` | After last token | `{ text }` — full response |
| `error` | On failure | `{ message }` |

**Bindings:** AI (via `@aerostack/sdk`)

**Key features:**
- Uses `TransformStream` for reliable Workers streaming
- Standard SSE format — works with `EventSource` and `fetch`
- Extensible to multi-turn conversations via `sdk.ai.chat()`

**Best for:** Chat UIs, AI copilots, progressive text generation, any frontend that needs streaming responses.

---

## Using Any Template

Every template follows the same workflow:

### 1. Initialize

```bash
aerostack init my-app --template api
cd my-app
```

Or use the interactive menu:

```bash
aerostack init my-app
# → Select database (D1 or Neon)
```

### 2. Install dependencies

```bash
npm install
```

### 3. Set up local environment

Copy the example environment file:

```bash
cp .dev.vars.example .dev.vars
```

Edit `.dev.vars` with your credentials:

```bash
# .dev.vars — local secrets (never commit this file)
AEROSTACK_PROJECT_ID=your-project-id
AEROSTACK_API_KEY=your-api-key

# Only for Neon templates:
DATABASE_URL=postgres://user:pass@ep-xxx.us-east-2.aws.neon.tech/mydb
```

### 4. Run locally

```bash
aerostack dev
# or
npm run dev
```

Your app is running at `http://localhost:8787`.

### 5. Run tests

```bash
npm test
# or
npm run test:watch
```

Every template includes sample tests using Vitest with the Cloudflare Workers pool.

### 6. Link to a project

```bash
aerostack link --write-toml
```

This writes your project ID into `aerostack.toml` so deploys go to the right place.

### 7. Deploy

```bash
aerostack deploy
```

Live on Cloudflare's edge in 300+ data centers.

### 8. Set production secrets

```bash
aerostack secrets set AEROSTACK_API_KEY
# For Neon templates:
aerostack secrets set DATABASE_URL
```

  Never commit `.dev.vars`. It contains your local credentials. Every template includes it in `.gitignore` by default.

---

## Database Selection

When running `aerostack init`, you choose a database:

### D1 (SQLite at the Edge) — Default

- Zero config, zero latency (in-process binding)
- SQLite syntax
- Best for most projects
- Templates: `blank`, `api`, `ws-chat`

### Neon (Serverless PostgreSQL)

- Full Postgres features (JSON, full-text search, extensions)
- HTTP connection — no TCP required on Workers
- Best for Postgres-dependent apps or migrating existing data
- Templates: `api-neon`, `ws-chat-neon`

  You can always add an external database later. See [External Databases](/functions/external-databases) for connecting Neon, Turso, Supabase, MongoDB, and more to any template.
