# Ploy — Full Documentation > Ploy is an open-source, self-hostable serverless deployment platform. Connect a GitHub repository for automatic builds and branch deployments, run serverless workers with SQLite databases, message queues, and durable workflows, and ship AI-powered apps through a built-in OpenAI-compatible gateway. Managed user auth and a local development emulator are included. Docs: https://docs.meetploy.com · Site: https://meetploy.com This file concatenates the full text of every documentation page below. # AI Skills URL: https://docs.meetploy.com/ai-skills # AI Skills Ploy provides agent skills that give AI coding assistants the knowledge to scaffold and build applications on Ploy. These skills work with Claude Code, Cursor, Windsurf, Codex, Aider, Cline, and other AI coding tools. ## Available Skills | Skill | Description | Use When | | ----------------- | ----------------------- | --------------------------------------------- | | `worker-basic` | Basic Cloudflare Worker | Building APIs, webhooks, serverless functions | | `nextjs-app` | Next.js application | Full-stack web apps with SSR | | `db-drizzle` | Database with Drizzle | Adding persistence to workers | | `nextjs-db` | Next.js with database | Full-stack apps with data | | `queue-handler` | Message queues | Background jobs, async processing | | `workflow` | Durable workflows | Multi-step processes, sagas | | `start-framework` | Ploy Start framework | Type-safe REST APIs | ## Quick Install The easiest way to install skills is using [`add-skill`](https://github.com/anthropics/add-skill), which works with any AI coding tool: ```bash npx add-skill meetploy/ploy ``` This will prompt you to: 1. Select which skills to install 2. Choose your AI tool (Claude Code, Cursor, Windsurf, etc.) 3. Automatically install to the correct location ### Install specific skills ```bash # Install only the skills you need npx add-skill meetploy/ploy/worker-basic npx add-skill meetploy/ploy/start-framework npx add-skill meetploy/ploy/db-drizzle ``` ## Manual Installation **Claude Code** ```bash git clone https://github.com/meetploy/ploy.git /tmp/ploy mkdir -p ~/.claude/skills cp -r /tmp/ploy/skills/* ~/.claude/skills/ ``` **Cursor** Copy to your Cursor skills directory: ```bash mkdir -p ~/.cursor/skills cp -r /path/to/ploy/skills/* ~/.cursor/skills/ ``` Or add to `.cursorrules` in your project: ``` Include skills from: ./skills/ ``` **Windsurf** Add to `.windsurfrules`: ```yaml skills: - path: ./skills/worker-basic/SKILL.md - path: ./skills/start-framework/SKILL.md # Add more as needed ``` **Other Tools** For Codex, Aider, Cline, or any tool with custom instructions, add the contents of the relevant SKILL.md files to your system prompt or project context. ## Usage Examples Once skills are installed, ask your AI assistant: ### Create a Worker > "Create a new Ploy worker with health check and JSON API endpoints" The AI will use the `worker-basic` skill to scaffold: ```typescript export default { async fetch(request, env) { const url = new URL(request.url); if (url.pathname === "/health") { return Response.json({ status: "ok" }); } if (url.pathname === "/api/data") { return Response.json({ message: "Hello!" }); } return new Response("Not Found", { status: 404 }); }, } satisfies Ploy; ``` ### Add Database > "Add a users table with CRUD operations" The AI will use the `db-drizzle` skill to add: ```yaml # ploy.yaml db: DB: default ``` ```typescript // schema.ts export const users = sqliteTable("users", { id: integer("id").primaryKey({ autoIncrement: true }), name: text("name").notNull(), email: text("email").notNull().unique(), }); ``` ### Build a REST API > "Create a REST API for managing products with Ploy Start" The AI will use the `start-framework` skill: ```typescript import { ploy, withDrizzle, z } from "@meetploy/start"; const worker = ploy() .state(withDrizzle("DB", schema)) .openapi({ path: "/docs", info: { title: "Products API", version: "1.0.0" } }) .get( "/products", { response: z.object({ products: z.array(productSchema) }), }, async (ctx) => { const products = await ctx.state.db.select().from(schema.products); return { products }; }, ) .post( "/products", { body: z.object({ name: z.string(), price: z.number() }), response: z.object({ product: productSchema }), }, async (ctx) => { const [product] = await ctx.state.db .insert(schema.products) .values(ctx.body) .returning(); return { product }; }, ) .build(); ``` ### Add Background Processing > "Add a queue for processing image uploads" The AI will use the `queue-handler` skill: ```yaml # ploy.yaml queue: UPLOADS: image-uploads ``` ```typescript export default { async fetch(request, env) { const { messageId } = await env.UPLOADS.send({ type: "process-image", imageUrl: "...", }); return Response.json({ queued: true, messageId }); }, async message(event) { await processImage(event.payload); }, } satisfies Ploy; ``` ### Create a Workflow > "Build an order processing workflow with payment and shipping" The AI will use the `workflow` skill: ```typescript workflows: { order_processing: { handler: async ({ input, step, log }) => { log("Processing order", { orderId: input.orderId }); const payment = await step.run("charge", async () => { return await chargeCustomer(input.amount); }); const shipment = await step.run("ship", async () => { return await createShipment(input.address); }); await step.sleep(24 * 60 * 60 * 1000); // 24 hours await step.run("followup", async () => { await sendFollowupEmail(input.email); }); return { paymentId: payment.id, trackingNumber: shipment.tracking }; }, }, } ``` ## Skill Architecture Each skill is a markdown file with: ```yaml --- name: skill-name description: Brief description for selection --- # Skill Name Instructions for the AI on how to implement this pattern... ``` Skills include: * Project structure * Configuration files (ploy.yaml, package.json, tsconfig.json) * Code examples with TypeScript * Best practices and patterns * Common use cases ## Creating Custom Skills Add your own skills by creating markdown files in `skills/your-skill/SKILL.md`: ```yaml --- name: my-custom-skill description: Custom pattern for my project --- # My Custom Skill When asked to implement [pattern], follow these steps... ``` ## Repository Skills are maintained in the Ploy repository: [github.com/meetploy/ploy](https://github.com/meetploy/ploy) ``` ploy/ └── skills/ ├── README.md ├── worker-basic/ │ └── SKILL.md ├── nextjs-app/ │ └── SKILL.md ├── db-drizzle/ │ └── SKILL.md ├── nextjs-db/ │ └── SKILL.md ├── queue-handler/ │ └── SKILL.md ├── workflow/ │ └── SKILL.md └── start-framework/ └── SKILL.md ``` ## Troubleshooting ### Skill Not Recognized Ensure the skill files are in the correct location for your tool: * Claude Code: `~/.claude/skills/` or `.claude/skills/` in project * Cursor: `~/.cursor/skills/` or referenced in `.cursorrules` ### AI Not Following Instructions Try being more specific in your request: * "Use the worker-basic skill to create a new API" * "Following the db-drizzle skill, add a users table" ### Missing Dependencies After scaffolding, run: ```bash pnpm install pnpm types # Generate env.d.ts ``` # Introduction to Ploy URL: https://docs.meetploy.com/ Ploy is an open serverless cloud. Connect a GitHub repository, or push to a [Ploy Git](https://docs.meetploy.com/platform/ploy-git) repository with no GitHub account, and every push builds and deploys automatically, with a preview URL for each branch. Your code runs as serverless [workers](https://docs.meetploy.com/workers) that get SQLite [databases](https://docs.meetploy.com/databases), message [queues](https://docs.meetploy.com/queues), durable [workflows](https://docs.meetploy.com/workflows), [cron triggers](https://docs.meetploy.com/workers/cron), an [AI gateway](https://docs.meetploy.com/ai), managed [user auth](https://docs.meetploy.com/auth), and [sandboxes](https://docs.meetploy.com/sandboxes) out of the box — with no servers to manage and nothing running when there is no traffic. The whole platform is open source and [self-hostable](https://docs.meetploy.com/self-host). ## How it works 1. **Choose a source** — connect GitHub, or create a [Ploy Git](https://docs.meetploy.com/platform/ploy-git) repository and push to it. 2. **Describe the project** — a [`ploy.yaml`](https://docs.meetploy.com/platform/configuration) in your repository sets the build command and declares the bindings your code needs: databases, queues, workflows, cron triggers, AI, auth, and more. 3. **Push** — every push builds and deploys. The production branch goes live; every other branch gets its own preview URL. 4. **Run** — your code runs as a worker with the declared bindings on `env`. Run the same thing locally with [`ploy dev`](https://docs.meetploy.com/cli/dev). 5. **Operate** — follow build logs and deployment status in the dashboard, set [environment variables](https://docs.meetploy.com/platform/env-vars), and roll back to any previous deployment in one step. ## Products Each product has its own section in the sidebar with an overview, `ploy.yaml` configuration, and the runtime API. ## Get started Pick the framework you are building with. Each guide covers installation, `ploy.yaml`, local development, and how to use Ploy bindings from that framework. Getting started: https://docs.meetploy.com/cli (CLI), https://docs.meetploy.com/start (Ploy Start SDK), https://docs.meetploy.com/nextjs (Next.js), https://docs.meetploy.com/vite (Vite), https://docs.meetploy.com/self-host (self-hosting). ## AI tooling Ploy is built to be read and driven by AI agents as well as people. AI tooling: https://docs.meetploy.com/llms.txt (docs index for LLMs), https://docs.meetploy.com/llms-full.txt (this file), https://docs.meetploy.com/ai-skills (agent skills), and https://docs.meetploy.com/agent-sdk (Agent SDK). ## Hosted or self-hosted Ploy runs the same either way. Use the hosted platform at [meetploy.com](https://meetploy.com) to skip setup entirely, or [self-host](https://docs.meetploy.com/self-host) it so your code, environment variables, and databases never leave your own infrastructure. ## Related # Self-Hosting Quickstart URL: https://docs.meetploy.com/self-host-quickstart # 🚀 Quickstart Welcome to **Ploy**—a self-hostable serverless deployment platform that lets you deploy web applications with automatic builds, GitHub integration, and continuous deployment. > **TL;DR** — Connect your GitHub repository, push your code, and Ploy handles the rest. *** ## 0 · Quick Install (Self-Hosted) Get Ploy running on your server in minutes with our automated install script: ```bash # Simple mode (unified container - good for testing/development) curl -fsSL https://raw.githubusercontent.com/meetploy/ploy/main/scripts/install.sh | sudo bash -s -- simple # Production mode (split containers - recommended for production) curl -fsSL https://raw.githubusercontent.com/meetploy/ploy/main/scripts/install.sh | sudo bash -s -- prod ``` ### What the install script does: 1. Detects your Linux distribution (Ubuntu, Debian, Fedora, CentOS, RHEL, Arch, openSUSE) 2. Installs Docker and Docker Compose if not already installed 3. Downloads the appropriate docker-compose configuration 4. Creates a sample `.env` file for configuration 5. Starts all Ploy services ### Installation modes: * **simple**: All services run in a single unified container. Best for testing, development, or small deployments. * **prod**: Each service runs in its own container. Better resource isolation and recommended for production use. ### After installation: 1. Edit `/opt/ploy/.env` with your configuration (especially GitHub OAuth credentials) 2. Restart services: `cd /opt/ploy && docker compose up -d` 3. Access the dashboard at `http://your-server-ip:3002` For more details, see the [Self-Hosting Guide](https://docs.meetploy.com/self-host). *** ## 1 · Sign in with GitHub 1. Visit the Ploy dashboard at [meetploy.com](https://meetploy.com) (or your self-hosted instance) 2. Click **Sign in with GitHub** 3. Authorize Ploy to access your repositories *** ## 2 · Create an organization and project 1. After signing in, **create a new organization** (or use an existing one) 2. Navigate to **Projects** and click **New Project** 3. Give your project a name (e.g., "my-app") *** ## 3 · Connect a GitHub repository 1. Click **Connect Repository** in your project 2. Install the Ploy GitHub App if prompted 3. Select the repository you want to deploy 4. Choose the branch to deploy (default: `main`) *** ## 4 · Configure build settings Ploy automatically detects most frameworks, but you can customize: ### Framework Detection Ploy automatically detects and configures: * **Next.js** - Static and server-side rendering * **React** - Static site generation with Vite or Create React App * **Vue** - Static sites with Vite * **Nuxt** - Static and server-side rendering * **Svelte/SvelteKit** - Static and server-side rendering * **Astro** - Static site generation * **Angular** - Static site generation * **Static HTML** - Plain HTML, CSS, and JavaScript ### Using ploy.yaml (Recommended) The recommended way to configure your project is by adding a `ploy.yaml` file to the root of your repository: ```yaml # ploy.yaml kind: static build: npm run build out: dist ``` Basic configuration options: * **kind**: Project type (`static` or `nextjs`) * **build**: Build command (e.g., `npm run build`) * **out**: Output directory for built files (e.g., `dist`, `build`, `.next`) For advanced configuration options including monorepo and base path support, see the [Configuration](https://docs.meetploy.com/platform/configuration) guide. ### Dashboard Configuration If needed, you can also override settings in the Ploy dashboard: ```bash # Build Command (optional - auto-detected) npm run build # Output Directory (optional - auto-detected) dist # Install Command (optional) npm install ``` ### Environment Variables Add environment variables for your build: 1. Go to **Project Settings** → **Environment Variables** 2. Add key-value pairs: * `API_URL=https://api.example.com` * `NEXT_PUBLIC_API_KEY=your-key-here` *** ## 5 · Deploy Once your repository is connected: 1. **Automatic Deployment**: Push to your configured branch 2. **Manual Deployment**: Click **Deploy** in the dashboard 3. **Monitor Progress**: Watch real-time build logs ```bash # Push to trigger deployment git add . git commit -m "Initial deployment" git push origin main ``` ### Deployment Process Ploy will: 1. Clone your repository 2. Install dependencies 3. Run the build command 4. Upload static assets 5. Generate a unique deployment URL *** ## 6 · Access your deployment After a successful deployment: 1. **View your app**: Click the deployment URL (e.g., `https://my-app-abc123.ploy.app`) 2. **Share with team**: Each deployment gets a unique URL 3. **Branch deployments**: Every branch gets its own URL for testing Example deployment URLs: ``` Production (main): https://my-app.ploy.app Branch (feature): https://my-app-feature-xyz.ploy.app PR Preview: https://my-app-pr-123.ploy.app ``` *** ## 7 · Advanced features ### Custom Domains Connect your own domain: 1. Go to **Project Settings** → **Domains** 2. Add your domain (e.g., `example.com`) 3. Configure DNS records as shown 4. Wait for SSL certificate provisioning ### Preview Deployments Every push to any branch creates a preview deployment: * Test features before merging to production * Share previews with team members or clients * Automatic cleanup when branches are deleted Add `[skip deploy]` to a commit message to skip one push, or set ignored branches under **Project Settings** → **Preferences** → **Deploy Rules**. See [`deploy`](https://docs.meetploy.com/platform/configuration#deploy) for the full rules. ### Build Logs Access detailed build logs: 1. Click on any deployment 2. View **Build Logs** tab 3. Debug failed deployments with full output ### Rollback Quickly revert to a previous deployment: 1. Go to **Deployments** history 2. Click on a previous successful deployment 3. Click **Promote to Production** *** ## 8 · Example Projects ### Next.js App ```bash # Create a new Next.js app npx create-next-app@latest my-nextjs-app cd my-nextjs-app # Initialize git and push to GitHub git init git add . git commit -m "Initial commit" git remote add origin https://github.com/yourusername/my-nextjs-app.git git push -u origin main ``` Then connect the repository in Ploy - it will auto-detect Next.js and deploy! ### Vite + React App ```bash # Create a new Vite app npm create vite@latest my-react-app -- --template react cd my-react-app # Initialize git and push to GitHub git init git add . git commit -m "Initial commit" git remote add origin https://github.com/yourusername/my-react-app.git git push -u origin main ``` Connect in Ploy and deploy automatically! ### Static HTML Site ```bash # Create a simple HTML site mkdir my-static-site cd my-static-site echo '

Hello Ploy!

' > index.html # Initialize git and push to GitHub git init git add . git commit -m "Initial commit" git remote add origin https://github.com/yourusername/my-static-site.git git push -u origin main ``` Connect in Ploy and deploy! *** ## 9 · FAQ **What frameworks are supported?** Ploy supports all major web frameworks including Next.js, React, Vue, Nuxt, Svelte, SvelteKit, Astro, Angular, and static HTML sites. Framework detection is automatic in most cases. **How much does it cost?** Ploy is open-source and free to self-host. For the hosted version, see our [Pricing page](https://meetploy.com#pricing). Self-hosting gives you complete cost control - you only pay for your infrastructure. **Can I use my own domain?** Yes! You can connect custom domains to any project. Ploy automatically provisions SSL certificates via Let's Encrypt. **How is Ploy different from managed platforms like Vercel?**

Ploy is an open-source serverless cloud, so it offers:

**How do I rollback a deployment?** Go to your project's Deployments page, find a previous successful deployment, and click "Promote to Production". Your app will immediately use that version. **Can I deploy multiple branches?** Yes! Every branch gets its own deployment URL. This is perfect for testing features before merging to production. **How do I view build logs?** Click on any deployment in your project's Deployments page, then view the Build Logs tab. You'll see real-time output from the build process. *** ## 10 · Next steps * Read the [Self-Hosting Guide](https://docs.meetploy.com/self-host) to deploy Ploy on your infrastructure * Check out our [GitHub repository](https://github.com/meetploy/ploy) for source code * Join our community for help and feature requests Happy deploying! ✨ # Self Host Ploy URL: https://docs.meetploy.com/self-host # Self Host Ploy Ploy is an open-source serverless cloud you can run on your own infrastructure. This guide will help you deploy Ploy yourself, giving you complete control over your deployments, code, and data. ## Prerequisites * **Docker** (latest version) and Docker Compose * **GitHub OAuth App** (for authentication) * **Domain** (optional, but recommended for production) * **2GB+ RAM** (4GB+ recommended for production) * **10GB+ disk space** (more for storing deployments) ## Quick Start The fastest way to get started is with Docker Compose: ```bash # Clone the repository git clone https://github.com/meetploy/ploy.git cd ploy # Copy environment variables cp .env.example .env # Edit .env with your configuration (see below) nano .env # Start all services docker compose up -d ``` After starting, access: * **Web Dashboard**: [http://localhost:3002](http://localhost:3002) * **Documentation**: [http://localhost:3005](http://localhost:3005) * **API**: [http://localhost:4002](http://localhost:4002) * **Handler** (serves deployments): [http://localhost:4001](http://localhost:4001) ## Option 1: Unified Docker Image (Simplest) This option uses a single Docker container with all services bundled together. Perfect for testing or small deployments. ```bash # Run the unified container docker run -d \ --name ploy \ --restart unless-stopped \ -p 3002:3002 \ -p 3005:3005 \ -p 4001:4001 \ -p 4002:4002 \ -v ~/ploy_data:/var/lib/postgresql/data \ -v ~/ploy_fs:/app/fs \ -e AUTH_SECRET=your-secret-key-here \ -e GITHUB_CLIENT_ID=your-github-client-id \ -e GITHUB_CLIENT_SECRET=your-github-client-secret \ -e GITHUB_WEBHOOK_SECRET=your-webhook-secret \ ghcr.io/meetploy/ploy-unified:latest ``` Note: Replace `latest` with a specific version from [releases](https://github.com/meetploy/ploy/releases). ### Using Docker Compose (Unified) ```bash # Download the compose file curl -O https://raw.githubusercontent.com/meetploy/ploy/main/infra/docker-compose.unified.yml # Copy and configure environment curl -O https://raw.githubusercontent.com/meetploy/ploy/main/.env.example cp .env.example .env # Edit .env with your configuration # Start the service docker compose -f docker-compose.unified.yml up -d ``` ## Option 2: Separate Services (Recommended for Production) This option runs each service in its own container, providing better scalability and resource management. ```bash # Clone the repository git clone https://github.com/meetploy/ploy.git cd ploy # Configure environment cp .env.example .env # Edit .env with your configuration # Start all services docker compose -f infra/docker-compose.split.yml up -d ``` ### Services in Split Mode The split deployment includes: * **postgres** - PostgreSQL database * **redis** - Redis cache and session store * **api** - REST API server * **ui** - Web dashboard (Next.js) * **builder** - Background job processor * **handler** - Deployment handler (serves deployed apps) * **docs** - Documentation site ### Private service network Only the API, UI, and deployment handler should accept traffic from outside the service network. Keep the internal API, database service, broker, sandbox control plane, and handler internal-delivery port private. The production and local Compose files do this by omitting host port mappings for those services. Direct development runs bind the internal API, database service, and broker to `127.0.0.1` by default. Set `HOST=0.0.0.0` only when the process is already protected by a private container or host network. To inspect a private service, run the probe inside its container instead of publishing its port. For example: ```bash docker compose -f infra/docker-compose.split.local.yml exec internal \ wget --spider http://localhost:80/ ``` For Kubernetes or another orchestrator, enforce the same boundary with firewall rules or NetworkPolicies: only platform services may reach the private service ports, and only the API, broker, and cron worker may reach the handler's internal delivery port (`8081`). ## Required Configuration ### 1. GitHub OAuth App Create a GitHub OAuth App for authentication: 1. Go to GitHub Settings → Developer settings → OAuth Apps 2. Click **New OAuth App** 3. Fill in: * **Application name**: Ploy * **Homepage URL**: `http://localhost:3002` (or your domain) * **Authorization callback URL**: `http://localhost:3002/api/auth/callback/github` 4. Click **Register application** 5. Copy the **Client ID** and generate a **Client Secret** ### 2. GitHub App (for Repository Access) Create a GitHub App for repository access and webhooks: 1. Go to GitHub Settings → Developer settings → GitHub Apps 2. Click **New GitHub App** 3. Fill in: * **GitHub App name**: Ploy Deployments * **Homepage URL**: `http://localhost:3002` * **Webhook URL**: `http://localhost:4002/webhooks/github` * **Webhook secret**: Generate a random string 4. Set permissions: * **Repository permissions**: * Contents: Read * Metadata: Read * Webhooks: Read & Write 5. Subscribe to events: * Push * Repository 6. Click **Create GitHub App** 7. Generate and download a private key 8. Note the **App ID** ### 3. Environment Variables Edit your `.env` file with the following required variables: ```bash # Database POSTGRES_PASSWORD=your_secure_password_here DATABASE_URL=postgresql://postgres:your_secure_password_here@postgres:5432/ploy # Redis REDIS_URL=redis://redis:6379 # Authentication AUTH_SECRET=your-secret-key-here BETTER_AUTH_URL=http://localhost:3002 # GitHub OAuth (for user authentication) GITHUB_CLIENT_ID=your-github-oauth-client-id GITHUB_CLIENT_SECRET=your-github-oauth-client-secret # GitHub App (for repository access) GITHUB_APP_ID=your-github-app-id GITHUB_APP_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\n...\n-----END RSA PRIVATE KEY-----" GITHUB_WEBHOOK_SECRET=your-webhook-secret # API URLs NEXT_PUBLIC_API_URL=http://localhost:4002 API_HANDLER_URL=http://handler:4001 # Deployment Storage FS_PATH=/app/fs ``` ### 4. Generate Secrets Generate secure random strings for secrets: ```bash # Generate AUTH_SECRET openssl rand -hex 32 # Generate GITHUB_WEBHOOK_SECRET openssl rand -hex 32 ``` ## Database Storage Modes Ploy supports two storage modes for project databases: * `basic` is the default. It keeps each project database as a local SQLite file inside `DB_STORAGE_DIR`. * `turso-cloud` is opt-in. It provisions databases in Turso Cloud and uses Turso-managed replication and point-in-time restore. ### Basic Mode `basic` matches the simplest self-hosted setup and is what the bundled compose files use by default. Required environment variables: ```bash DB_STORAGE_MODE=basic DB_STORAGE_DIR=/data/db-storage ``` Use this mode when: * you are running Ploy on a single machine * you want the fewest moving pieces * you are okay with local SQLite files and handling their durability yourself ### Turso Cloud Mode Set `DB_STORAGE_MODE=turso-cloud` to place worker databases in Turso Cloud. When enabled, Ploy creates Turso databases on demand and routes all worker database traffic there. Required environment variables: ```bash DB_STORAGE_MODE=turso-cloud TURSO_ORGANIZATION=your-turso-organization TURSO_GROUP_NAME=default TURSO_PRIMARY_LOCATION=ord TURSO_DATABASE_PREFIX=ploy TURSO_API_TOKEN=your_turso_platform_api_token TURSO_GROUP_AUTH_TOKEN=your_turso_group_auth_token ``` Optional: ```bash TURSO_API_URL=https://api.turso.tech TURSO_PITR_RETENTION_DAYS=30 ``` Use this mode when: * you want managed replicas and failover from Turso * you want Turso-backed point-in-time recovery * you do not want to run your own libSQL cluster ### Compose Defaults The compose files in this repository default to: ```bash DB_STORAGE_MODE=basic DB_STORAGE_DIR=/data/db-storage ``` The older libSQL containers remain available only behind an optional `legacy-libsql` compose profile and are no longer started by default. ## Auth hook connectivity [Auth lifecycle hooks](https://docs.meetploy.com/auth/hooks) require the internal auth service to call the handler. Set `HANDLER_URL` on that service to the handler's trusted internal listener, for example `http://handler:8081` in split Compose. Permit **internal-service → handler TCP 8081** in network policies and service routing; a policy allowing only API, broker, or worker callers is insufficient. Keep this listener private and inaccessible to customer workers. Do not substitute the public listener on port `8080`: public ingress strips the trusted invocation headers. Without an explicit URL, the local-development fallback is `http://localhost:8081`, which does not reach a separate handler container or pod. Optional pod affinity also requires `HANDLER_HEADLESS_HOST`, the correct `HANDLER_INTERNAL_PORT`, DNS access, and connectivity to discovered handler pods. Use the same `CUSTOM_DOMAIN` as the handler for calls without a public origin. Deploy and verify this connectivity before enabling hooks on a project; failed before-hook calls return `503 hook_failed`. ## Sandbox Provider Sandboxes (the long-lived compute a worker drives via `env..get(id)`) run on a pluggable backend, selected with `SANDBOX_PROVIDER`: * `docker` is the default and the runtime Ploy ships. Each sandbox is a Docker container on the sandbox host, with per-project network isolation. This requires the sandbox service to have access to a Docker daemon. * `boat` runs sandboxes on the hosted [Boat](https://docs.boat.dev) provider instead. No local Docker daemon or network-isolation setup is needed — Boat manages the machines. Set `BOAT_API_KEY` (from the Boat dashboard; a paid Boat plan is required to create sandboxes). To use the hosted provider, layer `docker-compose.sandbox-boat.yml` on top of your split compose file. It selects `boat` and removes the sandbox service's access to the host Docker daemon, which the hosted provider does not need: ```bash docker compose -f docker-compose.split.yml -f docker-compose.sandbox-boat.yml up -d ``` Outside Docker Compose, set `SANDBOX_PROVIDER=boat` on the sandbox service and don't give it a Docker socket. Switching an existing installation from `docker` to `boat`: Boat can't reach the Docker host, so it can't remove sandboxes the Docker provider created. Destroy them first (or remove their `ploy-sbx-*` containers and volumes on the old host afterwards); otherwise their files and credentials stay there. The sandbox service warns at startup while such sandboxes exist. #### Boat account and API key Use a **dedicated Boat account or organization per environment**, with no human members: everyone in a Boat organization can open, SSH into, fork and download its sandboxes. Set `BOAT_ORG` to create sandboxes in that organization. Give the sandbox service a **scoped, expiring** key, never an admin key: ```bash boat api-key create ploy-sandbox --ttl 365d \ --actions sandbox.create,sandbox.read,sandbox.update,sandbox.resume,sandbox.stop,sandbox.delete,exec,file.read,file.write,account.read ``` Add `snapshot.read` only if you use a template (`BOAT_TEMPLATE`); it also lets the key read the saved disks of the sandboxes it can access. The key cannot write snapshots, so it can't change your templates. Rotate it before it expires. The sandbox service logs a warning at startup when the key is unrestricted; set `BOAT_REQUIRE_SCOPED_KEY=true` to refuse to start instead. Boat may temporarily answer scoped-key creation with a 503 while it rolls out credential changes; retry later. #### Configuration ```bash BOAT_API_KEY=your-scoped-boat-api-key # Public https URL of the AI gateway (the API's /ai route). Boat machines run # outside your network, so the compose default (http://internal:80/ai) can't # work; the service refuses to start with an http:// or internal URL. SANDBOX_AI_URL=https://api.your-domain.com/ai # Optional: # BOAT_ORG=ploy-production # organization to create sandboxes in # BOAT_TEMPLATE=ploy-sandbox # start sandboxes from a template # BOAT_TEMPLATE_SNAPSHOT_ID=... # refuse launches if the template changed # BOAT_MACHINE_TYPE=small # small | default | large # BOAT_TTL_SECONDS=86400 # auto-archive backstop (0 disables) # BOAT_BASE_URL=https://boat.dev/api/v1 # API endpoint (must be https) # BOAT_REQUIRE_SCOPED_KEY=true # refuse an unrestricted key # SANDBOX_RETENTION_DAYS=30 # destroy sandboxes idle this long # SANDBOX_LOG_EXEC=1 # log command output (customer data) ``` Ploy's idle sweeper suspends and resumes sandboxes the same way on both providers, and a single command is capped at 10 minutes on both (use background processes for longer work). Boat counts `BOAT_TTL_SECONDS` from when a sandbox starts or resumes, not from its last activity, so it is only a backstop for sandboxes Ploy lost track of. #### What Boat stores, and for how long * **Disks.** A stopped sandbox is archived with its whole filesystem, which includes your customers' code and anything their commands wrote. Boat runs machines in the EU. * **Environment and commands.** Boat keeps each sandbox's launch environment and the text of the commands it runs. Ploy keeps credentials out of both: per-command environment variables and git tokens go through short-lived files inside the sandbox, and the AI token (valid for one hour, refreshed while the sandbox runs) lives in a private file rather than the launch environment. * **Retention.** Sandboxes suspended or stopped for longer than `SANDBOX_RETENTION_DAYS` (default 30; `0` keeps them) are destroyed, as are all sandboxes of a deleted project. Destroying deletes the machine and its snapshots; Boat erases the data in the background, which can take up to a few hours. The service also deletes Boat sandboxes it created but no longer tracks. * **Network.** Sandboxes have unrestricted outbound internet access; Ploy's per-project egress filtering applies only to the Docker provider. The sandbox image (`SANDBOX_DEFAULT_IMAGE`) is ignored. Sandboxes never receive your Boat account's own GitHub token, secrets, or agent logins. Where your setup allows it, give the sandbox service a database role that can read and write only the `sandbox` table and read the `project` table. ### Preinstalled tooling on Boat Boat sandboxes start from Boat's stock Ubuntu machine, which already includes Node.js, Python, Go, Rust, Docker, the GitHub CLI, Claude Code, Codex, and OpenCode. To add more, build a **template** (a Boat named snapshot) and point `BOAT_TEMPLATE` at it. The bundled template adds the Empryo agent and pins the other agents' versions: ```bash pnpm turbo run build --filter=sandbox BOAT_API_KEY=your-template-builder-key pnpm --filter sandbox boat:template ploy-sandbox ``` From a running sandbox service container, run `node dist/boat-template.js ploy-sandbox` instead. This creates a sandbox, installs the tooling, saves it as the `ploy-sandbox` template, deletes the build sandbox, and prints the template's snapshot id. Set `BOAT_TEMPLATE_SNAPSHOT_ID` to it: the sandbox service then refuses to launch if the template is replaced by anything else. Building a template needs a key that may write snapshots (for example the `ci` preset); use it only for this and keep it out of the sandbox service. Code running inside a sandbox cannot save or replace templates. Re-run the build to refresh the tooling, then update the pinned id; sandboxes already running are unaffected. ## Production Configuration For production deployments, consider these additional settings: ### Domain Setup 1. Point your domain to your server's IP 2. Update environment variables: ```bash # Frontend URL BETTER_AUTH_URL=https://ploy.yourdomain.com NEXT_PUBLIC_API_URL=https://api.yourdomain.com # Update GitHub OAuth callback # In GitHub OAuth App settings, set callback to: # https://ploy.yourdomain.com/api/auth/callback/github # Update GitHub App webhook URL # In GitHub App settings, set webhook to: # https://api.yourdomain.com/webhooks/github ``` ### Ploy-managed DNS Organization domains can be delegated to Ploy, which then answers DNS for them and routes subdomains to your projects. The authoritative DNS plane is switchable with `DNS_PROVIDER`; your records always live in Ploy's own database, regardless of which provider serves them. ```bash # Ploy's own resolver answers queries (default) DNS_PROVIDER=self_hosted # Or hand authority to a managed DNS zone DNS_PROVIDER=google_cloud_dns GOOGLE_CLOUD_PROJECT=your-project-id # Optional: keep customer zones in a separate project (defaults to GOOGLE_CLOUD_PROJECT) GOOGLE_CLOUD_DNS_PROJECT=your-customer-dns-project-id GOOGLE_CLOUD_DNS_CREDENTIALS= # How long a synced zone is trusted before it is reconciled again DNS_SYNC_DRIFT_SECONDS=3600 ``` With `self_hosted`, run the `dns-resolver` service: it needs UDP and TCP port 53 and your registrar must delegate the domain to the nameservers Ploy shows in the dashboard (`*.ns.`, so `CUSTOM_DOMAIN` must itself resolve to that host). With a managed provider, the resolver service is not needed — Ploy creates a zone per domain and reconciles your records into it, and the dashboard shows the nameservers that zone was given. The provider is recorded per domain when its zone is created, so changing `DNS_PROVIDER` later only affects domains delegated after the change. ### SSL/TLS Certificates Use a reverse proxy like Nginx or Caddy for SSL: #### Caddy Example Create a `Caddyfile`: ``` (ploy_upstream) { transport http { keepalive 3s } } ploy.yourdomain.com { reverse_proxy localhost:3002 { import ploy_upstream } } api.yourdomain.com { reverse_proxy localhost:4002 { import ploy_upstream } } *.ploy-deployments.yourdomain.com { reverse_proxy localhost:4001 { import ploy_upstream } } ``` Run Caddy: ```bash caddy run ``` The reverse proxy terminates TLS and forwards plain HTTP to the handler, so the handler cannot tell how the client connected. Tell it with `PUBLIC_PROTOCOL`, which is the protocol worker code sees in `request.url`: ```bash # Deployments are served over https by the reverse proxy PUBLIC_PROTOCOL=https ``` It defaults to `https` when `NODE_ENV=production` and `http` otherwise. Set `PUBLIC_PROTOCOL=http` if your deployments are served without TLS. #### Client IP addresses `X-Forwarded-For` is a list that every proxy appends to and clients can prefill, so Ploy does not trust it by default. To give deployments, request logs and sign-up rate limits the real client address, have the proxy set one header to the address it saw, overwriting anything the client sent, and tell the handler and API to trust it: ``` (ploy_upstream) { header_up X-Ploy-Client-IP {remote_host} transport http { keepalive 3s } } ``` ```bash # On the handler and the API PLOY_CLIENT_IP_HEADER=X-Ploy-Client-IP ``` Deployments then see that address in `X-Real-IP` and as the only `X-Forwarded-For` entry. Only set `PLOY_CLIENT_IP_HEADER` when every request reaches Ploy through a proxy that sets the header; otherwise clients can choose their own address. Keep the proxy's idle upstream timeout below **5 seconds**. Every Ploy service closes an idle keep-alive connection after 5 seconds, and the deployment runtime resets rather than cleanly closes it. Proxies pool upstream connections for much longer by default (Caddy 2m, Nginx 60s), so a pooled connection can be reused at the same instant the upstream tears it down. A request with a body is never replayed, so the caller gets a `502` with an empty body while the upstream — reset before it read the request — never runs or logs it. If passive health checks are enabled, that reset also pulls the upstream out of rotation and every host behind the proxy serves `503` for a few seconds before recovering on its own. Retiring idle connections first (`keepalive 3s` in the `ploy_upstream` snippet above, or `keepalive_timeout 3s` in an Nginx `upstream` block) closes the race. ### Resource Limits Add resource limits to your `docker-compose.yml`: ```yaml services: api: deploy: resources: limits: cpus: "1" memory: 1G reservations: cpus: "0.5" memory: 512M ``` ### Worker CPU Limits Each invocation of a deployed worker gets a CPU time budget from its organization's plan. Organizations on a self-hosted instance use the **Free** limits unless you assign a plan or override them. Set these on the `internal` service (or the unified container); `0` turns a limit off: | Variable | Default (Free / Pro / Enterprise) | | ------------------------------------- | --------------------------------- | | `WORKER_CPU_LIMIT_MS_` | `1000` / `30000` / `300000` | | `WORKER_CPU_LIMIT_MS_QUEUE_` | `5000` / `30000` / `300000` | | `WORKER_CPU_LIMIT_MS_TIMER_` | `5000` / `30000` / `300000` | | `WORKER_CPU_LIMIT_MS_CRON_` | `10000` / `300000` / `900000` | | `WORKER_CPU_LIMIT_MS_WORKFLOW_` | `15000` / `300000` / `900000` | `` is `FREE`, `PRO`, or `ENTERPRISE`, for example `WORKER_CPU_LIMIT_MS_CRON_FREE=60000`. The first row applies to HTTP requests. The startup limit for a worker's top-level code is set on the `handler` service with `WORKER_STARTUP_CPU_LIMIT_MS` (default `5000`, `0` turns it off). All deployments on a handler share one JavaScript thread, so these limits are what stop one runaway deployment from stalling the others. Raise them rather than turning them off. ### Monitoring Enable logging and monitoring: ```bash # View logs for all services docker compose logs -f # View logs for specific service docker compose logs -f api # View resource usage docker stats ``` ## Management Commands ### Docker Compose (Unified) ```bash # Start services docker compose -f docker-compose.unified.yml up -d # View logs docker compose -f docker-compose.unified.yml logs -f # Restart services docker compose -f docker-compose.unified.yml restart # Stop services docker compose -f docker-compose.unified.yml down # Stop and remove volumes docker compose -f docker-compose.unified.yml down -v ``` ### Docker Compose (Split) ```bash # Start all services docker compose -f infra/docker-compose.split.yml up -d # Start specific service docker compose -f infra/docker-compose.split.yml up -d api # View logs docker compose -f infra/docker-compose.split.yml logs -f # Restart services docker compose -f infra/docker-compose.split.yml restart # Stop services docker compose -f infra/docker-compose.split.yml down ``` ### Database Operations ```bash # Backup database docker exec ploy-postgres pg_dump -U postgres ploy > backup.sql # Restore database docker exec -i ploy-postgres psql -U postgres ploy < backup.sql # Access database shell docker exec -it ploy-postgres psql -U postgres ploy ``` ## Troubleshooting ### Common Issues **Services won't start:** ```bash # Check logs docker compose logs -f # Verify environment variables docker compose config # Ensure ports are not in use lsof -i :3002 lsof -i :4002 ``` **Database connection errors:** ```bash # Check PostgreSQL is running docker compose ps postgres # Verify DATABASE_URL in .env # Ensure POSTGRES_PASSWORD matches in DATABASE_URL ``` **GitHub webhook not working:** 1. Check webhook URL is publicly accessible 2. Verify GITHUB\_WEBHOOK\_SECRET matches GitHub App 3. Check API logs: `docker compose logs -f api` 4. Test webhook delivery in GitHub App settings **Deployments failing:** ```bash # Check worker logs docker compose logs -f builder # Check handler logs docker compose logs -f handler # Verify FS_PATH volume is writable docker exec ploy-builder ls -la /app/fs ``` ### Debug Mode Enable debug logging: ```bash # Add to .env LOG_LEVEL=debug # Restart services docker compose restart ``` ## Updating Ploy To update to the latest version: ```bash # Pull latest changes git pull origin main # Pull latest images docker compose pull # Restart services docker compose down docker compose up -d # Check logs for any issues docker compose logs -f ``` ## Build from Source To build Ploy from source: ```bash # Clone repository git clone https://github.com/meetploy/ploy.git cd ploy # Install dependencies pnpm install # Build all packages pnpm build # Start services with local build docker compose -f infra/docker-compose.local.yml up -d ``` ## Performance Tuning ### PostgreSQL Optimize PostgreSQL for your workload: ```bash # Add to docker-compose.yml postgres service environment: - POSTGRES_SHARED_BUFFERS=256MB - POSTGRES_EFFECTIVE_CACHE_SIZE=1GB - POSTGRES_MAX_CONNECTIONS=100 ``` ### Redis Configure Redis memory limits: ```bash # Add to docker-compose.yml redis service command: redis-server --maxmemory 256mb --maxmemory-policy allkeys-lru ``` ### Worker Concurrency Adjust worker concurrency: ```bash # Add to .env WORKER_CONCURRENCY=5 ``` ## Security Best Practices 1. **Use strong passwords** for database and secrets 2. **Enable HTTPS** in production with valid SSL certificates 3. **Keep secrets secure** - never commit `.env` files 4. **Regular backups** of database and deployment files 5. **Update regularly** to get security patches 6. **Firewall rules** - only expose necessary ports 7. **Limit GitHub App permissions** to minimum required ## Next Steps Once Ploy is running: 1. **Sign in** at [http://localhost:3002](http://localhost:3002) (or your domain) 2. **Create an organization** and project 3. **Connect a repository** and deploy your first app 4. **Configure custom domains** for production deployments 5. **Explore the API** at [http://localhost:4002/docs](http://localhost:4002/docs) ## Support * **Documentation**: [https://docs.meetploy.com](https://docs.meetploy.com) * **GitHub Issues**: [https://github.com/meetploy/ploy/issues](https://github.com/meetploy/ploy/issues) * **Community**: Join our Discord or discussions Happy self-hosting! ✨ ## Sandboxed builds Operators can run deployment builds in isolated sandboxes while keeping deployment orchestration, database migrations, and artifact uploads in the builder. Customers continue using the same deployments and build logs. Set these variables on the builder: ```bash BUILD_EXECUTOR=sandbox SANDBOX_URL=http://sandbox:80 SANDBOX_AUTH_TOKEN=replace-with-your-control-plane-token # Optional rollout: comma-separated organization IDs; empty enables all. BUILD_EXECUTOR_ORGANIZATIONS= ``` The sandbox service selects Docker or Boat through `SANDBOX_PROVIDER`. A failed sandbox build never falls back to executing customer code inside the builder. Sandbox builds require a GitHub App installation that can issue repository-scoped, read-only clone credentials. For Docker, use `BUILD_SANDBOX_IMAGE` to select a pinned build runtime image. The published image is `ghcr.io/meetploy/ploy-build-runtime`. For local development, build it with `pnpm sandbox:build-image` and set `BUILD_SANDBOX_IMAGE=ploy-build-runtime`. The sandbox service must have `SANDBOX_NETWORK_ISOLATION=true`. Build sandboxes use a separate network and egress proxy, without the private-service exceptions of regular customer sandboxes. For Boat, create the build template from the repository root after building the sandbox service: ```bash pnpm turbo run build --filter=sandbox pnpm --filter sandbox boat:template ploy-build ``` Set `BUILD_SANDBOX_TEMPLATE=ploy-build` and the printed `BUILD_SANDBOX_TEMPLATE_SNAPSHOT_ID` on the builder. Set `BUILD_SANDBOX_MACHINE_TYPE` when an explicit machine size is needed. Organization owners and admins can override the size under **Settings → Preferences → Build Machine** (`small`, `default`, `large` or `xlarge`; Boat's `xlarge` needs its $100 plan or higher). On Docker the override sets the CPU and memory limits to the same sizes, so the sandbox host needs that capacity. Changing the size keeps each branch's build cache; the next build resumes on the new size. The template contains the build toolchain, without Ploy AI credentials or bindings. Regular customer sandboxes retain their existing AI functionality. Each project and branch reuses its own sandbox. Different branches compile in parallel within the builder's concurrency limit; shared project updates and migrations remain serialized. Sandboxes stop after each attempt. Clearing a build's cache destroys that branch's sandbox before rebuilding. Stopped sandboxes expire according to `SANDBOX_RETENTION_DAYS` on the sandbox service (30 days by default; zero disables inactivity expiry). Deleted projects also have their sandboxes removed. Deleting a Git branch does not cancel builds or immediately remove its cache. Branch caches use automatic provider snapshots, not named templates. Keep the active platform templates; remove superseded snapshots only after no deployment configuration references them. | Builder variable | Default | Purpose | | -------------------------- | ------------ | ---------------------------------- | | `BUILD_EXECUTOR` | `local` | Select local or sandbox execution. | | `BUILD_SANDBOX_MEMORY_MB` | `8192` | Docker memory limit. | | `BUILD_SANDBOX_CPUS` | `2` | Docker CPU limit. | | `BUILD_SANDBOX_PIDS` | `512` | Docker process limit. | | `BUILD_ARTIFACT_MAX_BYTES` | `2147483648` | Maximum extracted artifact bytes. | | `BUILD_ARTIFACT_MAX_FILES` | `100000` | Maximum artifact entries. | The builder sends project environment variables to the build job, never its own platform credentials. Platform-created job and credential files are removed before archival. Customer build commands can still write their own environment values into generated output or caches. ## Isolated database migrations By default the builder applies customer migrations from the build output. To keep customer database access out of the process that orchestrates untrusted builds, run the migrator and set `DB_MIGRATIONS_EXECUTOR=migrator` on the builder: ```bash # Same image as the builder, different command. node --no-warnings --enable-source-maps dist/migrator.js ``` The builder then only records a request per deployment and waits for the result. The migrator verifies that the deployment's commit is on the repository's default branch, checks out only `ploy.yaml` and `.sql` files at that commit (no hooks, filters, submodules, or symlinks), applies pending migrations, prepares Ploy Auth databases, and writes an audit row per applied migration to `database_migration_audit`. It needs `DATABASE_URL`, `ENCRYPTION_KEY`, the GitHub App credentials, Redis (for build logs), and `DB_URL`; once it runs, the builder no longer needs `DB_URL`, so restrict the DB service to the platform services that use it. | Migrator variable | Default | Purpose | | ----------------------- | ------- | ---------------------------------------------- | | `DB_URL` | — | DB service URL (required). | | `MIGRATOR_CONCURRENCY` | `4` | Deployments processed in parallel per replica. | | `MIGRATOR_LEASE_MS` | `60000` | Lease after which another replica takes over. | | `MIGRATOR_MAX_ATTEMPTS` | `3` | Interrupted attempts before a run fails. | | `MIGRATOR_WORK_DIR` | tmpdir | Parent directory for temporary checkouts. | # TanStack Start URL: https://docs.meetploy.com/tanstack-start # TanStack Start [TanStack Start](https://tanstack.com/start) apps run on Ploy through the same [`ploy()`](https://docs.meetploy.com/vite) plugin used for other Vite apps. You get TanStack's file-based routing, server routes, and build-time prerendering, served on the Ploy Workers runtime — with bindings and configuration driven entirely from `ploy.yaml`. TanStack Start requires the **latest Vite**. Pin `vite` to the current major (Vite 8+) in your project; older majors are not supported by the TanStack Start adapter. ## Project setup A TanStack Start project needs three pieces: a `package.json` that calls Ploy, a `vite.config.ts` that combines `ploy()` with the TanStack Start plugin, and a `ploy.yaml`. ```json title="package.json" { "scripts": { "build": "ploy vite build && tsc --noEmit", "types": "ploy types -o env.d.ts" }, "dependencies": { "@tanstack/react-router": "^1.168.0", "@tanstack/react-start": "^1.167.0", "react": "^19", "react-dom": "^19" }, "devDependencies": { "@meetploy/cli": "latest", "@meetploy/vite": "latest", "@vitejs/plugin-react": "^6", "vite": "^8" } } ``` ```typescript title="vite.config.ts" import { ploy } from "@meetploy/vite"; import { tanstackStart } from "@tanstack/react-start/plugin/vite"; import viteReact from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [ ...ploy({ viteEnvironment: { name: "ssr" } }), tanstackStart({ prerender: { enabled: true, autoSubfolderIndex: true, crawlLinks: false, failOnError: true, }, }), viteReact(), ], }); ``` ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist compatibility_date: "2026-03-17" compatibility_flags: - nodejs_compat ``` `ploy()` returns an array of plugins, so spread it into the `plugins` list. Any [plugin options](https://docs.meetploy.com/vite#configuration) you would pass to the underlying Vite integration (such as `viteEnvironment`) go directly to `ploy()`. When `@tanstack/react-start` is installed, Ploy automatically maps the worker entry to `@tanstack/react-start/server-entry` — there is no `worker/index.ts` to maintain. ## Routing TanStack Start uses file-based routing under `src/routes`. Pages render with React; server routes run on the worker. ```tsx title="src/routes/index.tsx" import { createFileRoute } from "@tanstack/react-router"; export const Route = createFileRoute("/")({ component: HomePage, }); function HomePage() { return

Rendered at build time, served from the worker

; } ``` ### Server routes Add a `server` block to a route to handle requests on the worker — this is where API endpoints live. ```ts title="src/routes/api/hello.ts" import { createFileRoute } from "@tanstack/react-router"; export const Route = createFileRoute("/api/hello")({ server: { handlers: { GET: ({ pathname }) => Response.json({ message: "hello from worker", pathname }), }, }, }); ``` ## Prerendering The TanStack Start plugin can prerender routes to static HTML at build time while keeping the app on the worker runtime for everything else. Configure it through the `prerender` option in `vite.config.ts`: ```typescript tanstackStart({ prerender: { enabled: true, autoSubfolderIndex: true, crawlLinks: false, failOnError: true, }, }); ``` Prerendered routes are emitted as static files and served as assets; dynamic routes and server handlers continue to run on the worker. ## Bindings Add Ploy resources — databases, queues, auth, and more — to `ploy.yaml` exactly as you would for any other Vite app. `ploy()` injects them into the worker so they are available on `env` in your server routes, backed by the local Ploy dev environment during `ploy dev`. See the [Vite](https://docs.meetploy.com/vite#bindings) guide for the binding maps and [Features](https://docs.meetploy.com/databases) for each resource. ```yaml title="ploy.yaml" db: DB: default ``` After changing bindings, regenerate types so `env.d.ts` stays current: ```bash ploy types -o env.d.ts ``` ## Running it ```bash # Dev server + local Ploy dashboard ploy dev # Production build ploy vite build ``` `ploy dev` auto-detects the TanStack Start project and starts the Vite dev server alongside the local Ploy dashboard. See [ploy dev](https://docs.meetploy.com/cli/dev) and [ploy vite](https://docs.meetploy.com/cli/vite) for the command reference. ## Example A complete, runnable project — prerendered routes, a server route, and worker APIs — lives in [examples/tanstack-start](https://github.com/meetploy/ploy/tree/main/examples/tanstack-start). # Vite URL: https://docs.meetploy.com/vite # Vite Ploy runs Vite apps — React SPAs that ship a worker, TanStack Start apps, and other worker + assets projects — directly from your `ploy.yaml`. You keep a single source of truth for bindings, assets, and compatibility settings, and Ploy handles the dev and build toolchain for you. Ploy ships the [`@meetploy/vite`](https://www.npmjs.com/package/@meetploy/vite) package. Add its `ploy()` plugin to your `vite.config.ts` and it wires bindings, assets, and compatibility settings from `ploy.yaml` into the Vite toolchain for both dev and build. ## How it works When you run `ploy dev` or `ploy vite`, Ploy: 1. **Detects a Ploy Vite project** — the project has a `vite.config.*` file **and** `@meetploy/vite` in its dependencies (or an ancestor's `package.json`, so monorepos work). 2. **Reads and validates `ploy.yaml`** and resolves any Agent SDK bindings. 3. **Builds the runtime configuration** from `ploy.yaml` — bindings, assets, and compatibility date/flags. 4. **Isolates the Miniflare registry** under a fresh temp directory per project, so multiple projects don't collide locally. 5. **Spawns Vite** (your local `node_modules/.bin/vite`, falling back to `npx vite`) with the generated config and Ploy environment variables wired in. For `ploy dev`, a local Ploy dashboard / mock server is also started on `port + 1000` and its URL is exposed to the worker via `PLOY_DASHBOARD_URL` and `PLOY_MOCK_SERVER_URL`. Keep your bindings and compatibility settings in `ploy.yaml` — it's the single source of truth for your project's configuration. ## Project setup A Ploy Vite project needs three pieces: a `package.json` that calls Ploy, a `vite.config.ts` using the `ploy()` plugin from `@meetploy/vite`, and a `ploy.yaml`. Install the plugin as a dev dependency: ```bash pnpm add -D @meetploy/vite ``` ```json title="package.json" { "scripts": { "dev": "ploy vite dev", "build": "tsc --noEmit && ploy vite build", "types": "ploy types -o env.d.ts" } } ``` ```typescript title="vite.config.ts" import { ploy } from "@meetploy/vite"; import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [react(), ...ploy()], }); ``` `ploy()` returns an array of plugins, so spread it into the `plugins` list. ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist compatibility_date: "2026-03-23" assets: binding: ASSETS not_found_handling: single-page-application run_worker_first: - /api/* - "!/api/docs/*" db: DB: default ``` For non-TanStack projects, Ploy looks for a worker entry at `worker/index.ts` (or the `.js` / `.mjs` variants). ## Configuration Everything the Vite toolchain needs is configured through `ploy.yaml`. ### Project kind Use `kind: dynamic` for Vite apps that ship a worker alongside static assets. ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist ``` | Field | Description | | ------- | ----------------------------------------- | | `kind` | `dynamic` for Vite worker + assets apps | | `build` | Build command Ploy runs to produce `out` | | `out` | Output directory the Vite build writes to | ### Compatibility Set the Workers runtime compatibility date and flags here in `ploy.yaml`. ```yaml title="ploy.yaml" compatibility_date: "2026-03-23" compatibility_flags: - nodejs_compat ``` ### Assets The top-level `assets` key controls static asset behavior for dynamic Vite deployments. ```yaml title="ploy.yaml" assets: binding: ASSETS not_found_handling: single-page-application run_worker_first: - /api/* - "!/api/docs/*" ``` * `binding` exposes the asset fetcher to your worker as `env.ASSETS` * `not_found_handling: single-page-application` enables SPA fallback so client routes resolve to `index.html` * `run_worker_first` lets API routes (or other patterns) bypass the asset layer and hit your worker first; prefix a pattern with `!` to exclude it ### Bindings Add Ploy resources — databases, queues, auth, and more — with the same binding maps used by workers. They're available on `env` in your worker. ```yaml title="ploy.yaml" db: DB: default queue: TASKS: tasks ``` After changing bindings, regenerate types so `env.d.ts` stays current: ```bash ploy types -o env.d.ts ``` ### Dev server port and host You can pin the local dev port and host per project. CLI flags (`-p` / `--port`, `-h` / `--host`) take precedence. ```yaml title="ploy.yaml" dev: port: 3000 host: localhost ``` ## Running it There are two ways to drive the Vite integration: * **`ploy dev`** — auto-detects the project type and, for Ploy Vite projects, starts the Vite dev server plus the local Ploy dashboard. This is the usual command during development. See [ploy dev](https://docs.meetploy.com/cli/dev). * **`ploy vite `** — runs the underlying Vite command directly with the `ploy.yaml`-managed config. Use this in `package.json` scripts and CI. See [ploy vite](https://docs.meetploy.com/cli/vite). ```bash # Auto-detected dev server + dashboard ploy dev # Explicit Vite dev / build with ploy.yaml config ploy vite dev ploy vite build ``` Any extra arguments after `ploy vite ` are forwarded to Vite. To pass Vite's own `--config`, forward it explicitly: ```bash ploy vite build -- --config vite.config.custom.ts ``` ## TanStack Start TanStack Start apps work the same way — spread `ploy()` alongside the TanStack Start plugin. See the dedicated [TanStack Start](https://docs.meetploy.com/tanstack-start) guide for routing, server routes, and prerendering. ## Notes * Use the `ploy()` plugin from `@meetploy/vite` and let Ploy manage your configuration from `ploy.yaml`. * Keep compatibility settings and bindings in `ploy.yaml`. * For plain workers use [`ploy dev`](https://docs.meetploy.com/cli/dev) / [`ploy build`](https://docs.meetploy.com/cli); for Next.js use `ploy dev` with [`@meetploy/nextjs`](https://docs.meetploy.com/nextjs). # Commands URL: https://docs.meetploy.com/agent-sdk/commands # Commands The Agent SDK provides built-in commands accessible via `agent.commands` in your `handle` function. These let users manage their workspace, toggle debug mode, and install MCP servers. ## Using Commands Commands are available on the `AgentContext` passed to your `handle` function. Route them however fits your platform: ```typescript handle: async (req, env, agent) => { const body = (await req.json()) as { userId: string; chatId: string; text: string; }; // Check for command prefix if (body.text.startsWith("/")) { const [command, ...args] = body.text.slice(1).split(" "); switch (command) { case "reset": return Response.json({ reply: await agent.commands.reset(body.userId, body.chatId), }); case "debug": return Response.json({ reply: await agent.commands.debug(body.userId, body.chatId), }); case "tools": return Response.json({ reply: await agent.commands.listTools(body.userId), }); case "install": return Response.json({ reply: await agent.commands.installMcp( body.userId, body.chatId, args[0], ), }); case "uninstall": return Response.json({ reply: await agent.commands.uninstallMcp(body.userId, args[0]), }); } } // Normal message handling // ... }; ``` ## Available Commands ### reset Deletes the user's workspace entirely, clearing conversation history, memory, and all settings. ```typescript const reply = await agent.commands.reset(userId, chatId); // "Context cleared. Starting fresh." ``` ### debug Toggles debug mode on the user's workspace. When enabled, internal processing details are visible. ```typescript const reply = await agent.commands.debug(userId, chatId); // "Debug mode enabled. You'll see internal processing details." // or // "Debug mode disabled." ``` ### listTools Lists all available tools -- built-in, custom, and MCP server tools. ```typescript const reply = await agent.commands.listTools(userId); // "Available tools:\n- memory_set\n- memory_get\n- ..." ``` ### installMcp Installs an MCP server by fetching its manifest from a URL. The manifest must expose a `/manifest` endpoint returning `{ name: string, tools: Array<{ name, description, parameters }> }`. ```typescript const reply = await agent.commands.installMcp( userId, chatId, "https://mcp.example.com", ); // 'Installed MCP server "weather" with tools: get_forecast, get_alerts' ``` ### uninstallMcp Removes an installed MCP server by name. ```typescript const reply = await agent.commands.uninstallMcp(userId, "weather"); // 'Uninstalled MCP server "weather".' ``` ## AgentCommands Interface ```typescript interface AgentCommands { reset: (userId: string, chatId: string) => Promise; debug: (userId: string, chatId: string) => Promise; installMcp: (userId: string, chatId: string, url: string) => Promise; uninstallMcp: (userId: string, name: string) => Promise; listTools: (userId: string) => Promise; } ``` Commands return plain strings. It's up to your `handle` function to send the reply back to the user through your platform's messaging API. ## Next Steps * [createAgent()](https://docs.meetploy.com/agent-sdk/create-agent) -- Access commands via `agent.commands` in your handler * [Tools](https://docs.meetploy.com/agent-sdk/tools) -- The tools listed by `/tools` * [State & Workspaces](https://docs.meetploy.com/agent-sdk/state) -- What `/reset` deletes # createAgent() URL: https://docs.meetploy.com/agent-sdk/create-agent # createAgent() `createAgent(config)` is the main entry point of the Agent SDK. It takes an `AgentConfig` and returns a `Ploy` export that handles fetch requests, timer events, and the durable agent workflow. ## AgentConfig ```typescript import { createAgent } from "@meetploy/agent-sdk"; export default createAgent({ // Required systemPrompt: "You are a helpful assistant.", handle: myHandler, // Optional model: "auto", contextCompression: { enabled: true, maxTokens: 2000, summaryModel: "gpt-4o-mini", preserveRecentMessages: 12, }, streaming: { enabled: false }, features: { memory: true, artifacts: true, scheduling: true, mcp: true }, tools: [myTool], hooks: { onRunPartial(ctx, partial) { /* ... */ }, onRunComplete(ctx, response) { /* ... */ }, }, maxSteps: 30, }); ``` ### systemPrompt The system prompt sent to the AI on every turn. Can be a static string or a function that returns a per-user prompt: ```typescript // Static systemPrompt: "You are a helpful assistant."; // Dynamic per-user systemPrompt: async (userId) => { const prefs = await loadPreferences(userId); return `You are a helpful assistant. Language: ${prefs.language}.`; }; ``` The SDK automatically appends the user's stored memories to the system prompt. When context compression is enabled, it also appends the running conversation summary. ### handle Your custom request handler. This is where you parse incoming requests (HTTP, webhooks, etc.), call `agent.handleMessage()`, and return a response: ```typescript async function handle(req: Request, env: PloyEnv, agent: AgentContext) { const body = (await req.json()) as { userId: string; chatId: string; text: string; }; const messenger = new MyMessenger(); await agent.handleMessage({ userId: body.userId, chatId: body.chatId, platform: "http", text: body.text, messenger, }); return Response.json({ ok: true }); } ``` The `AgentContext` passed to your handler provides: | Property | Type | Description | | --------------- | --------------------------- | -------------------------------------------- | | `handleMessage` | `(params) => Promise` | Enqueue a user message for processing | | `commands` | `AgentCommands` | Built-in commands (reset, debug, tools, MCP) | | `state` | `StateManager` | Direct access to the state binding | | `env` | `PloyEnv` | The full Ploy environment bindings | ### model The model name passed to the AI gateway. Defaults to `"auto"`. ```typescript model: "gpt-4o"; ``` ### contextCompression Enable summary-based context compression for long-running conversations: ```typescript contextCompression: { enabled: true, maxTokens: 2000, summaryModel: "gpt-4o-mini", preserveRecentMessages: 12, } ``` Options: | Property | Type | Description | | ------------------------ | --------- | ------------------------------------------------------------------------------------------------ | | `enabled` | `boolean` | Enables summary-based compression. Disabled by default. | | `maxTokens` | `number` | Estimated prompt budget before older history is summarized. | | `summaryModel` | `string` | Optional model used for summary generation. Defaults to the main `model`. | | `preserveRecentMessages` | `number` | Number of most recent chat messages to keep verbatim. Defaults to `12`. | | `summaryPrompt` | `string` | Optional prompt template for the summarizer. Supports `{summary}` and `{messages}` placeholders. | When the estimated prompt size exceeds `maxTokens`, the SDK summarizes older history, stores the result in the user's workspace, and keeps only the most recent messages verbatim. That summary is then injected into future system prompts. This is currently based on estimated prompt size, not exact tokenizer counts. The API is stable, but the threshold is approximate until the SDK grows native tokenizer support. ### features Toggle built-in tool categories. All default to `true`: ```typescript features: { memory: true, // memory_set, memory_get, memory_delete, memory_list artifacts: true, // artifact_create scheduling: true, // schedule_task, list_scheduled_tasks, get_scheduled_task, update_scheduled_task, delete_scheduled_task mcp: true, // mcp_call_tool (when MCP servers are installed) } ``` ### streaming Enable first-class partial generation inside the SDK workflow: ```typescript streaming: { enabled: true, throttleMs: 400, minCharsDelta: 24, maxPartialLength: 4096, } ``` When enabled, the SDK requests `stream: true` from the AI gateway, emits throttled partial updates to `hooks.onRunPartial` during generation, and still persists only the final assistant message into workspace history. Because the durable workflow does not carry a live runtime messenger instance today, streamed partials are currently consumed through hooks. The `Messenger.sendPartialMessage` method is available for transports or adapters that can bridge partial delivery themselves. Example: ```typescript import { createAgent } from "@meetploy/agent-sdk"; export default createAgent({ systemPrompt: "You are a helpful assistant.", handle: myHandler, streaming: { enabled: true, throttleMs: 250, minCharsDelta: 12, }, hooks: { async onRunPartial(ctx, partial) { await ctx.state.setJSON(`draft:${ctx.chatId}`, { key: partial.key, text: partial.text, step: partial.step, isFinal: partial.isFinal, }); }, async onRunComplete(ctx, response) { await ctx.state.delete(`draft:${ctx.chatId}`); await ctx.state.set(`last_response:${ctx.chatId}`, response); }, }, }); ``` In that flow, `onRunPartial` receives the current accumulated assistant text as it grows. `partial.key` stays stable for the in-progress assistant turn, so your UI or adapter can replace the same draft message instead of appending a new one on every update. ### tools Array of custom tool definitions. Use `defineTool()` for type-safe args: ```typescript import { defineTool } from "@meetploy/agent-sdk"; const myTool = defineTool({ name: "lookup_user", description: "Look up a user by ID", parameters: { type: "object", properties: { userId: { type: "string" } }, required: ["userId"], }, async execute(args, ctx) { // args.userId is typed as string const data = await ctx.state.get(`user:${args.userId}`); return data ?? "User not found"; }, }); ``` See [Tools](https://docs.meetploy.com/agent-sdk/tools) for full documentation. ### hooks Lifecycle hooks that fire during agent execution. Every hook receives a `HookContext` with access to `env`, `state`, and an `execute()` function for calling tools: ```typescript hooks: { async onRunComplete(ctx, response) { await ctx.state.set(`last_response:${ctx.userId}`, response); }, async onRunError(ctx, error) { console.error(`Agent error for ${ctx.userId}: ${error.message}`); }, } ``` See [Hooks](https://docs.meetploy.com/agent-sdk/hooks) for the full list. ### maxSteps Maximum iterations of the AI-call-then-tool-execution loop per run. Prevents runaway tool loops. Defaults to `30`. ```typescript maxSteps: 50; ``` ## Messenger Interface The `Messenger` you pass to `handleMessage()` defines how the agent sends responses back to the user. Implement it for your platform: ```typescript import type { Messenger } from "@meetploy/agent-sdk"; class TelegramMessenger implements Messenger { sendMessage(chatId: string, text: string) { return fetch(`https://api.telegram.org/bot${token}/sendMessage`, { method: "POST", body: JSON.stringify({ chat_id: chatId, text }), }).then(() => undefined); } sendDocument(chatId: string, filename: string, content: string | Uint8Array) { // Upload file to Telegram } sendTypingIndicator(chatId: string) { return fetch(`https://api.telegram.org/bot${token}/sendChatAction`, { method: "POST", body: JSON.stringify({ chat_id: chatId, action: "typing" }), }).then(() => undefined); } // Optional for transports that can bridge partial delivery outside // the durable workflow. The SDK's built-in streaming flow currently // emits partials through hooks.onRunPartial. sendPartialMessage?(chatId: string, partial: PartialMessage) { return updateDraft(chatId, partial.key, partial.text); } } ``` ## Return Value `createAgent()` returns a `Ploy` object with: * `fetch` -- Handles HTTP requests (health check + delegates to your `handle` function) * `timer` -- Handles scheduled task triggers * `workflows.ploy_agent_run` -- The durable agent tick loop The SDK owns the `timer` and `workflows` handlers. You do not need to define these yourself -- only implement the `handle` function. ## Next Steps * [Tools](https://docs.meetploy.com/agent-sdk/tools) -- Define custom tools with `defineTool()` * [Hooks](https://docs.meetploy.com/agent-sdk/hooks) -- React to agent lifecycle events * [State & Workspaces](https://docs.meetploy.com/agent-sdk/state) -- Understand per-user state # Hooks URL: https://docs.meetploy.com/agent-sdk/hooks # Hooks Lifecycle hooks let you run custom logic when specific events occur during an agent run. Every hook receives a `HookContext` as its first argument, giving you access to the full environment, state, and the ability to call tools. ## HookContext All hooks receive this context: ```typescript interface HookContext { userId: string; // The user who triggered the event chatId: string; // The active chat ID env: PloyEnv; // Full Ploy environment bindings state: StateManager; // Key-value state (get/set/delete/getJSON/setJSON) execute: (toolName: string, args: Record) => Promise; } ``` The `execute` function lets you call any registered tool (built-in or custom) from within a hook: ```typescript hooks: { async onMemorySet(ctx, key, secret) { // Call the artifact_create tool from within a hook await ctx.execute("artifact_create", { filename: "memory-log.txt", content: `Memory "${key}" was set (secret: ${secret})`, }); }, } ``` ## Available Hooks ### onRunPartial Fires during streamed generation when `streaming.enabled` is `true`. ```typescript onRunPartial?: (ctx: HookContext, partial: RunPartial) => Promise ``` `RunPartial` contains: ```typescript interface RunPartial { key: string; text: string; delta: string; step: number; isFinal: boolean; } ``` * `key` is stable for the current assistant turn, so you can update one draft message in place * `text` is the full accumulated partial text emitted so far * `delta` is the newest chunk for this emission * `step` is the current AI loop iteration * `isFinal` is `true` only when the SDK forces a last flush of buffered text before normal completion handling continues Example: ```typescript hooks: { async onRunPartial(ctx, partial) { await ctx.state.setJSON(`stream:${ctx.chatId}`, { key: partial.key, text: partial.text, lastDelta: partial.delta, step: partial.step, done: partial.isFinal, }); }, async onRunComplete(ctx) { await ctx.state.delete(`stream:${ctx.chatId}`); }, } ``` If you bridge partials into your own transport, treat `text` as the source of truth and use `key` as the message identity. `delta` is useful for logging or append-only transports, but `text` is the safer field for rendering. Use this hook as the primary way to observe streamed output today. The durable workflow does not hold onto the runtime `Messenger` instance passed to `handleMessage()`. `onRunPartial` is best-effort. If the hook throws, the SDK logs a warning and continues the run instead of failing the assistant response. ### onMemorySet Fires when the agent stores a memory entry. ```typescript onMemorySet?: (ctx: HookContext, key: string, secret: boolean) => Promise ``` ```typescript hooks: { async onMemorySet(ctx, key, secret) { if (secret) { await ctx.state.set(`audit:${ctx.userId}:${Date.now()}`, `secret stored: ${key}`); } }, } ``` ### onMemoryDelete Fires when the agent deletes a memory entry. ```typescript onMemoryDelete?: (ctx: HookContext, key: string) => Promise ``` ### onArtifactCreated Fires when the agent creates a file artifact. ```typescript onArtifactCreated?: (ctx: HookContext, filename: string, content: string) => Promise ``` ```typescript hooks: { async onArtifactCreated(ctx, filename, content) { // Store metadata about created artifacts const artifacts = await ctx.state.getJSON(`artifacts:${ctx.userId}`) ?? []; artifacts.push(filename); await ctx.state.setJSON(`artifacts:${ctx.userId}`, artifacts); }, } ``` ### onTaskScheduled Fires when the agent schedules a future task. ```typescript onTaskScheduled?: (ctx: HookContext, task: ScheduledTask) => Promise ``` The `ScheduledTask` contains: ```typescript interface ScheduledTask { id: string; description: string; scheduledTime: number; recurring: boolean; intervalMs?: number; } ``` ### onRunComplete Fires when the agent finishes a run with a response (no more tool calls). ```typescript onRunComplete?: (ctx: HookContext, response: string) => Promise ``` ```typescript hooks: { async onRunComplete(ctx, response) { // Log the response for analytics await ctx.state.set( `log:${ctx.userId}:${Date.now()}`, response.slice(0, 500), ); }, } ``` ### onRunError Fires when the agent run fails with an error. ```typescript onRunError?: (ctx: HookContext, error: Error) => Promise ``` ```typescript hooks: { async onRunError(ctx, error) { // Notify an external service await fetch("https://alerts.example.com/webhook", { method: "POST", body: JSON.stringify({ userId: ctx.userId, error: error.message, }), }); }, } ``` Hooks run inside the durable workflow, so they benefit from automatic retries on failure. Keep hooks lightweight to avoid slowing down the agent loop. ## Next Steps * [createAgent()](https://docs.meetploy.com/agent-sdk/create-agent) -- Pass hooks via the `hooks` config option * [Tools](https://docs.meetploy.com/agent-sdk/tools) -- Tools that trigger hooks (memory, artifacts, scheduling) * [Workflows](https://docs.meetploy.com/agent-sdk/workflows) -- Understand the durable tick loop that runs hooks # Agent SDK URL: https://docs.meetploy.com/agent-sdk # Agent SDK The Ploy Agent SDK (`@meetploy/agent-sdk`) wraps Ploy primitives -- state, workflows, timers, and file storage -- into a single `createAgent()` call. You get a fully functional AI agent with a durable tick loop, built-in tools, per-user workspaces, and lifecycle hooks out of the box. ## What You Get * **Durable workflow tick loop** -- AI calls and tool execution survive failures and restarts * **Built-in tools** -- Memory, artifacts, scheduling, and MCP server integration * **Per-user workspaces** -- Conversation history, memory, and settings isolated per user * **Type-safe custom tools** -- `defineTool()` infers argument types from JSON Schema * **Lifecycle hooks** -- React to memory changes, artifacts, scheduled tasks, and run completion with full env access * **Message queuing** -- Messages received during an active run are queued and processed in order * **Context compression** -- Optional summary-based compression for long-running conversations * **Commands** -- Built-in `/reset`, `/debug`, `/tools`, and MCP management ## Quick Start Install the SDK: ```bash pnpm add @meetploy/agent-sdk ``` Configure your `ploy.yaml`: ```yaml title="ploy.yaml" kind: worker agentSDK: true ``` The `agentSDK: true` flag automatically sets up all required bindings (`ai`, `state`, `fs`, `workflow`, `timer`) with the correct names and defaults. No manual binding configuration needed. Create your agent: ```typescript title="src/index.ts" import { createAgent, defineTool } from "@meetploy/agent-sdk"; const weatherTool = defineTool({ name: "get_weather", description: "Get the current weather for a city", parameters: { type: "object", properties: { city: { type: "string", description: "City name" }, }, required: ["city"], }, async execute(args, ctx) { // args.city is typed as string const response = await fetch(`https://wttr.in/${args.city}?format=3`); return await response.text(); }, }); export default createAgent({ systemPrompt: "You are a helpful weather assistant.", tools: [weatherTool], handle(req, env, agent) { // Your custom HTTP handler -- parse the request, // call agent.handleMessage(), return a response return new Response("OK"); }, }); ``` That's it. The SDK handles the durable workflow loop, AI calls, tool execution, workspace persistence, and message queuing automatically. ## How It Works When a user sends a message: 1. `handleMessage()` loads or creates the user's workspace 2. If a run is already active, the message is queued 3. Otherwise, a durable workflow is triggered 4. The workflow loops: call the AI, execute any tool calls, repeat 5. When the AI responds without tool calls, the run completes 6. Any queued messages trigger a new run The SDK owns the `fetch`, `timer`, and `workflows` handlers on the returned Ploy export. Your custom logic goes in the `handle` function, which receives the request, env, and an `AgentContext` with `handleMessage`, `commands`, and `state`. ## Next Steps * [createAgent()](https://docs.meetploy.com/agent-sdk/create-agent) -- Configuration options and the handle function * [Tools](https://docs.meetploy.com/agent-sdk/tools) -- Built-in tools and defining custom tools with `defineTool()` * [Hooks](https://docs.meetploy.com/agent-sdk/hooks) -- Lifecycle hooks for reacting to agent events * [State & Workspaces](https://docs.meetploy.com/agent-sdk/state) -- Per-user workspace management and the StateManager * [Commands](https://docs.meetploy.com/agent-sdk/commands) -- Built-in commands for users * [Workflows](https://docs.meetploy.com/agent-sdk/workflows) -- How the durable tick loop works # State & Workspaces URL: https://docs.meetploy.com/agent-sdk/state # State & Workspaces The Agent SDK manages per-user state automatically through **workspaces**. Each user gets an isolated workspace containing their conversation history, optional conversation summary, memory entries, MCP server configs, and run state. The `StateManager` provides a typed wrapper over the raw Ploy `StateBinding`. ## Workspaces A workspace is created automatically when a user sends their first message. It's stored in the state binding under the key `agent:workspace:{userId}`. ```typescript interface Workspace { userId: string; chatId: string; platform: string; messages: ChatMessage[]; // Conversation history conversationSummary: string | null; // Running summary used for compressed context memory: Record; // User memories (set via memory tools) mcpServers: McpServer[]; // Installed MCP servers debugMode: boolean; // Debug mode toggle activeRunId: string | null; // Active workflow run ID (null if idle) queue: QueuedMessage[]; // Messages queued during active runs } ``` ### Automatic Behaviors The SDK handles these workspace operations automatically: * **Creation** -- A default workspace is created on the user's first message * **Message trimming** -- Without context compression, conversation history is capped at 50 messages * **Context compression** -- With `contextCompression` enabled, older history is summarized into `conversationSummary` * **Memory injection** -- Memory entries are appended to the system prompt (secrets are hidden) * **Summary injection** -- `conversationSummary` is appended to the system prompt when present * **Message queuing** -- Messages received during an active run are queued and processed in order * **Run tracking** -- `activeRunId` prevents concurrent runs for the same user ## StateManager The `StateManager` wraps the raw `StateBinding` with JSON-aware helpers. It's available on `AgentContext.state`, `ToolContext.state`, and `HookContext.state`. ### API ```typescript interface StateManager { get(key: string): Promise; set(key: string, value: string): Promise; delete(key: string): Promise; update(key: string, update: StateUpdateDoc): Promise; getJSON(key: string): Promise; setJSON(key: string, value: unknown): Promise; } ``` The `update` method applies a MongoDB-style update document to JSON values atomically using SQLite JSON functions. Supported operators: `$set`, `$unset`, `$inc`, `$push`, `$pop`. See [State > update()](https://docs.meetploy.com/workers/state#updatekey-update---atomic-json-updates) for details. ### Usage in handle() ```typescript handle: async (req, env, agent) => { // Read state directly const visits = (await agent.state.getJSON("visits")) ?? 0; await agent.state.setJSON("visits", visits + 1); return Response.json({ visits: visits + 1 }); }; ``` ### Usage in Tools ```typescript const myTool = defineTool({ name: "save_note", description: "Save a note", parameters: { type: "object", properties: { text: { type: "string" } }, required: ["text"], }, async execute(args, ctx) { await ctx.state.set(`note:${ctx.userId}`, args.text); return "Note saved."; }, }); ``` ### Usage in Hooks ```typescript hooks: { async onRunComplete(ctx, response) { const count = await ctx.state.getJSON(`runs:${ctx.userId}`) ?? 0; await ctx.state.setJSON(`runs:${ctx.userId}`, count + 1); }, } ``` ### Atomic Workspace Updates The SDK provides `updateWorkspace()` for partial updates to workspace state without loading and saving the entire object: ```typescript import { updateWorkspace } from "@meetploy/agent-sdk"; // Set a single field await updateWorkspace(state, userId, { $set: { activeRunId: null }, }); // Append to the message queue await updateWorkspace(state, userId, { $push: { queue: { text: "hello", timestamp: Date.now() } }, }); // Multiple atomic operations await updateWorkspace(state, userId, { $set: { activeRunId: "run_123", chatId: newChatId, platform: "slack" }, }); ``` This is more efficient than `loadWorkspace` + modify + `saveWorkspace` and avoids race conditions when concurrent requests touch the same workspace. ## Memory Entries Memory entries are key-value pairs stored in the workspace. The agent can set, get, delete, and list them using the built-in memory tools. Memories are automatically injected into the system prompt so the agent remembers user preferences across conversations. ```typescript interface MemoryEntry { value: string; secret: boolean; // Hidden in debug output and system prompt createdAt: number; } ``` Secret memories (e.g., API keys) are injected with the value `[SECRET]` in the system prompt and debug views, but the full value is available to tools. State values are strings. Use `getJSON`/`setJSON` for structured data. The SDK uses `JSON.stringify`/`JSON.parse` internally. ## Next Steps * [createAgent()](https://docs.meetploy.com/agent-sdk/create-agent) -- The `state` property on `AgentContext` * [Tools](https://docs.meetploy.com/agent-sdk/tools) -- Access state via `ctx.state` in tool execute functions * [Commands](https://docs.meetploy.com/agent-sdk/commands) -- The `/reset` command deletes the user's workspace # Tools URL: https://docs.meetploy.com/agent-sdk/tools # Tools The Agent SDK provides built-in tools for common agent capabilities and a `defineTool()` helper for creating custom tools with full TypeScript type inference. ## Built-in Tools All built-in tools are enabled by default and can be toggled via `features` in `AgentConfig`. ### Memory Tools Store and recall user-specific information across conversations. | Tool | Description | | --------------- | ---------------------------------------------------- | | `memory_set` | Store a key-value pair (optionally marked as secret) | | `memory_get` | Retrieve a stored value by key | | `memory_delete` | Delete a stored value | | `memory_list` | List all stored memory keys | Memory entries are persisted in the user's workspace and automatically injected into the system prompt. Secret entries are hidden from debug output. ```typescript features: { memory: true; } // default ``` ### Artifact Tool Create files and send them to the user. | Tool | Description | | ----------------- | ---------------------------------------------------------------------- | | `artifact_create` | Create a file, store it in file storage, and send it via the messenger | Files are stored under `{userId}/{filename}` in the `FILES` binding. ```typescript features: { artifacts: true; } // default ``` ### Scheduling Tools Schedule and manage tasks for future execution. | Tool | Description | | ----------------------- | --------------------------------------------------- | | `schedule_task` | Schedule a one-time or recurring task | | `list_scheduled_tasks` | List all tasks the agent has scheduled | | `get_scheduled_task` | Get the current status of a specific scheduled task | | `update_scheduled_task` | Update a task's description, time, or recurrence | | `delete_scheduled_task` | Cancel a scheduled task so it will no longer fire | When a scheduled time arrives, the SDK triggers a new workflow run with the task description injected as a user message. `list_scheduled_tasks` returns tasks tracked in the user's workspace. `get_scheduled_task` queries the scheduler binding directly, so it reflects real-time status (returns not-found for tasks that have already fired). ```typescript features: { scheduling: true; } // default ``` ### MCP Tool Call tools provided by installed MCP (Model Context Protocol) servers. | Tool | Description | | --------------- | -------------------------------------- | | `mcp_call_tool` | Call a tool on an installed MCP server | Only available when at least one MCP server is installed in the user's workspace. See [Commands](https://docs.meetploy.com/agent-sdk/commands) for how users install MCP servers. ```typescript features: { mcp: true; } // default ``` ## Custom Tools with `defineTool()` `defineTool()` creates a type-safe tool definition where the `execute` function's `args` parameter is automatically typed from the JSON Schema `parameters` object. ### Basic Example ```typescript import { defineTool } from "@meetploy/agent-sdk"; const searchTool = defineTool({ name: "search", description: "Search for information", parameters: { type: "object", properties: { query: { type: "string", description: "Search query" }, limit: { type: "number", description: "Max results" }, }, required: ["query"], }, async execute(args, ctx) { // args.query: string (required) // args.limit?: number (optional -- not in required array) const results = await doSearch(args.query, args.limit ?? 10); return JSON.stringify(results); }, }); ``` ### Type Inference `defineTool()` uses TypeScript's `const` generic inference to map JSON Schema types to TypeScript types: | JSON Schema `type` | TypeScript type | | ------------------ | ------------------------- | | `"string"` | `string` | | `"number"` | `number` | | `"integer"` | `number` | | `"boolean"` | `boolean` | | `"object"` | `Record` | | `"array"` | `unknown[]` | Properties listed in `required` are required; all others are optional (`?`). ### ToolContext The `ctx` parameter in `execute` provides access to user context and platform bindings: ```typescript interface ToolContext { userId: string; // Current user ID chatId: string; // Current chat ID env: PloyEnv; // Full Ploy environment bindings state: StateManager; // Key-value state (get/set/delete/getJSON/setJSON) messenger: Messenger; // Platform messenger } ``` ### Using ToolDefinition Directly If you prefer to type args manually instead of using `defineTool()`, use `ToolDefinition`: ```typescript import type { ToolDefinition } from "@meetploy/agent-sdk"; const myTool: ToolDefinition<{ city: string; units?: string }> = { name: "get_weather", description: "Get weather for a city", parameters: { type: "object", properties: { city: { type: "string" }, units: { type: "string" }, }, required: ["city"], }, async execute(args, ctx) { // args is { city: string; units?: string } return `Weather in ${args.city}`; }, }; ``` Custom tools must return a `Promise`. The returned string is sent back to the AI as the tool result for the next iteration of the tick loop. ## Next Steps * [createAgent()](https://docs.meetploy.com/agent-sdk/create-agent) -- Pass tools via the `tools` config option * [Hooks](https://docs.meetploy.com/agent-sdk/hooks) -- React when tools create artifacts or schedule tasks * [State & Workspaces](https://docs.meetploy.com/agent-sdk/state) -- Access state from within tool execute functions # Workflows URL: https://docs.meetploy.com/agent-sdk/workflows # Workflows The Agent SDK uses Ploy's durable workflow system to run the agent loop. Each user message triggers a workflow execution that loops through AI calls and tool execution until the agent produces a final response. Every step is persisted, so the loop survives failures and restarts. ## The Tick Loop When `handleMessage()` triggers a workflow, the `ploy_agent_run` workflow executes these steps: ### 1. Load Workspace Loads the user's workspace from state (or creates a default one). Appends the user's message to the conversation history and trims to the last 50 messages. ### 2. Build System Prompt Resolves the system prompt (static string or async function) and appends the user's memory entries. ### 3. AI Call + Tool Execution Loop The core loop runs up to `maxSteps` iterations (default: 30): 1. Build the message array (system prompt + conversation history) 2. Call `env.AI.run(model, inputs, options?)` 3. If `streaming.enabled` is on, the SDK parses OpenAI-compatible SSE chunks and emits throttled `onRunPartial` hook updates with the current accumulated assistant text 4. If the AI responds **without tool calls** -- the run is complete, the response is stored 5. If the AI responds **with tool calls** -- execute each tool, append results to the conversation, and loop Each iteration is a durable `step.run()`, so completed steps are skipped on retry. Only the final assistant message is written into workspace history. Streamed partials are transient and intended for hooks or transport adapters. ### 4. Check Queue After the run completes, the workflow checks for queued messages. If any exist, the first is dequeued and a new workflow is triggered to process it. ## Durability Every step in the workflow is persisted by Ploy's workflow engine: * **AI calls** -- `ai_call_1`, `ai_call_2`, etc. * **Tool executions** -- `tools_1`, `tools_2`, etc. * **State saves** -- `save_step_1`, `save_final_2`, etc. If a step fails, it's automatically retried. Completed steps are skipped on re-execution. ## Message Queuing When a user sends a message while a run is active, the message is queued in the workspace: ```typescript // This happens automatically inside handleMessage() if (workspace.activeRunId) { workspace.queue.push({ text, timestamp: Date.now() }); await saveWorkspace(state, workspace); return; // Don't trigger a new workflow } ``` After the current run completes, the workflow dequeues and processes the next message. This ensures messages are processed in order without concurrent runs. ## Configuration The workflow is named `ploy_agent_run` and is automatically configured when you set `agentSDK: true` in `ploy.yaml`: ```yaml title="ploy.yaml" kind: worker agentSDK: true ``` This expands to `workflow: { PLOY_AGENT_WORKFLOW: ploy_agent_run }` along with all other required bindings. The SDK registers the workflow handler automatically. You do not need to implement it. ### maxSteps Control the maximum iterations of the AI-tool loop: ```typescript createAgent({ maxSteps: 50, // default: 30 // ... }); ``` This prevents runaway tool loops from consuming resources. ## Timer Integration Scheduled tasks use Ploy's timer binding. When a timer fires, the SDK's `timer` handler: 1. Reads the task payload (userId, chatId, platform, description) 2. Injects `[Scheduled task]: {description}` as a user message 3. Triggers a new `ploy_agent_run` workflow This means scheduled tasks are processed through the same durable loop as regular messages. The timer binding (`PLOY_AGENT_SCHEDULER`) is also automatically configured by `agentSDK: true`. The workflow and timer handlers are owned by the SDK. With `agentSDK: true`, all bindings are configured automatically -- you only need to implement the `handle` function for incoming requests. ## Next Steps * [createAgent()](https://docs.meetploy.com/agent-sdk/create-agent) -- Configure `maxSteps` and other options * [Hooks](https://docs.meetploy.com/agent-sdk/hooks) -- `onRunComplete` and `onRunError` fire at the end of the loop * [State & Workspaces](https://docs.meetploy.com/agent-sdk/state) -- How workspace state persists across workflow steps * [Ploy Workflows](https://docs.meetploy.com/workflows) -- The underlying Ploy workflow system # Delegated AI credentials URL: https://docs.meetploy.com/ai/delegation # Delegated AI credentials A trusted service can exchange its existing project AI Bearer token for a short-lived task credential through Ploy's built-in broker. This is a real platform endpoint, not an application-supplied signing interface. Only the delegated token belongs in the task or sandbox. Keep the parent project token on the trusted service, and never send `PLOY_AI_TOKEN_SECRET` or upstream provider keys to customer workers, browsers, or sandboxes. ## Provision and manage through the CLI Use your existing `ploy auth login` platform login as an **owner or admin** of the exact organization and project. No new signing secret or provider key is required, and no billing plan or credits are changed automatically. ```sh ploy api ai configure project-example --org org-example --enabled true --json ploy api ai models project-example --org org-example --json ploy api ai delegate project-example --org org-example \ --tenant tenant-example --task task-example --models provider/model \ --ttl-seconds 60 --max-requests 1 --json ploy api ai revoke project-example grant-example --org org-example --yes --json ``` `models` returns the actual upstream catalog without inference. Choose an explicit available low-cost model from that catalog; no fallback model is selected. Enabling AI requires an already eligible paid organization; it never upgrades or funds an account. Keep `ai: true` in `ploy.yaml` for subsequent deployments: a build's configuration can update the project flag, and existing deployment-resolution caches may delay an operator flag change. `delegate` outputs a sensitive **task-only** token only when `--json` is supplied. Protect stdout and pipe it only to your authorized task credential handoff; do not paste tokens into logs, issues or shell history. Without `--json`, the token is hidden. The default requested lifetime is 600 seconds, also capped by the operator session's remaining lifetime. Request/rate integers are strictly validated, and both rate options must be supplied together. Revocation requires `--yes`. The authenticated management API is: * `POST /orgs/{orgId}/projects/{projectId}/ai/delegations`, with the task scope below and optional `deploymentId`. Response: `{token, grantId, expiresAt}`; Unix milliseconds. Unknown scope overrides are rejected. * `POST /orgs/{orgId}/projects/{projectId}/ai/delegations/{grantId}/revoke`, body `{ "confirmation": "REVOKE" }`. * `PATCH /orgs/{orgId}/projects/{projectId}/ai/configuration`, body `{ "enabled": true }` or `false`. * `GET /orgs/{orgId}/projects/{projectId}/ai/models`, with no request body or inference. All four require the existing platform login/session and owner/admin membership, with exact organization/project ownership. An optional deployment must belong to that project. Responses are not cacheable; no endpoint exports a broad project credential. Revocation remains available when project AI is disabled or its plan is no longer eligible. ## Unattended trusted-service delegation A direct CLI task grant is useful for a bounded smoke test, **not** a renewable bootstrap credential for an unattended service. Deploy the trusted service with `ai: true`; Ploy supplies a project/deployment-scoped AI capability without a user-managed signing secret. The generic binding calls the same platform broker through the private AI service: ```ts const grant = await env.AI.delegate({ tenantId: authorizedTenant.id, taskId: task.id, models: [selectedCatalogModel], ttlSeconds: 600, maxRequests: 20, rate: { requests: 5, windowSeconds: 60 }, }); // Hand off only grant.token to this task, never the parent worker credential. // On completion/cancellation, revoke future admissions explicitly: await env.AI.revoke(grant.grantId); ``` The trusted service authorizes task ownership before each mint or renewal and keeps grant IDs for revocation. A later renewal creates a new grant, not a child of the old task token. Keep the project capability in the trusted worker binding; task sandboxes must suppress broad automatic project-token injection and receive only their bounded task credential. Do not use a platform CLI session as the service's runtime credential. The handler's cached worker identity now includes a 30-minute AI credential epoch, shorter than the default one-hour project credential lifetime. New requests load a fresh isolate and platform-minted capability after the epoch boundary. This changes neither task IDs nor durable workflow state and does not replay, retry or cancel customer requests. Existing in-flight work is not restarted; a worker retaining its old environment for over an hour can still reach that environment's token expiry and must surface the failure rather than replay inference. The raw escape hatch also remains available to the **trusted worker**: `POST http://ai/delegate` with its injected `PLOY_AI_TOKEN`. `env.AI.delegate`/`revoke` avoid manual URL/header assembly and use the private scoped service; the local emulator uses the same client logic with its configured AI endpoint. Neither facade returns a signing secret or broad project token. ## Issue a credential Call `POST /ai/delegate` on the public Ploy API (or the internal AI service from a trusted platform binding), using `Authorization: Bearer ` and a JSON object: ```json { "tenantId": "tenant-example", "taskId": "task-example", "models": ["provider/model"], "ttlSeconds": 600, "maxRequests": 20, "rate": { "requests": 5, "windowSeconds": 60 } } ``` * `tenantId` and `taskId`: required nonempty strings, at most 256 characters. The trusted issuer must derive these from its authorized task, not forward unvalidated sandbox input. * `models`: 1–100 exact model IDs, each at most 256 characters. The entire serialized UTF-8 delegation scope must fit in 4,096 bytes; oversized scopes are rejected before issuance so the Bearer token fits ordinary HTTP header limits. No wildcard expansion or normalization. An alias such as `auto` authorizes that upstream alias and its routing; choose explicit IDs when tasks must not use automatic routing. * `ttlSeconds`: required integer, 1–600 seconds. Expiry is the earlier of the requested lifetime and the parent token's expiry. * `maxRequests`: optional positive integer, at most 2,147,483,647. Omission means no total request limit within the short lifetime. * `rate`: optional fixed-window limit, with positive integer `requests` (at most 2,147,483,647) and integer `windowSeconds` from 1–600. Windows begin on the first accepted request and reset on an admission after the window ends. Response (`200`): ```json { "token": "opaque-signed-token", "grantId": "platform-generated-grant-id", "expiresAt": 1790000000000 } ``` `expiresAt` is Unix time in **milliseconds**. Treat the token as opaque: it retains Ploy's existing signed two-part HMAC format, not a JWT. The platform signs the exact project, optional deployment, task, tenant, model list, limits and expiry. Request-supplied project/deployment/expiry fields cannot override the parent. Existing project AI credentials keep their original behavior. Delegated tokens cannot issue child credentials or revoke grants. Management endpoints accept only owner project Bearer credentials, not query-token or `x-api-key` authentication. Project AI enablement, paid-plan eligibility, project/organization deletion and deployment ownership are checked for management and inference requests. ## Call the gateway Supply the delegated token as `Authorization: Bearer ` (or the inference protocol's `x-api-key`) on the Ploy AI endpoint. Each request must be JSON, at most 16 MiB, and contain a top-level `model` matching the signed allowlist. Allowed routes are POST `/ai/run`, `/ai/v1/chat/completions`, `/ai/v1/messages`, `/ai/v1/responses`, `/ai/v1/embeddings`, and `/ai/v1/images/generations`. `/ai/run` forwards to chat completions. Delegated GET/model-catalog, provider configuration, header-selected provider protocol routes, and administrative routes are denied. `ai-language-model-id` overrides are denied for delegated requests. Responses remains **stateless**: the gateway forces `store: false`; rejects background jobs, conversation/previous-response links, stored item/file references, and provider-hosted tools; and allows client-executed `function`/`custom` tools. Retrieval and deletion of shared upstream responses are unavailable. Streaming continues without buffering the upstream completion. The gateway discards incoming `x-ploy-*`, `x-llmgateway-*`, `x-tenant-id`, `x-task-id`, `x-project-id`, `x-deployment-id`, `x-grant-id` and `x-organization-id` headers. Attribution comes from verified token claims, never spoofable request headers. Provider/model attribution still comes from the upstream usage report. Tenant/task/grant IDs accompany usage events and are persisted in existing billing and deployment-live-log JSON metadata without storing prompts or credentials. Usage delivery retains the existing Redis queue and database fallback; simultaneous failure of both can still lose an event and is logged, not an exact spend guarantee. ## Revoke a credential Call `POST /ai/delegate/revoke` with an owner project AI Bearer token: ```json { "grantId": "platform-generated-grant-id" } ``` A matching grant returns `200 { "revoked": true }`; repeating revocation is safe. An unknown or foreign grant returns `404`. Project-only credentials may revoke that project's grants; a deployment-scoped owner may revoke only grants for that same project and deployment. Revocation is durable in PostgreSQL and checked on **every new request**, across gateway replicas and process restarts. There is no local allow-cache or stateless revocation substitute. Missing, expired, mismatched or revoked grants fail closed (`403`); atomic quota/rate admission failures return `429`, including a revoke/expiry race after the initial check. Store outages fail closed (`5xx`). Accepted in-flight inference is not terminated by later revocation. ## Replay and operational limits Tokens are bearer capabilities: possession allows repeated calls until expiry, revocation or exhaustion. This is not proof-of-possession or single-use authentication. Optional `maxRequests: 1` bounds admission to one upstream attempt, but does not provide idempotent retrieval of its result. Every accepted attempt consumes the atomic shared PostgreSQL request/rate reservation **before** upstream fetch, including transport errors, cancellation and provider errors. No refunds, automatic prompt replay, or implicit retries are added. A client retry is a new attempt and may incur another charge. Limits count requests, not dollars or tokens; model prices and request size vary. Explicitly revoke on task completion and on cancellation; keep the bounded lifetime as a fallback when the caller crashes before cleanup. Deployment requires the generated `ai_delegation` migration and a configured platform signing secret using the existing production secret checks. Issuance fails if persistence is unavailable; credentials are never knowingly returned without a durable grant. Expired rows currently remain for operational retention; no automatic pruning job is introduced here. No production configuration or migration is applied by this implementation. ## Verification From the repository root, rebuild dependency packages before integration tests: ```sh pnpm exec turbo run build --filter=@meetploy/tools --cache=local:rw pnpm exec vitest run packages/shared/src/ai-token.spec.ts packages/shared/src/ai-delegation.spec.ts apps/api/test/ai-gateway.spec.ts apps/api/test/ai-delegation.spec.ts packages/tools/src/ai-usage.spec.ts --exclude '**/.worktrees/**' PLOY_AI_DELEGATION_DB_TEST=1 pnpm exec vitest run packages/db/test/ai-delegation.spec.ts --exclude '**/.worktrees/**' ``` The opt-in PostgreSQL fixture connects only to the local seeded PostgreSQL at `127.0.0.1:5433`, using a connection-local temporary table created from the generated migration. It tests actual reservation SQL, rate-window rollover, persisted revocation and scope mismatch rejection without resetting or mutating existing project data. HTTP fixtures exercise both public and internal route trees with mocked upstream inference; they do not bill real models. # AI URL: https://docs.meetploy.com/ai # AI Ploy provides a built-in AI gateway for workers, allowing you to build AI-powered applications with `env.AI.run()` and with direct OpenAI-compatible SDK calls when needed. One `ai: true` line in `ploy.yaml` gives your worker a model endpoint and a per-deployment token — no provider keys to manage. Use it for chat features, summarisation, extraction, embeddings, or as the model backend for an agent. To build full agents with tools, hooks, and durable state, see the [Agent SDK](https://docs.meetploy.com/agent-sdk); to let agents run code, pair it with [Sandboxes](https://docs.meetploy.com/sandboxes). ## Enabling AI To use AI in your worker, add `ai: true` to your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic ai: true ``` This injects an `env.AI` binding plus the raw escape-hatch environment variables: * `AI` - AI binding with `env.AI.run(model, inputs, options?)` * `PLOY_AI_URL` - OpenAI-compatible base URL for direct SDK or HTTP requests * `PLOY_AI_TOKEN` - Authentication token (automatically managed per deployment) ## Local Development When you run `ploy dev`, remote AI bindings are attributed to an organization-scoped local development AI sandbox in Ploy. * If your checkout matches a deployed project, Ploy uses that project to choose the organization, then routes local AI usage through the organization's sandbox. * If your checkout does not match a deployed project and you belong to multiple organizations, set `PLOY_DEV_AI_PROJECT_ID` to any project in the target organization to choose the correct sandbox. * For full manual control, set both `PLOY_DEV_AI_URL` and `PLOY_DEV_AI_TOKEN`. Example: ```bash PLOY_DEV_AI_PROJECT_ID=proj_123 pnpm exec ploy dev ``` ## Basic AI Example Here's a simple worker that calls an AI model: ```typescript title="src/index.ts" interface Env { AI: Ai; PLOY_AI_URL: string; PLOY_AI_TOKEN: string; } export default { async fetch(request, env) { const url = new URL(request.url); // Health check endpoint if (url.pathname === "/health") { return new Response("ok"); } // AI endpoint if (url.pathname === "/ai") { try { // Get parameters from query string const model = url.searchParams.get("model") || "glm-4.6v-flash"; const prompt = url.searchParams.get("prompt") || "just reply 'OK'"; const data = await env.AI.run(model, { prompt }); return new Response(JSON.stringify(data), { status: 200, headers: { "Content-Type": "application/json" }, }); } catch (error) { return new Response( JSON.stringify({ error: error instanceof Error ? error.message : String(error), }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } } return new Response("hi!"); }, }; ``` ### Usage ```bash # Basic request curl https://your-deployment.ploy.app/ai # Custom prompt curl "https://your-deployment.ploy.app/ai?prompt=What is TypeScript?" # Different model curl "https://your-deployment.ploy.app/ai?model=gpt-4&prompt=Hello" ``` ## `env.AI.run()` Ploy exposes `env.AI.run(model, inputs, options?)`: ```typescript const response = await env.AI.run("auto", { prompt: "Hello, World", }); ``` `env.AI.run()` is the primary worker API. The raw `PLOY_AI_URL` and `PLOY_AI_TOKEN` variables remain available when you want to call the OpenAI-compatible gateway directly with your own client. ## Examples * `examples/ai-simple` uses `env.AI.run()` for the basic request path. * `examples/ai-streaming` uses `env.AI.run()` with `stream: true` and returns SSE. * `examples/ai-openai` uses the OpenAI SDK with `PLOY_AI_URL` and `PLOY_AI_TOKEN`. ## OpenAI-Compatible API Ploy's AI integration uses the OpenAI chat completions format: ### Request Format ```typescript { model: string; // Model name (e.g., "glm-4.6v-flash", "gpt-4") messages: Array<{ // Conversation messages role: "system" | "user" | "assistant"; content: string; }>; temperature?: number; // Randomness (0-2, default: 1) max_tokens?: number; // Maximum response length top_p?: number; // Nucleus sampling (0-1, default: 1) stream?: boolean; // Enable streaming responses } ``` ### Response Format ```typescript { id: string; object: "chat.completion"; created: number; model: string; choices: Array<{ index: number; message: { role: "assistant"; content: string; }; finish_reason: string; }>; usage: { prompt_tokens: number; completion_tokens: number; total_tokens: number; } } ``` ## Conversation Context Build conversational applications by maintaining message history: ```typescript interface Message { role: "system" | "user" | "assistant"; content: string; } export default { async fetch(request, env) { if (request.method !== "POST") { return new Response("Method Not Allowed", { status: 405 }); } try { const { messages, model = "glm-4.6v-flash" } = await request.json(); // Add system prompt const fullMessages: Message[] = [ { role: "system", content: "You are a helpful assistant that provides concise answers.", }, ...messages, ]; const data = await env.AI.run(model, { messages: fullMessages, }); return new Response(JSON.stringify(data), { headers: { "Content-Type": "application/json" }, }); } catch (error) { return new Response( JSON.stringify({ error: error instanceof Error ? error.message : String(error), }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, }; ``` ## Direct SDK Usage If you need a library that expects an OpenAI-compatible `baseURL` and `apiKey`, use the injected raw variables: ```typescript import OpenAI from "openai"; const client = new OpenAI({ apiKey: env.PLOY_AI_TOKEN, baseURL: env.PLOY_AI_URL, }); const response = await client.chat.completions.create({ model: "auto", messages: [{ role: "user", content: "Hello" }], }); ``` ## Vercel AI SDK Next.js projects with `ai: true` get Ploy registered as the [AI SDK](https://ai-sdk.dev)'s default provider, so a bare model id resolves through Ploy instead of the Vercel AI Gateway: ```typescript title="app/api/chat/route.ts" import { convertToModelMessages, streamText } from "ai"; export async function POST(req: Request) { const { messages } = await req.json(); const result = streamText({ model: "anthropic/claude-sonnet-5", messages: await convertToModelMessages(messages), }); return result.toUIMessageStreamResponse(); } ``` No provider setup, no `AI_GATEWAY_API_KEY`, and no code change when moving an existing AI Gateway app onto Ploy — model ids keep the same `provider/model` format. Ploy wires this up during the build (and during `ploy dev`) by generating two files next to your `app` directory: * `ploy-ai-provider.js` — registers `globalThis.AI_SDK_DEFAULT_PROVIDER` * `instrumentation.js` — imports it through the Next.js instrumentation hook If you already have an `instrumentation` file, Ploy adds the import to it and leaves the rest alone. Both files are regenerated on every build, so you can commit them or add them to `.gitignore`. This needs `ai` v5 or later in your project. To opt out, set `globalThis.AI_SDK_DEFAULT_PROVIDER` yourself or pass a model instance instead of a string — Ploy never overwrites a provider that is already registered. Set `PLOY_AI_GATEWAY_URL` to point the AI SDK at a specific gateway URL. By default it is derived from `PLOY_AI_URL`. ## Streaming `env.AI.run()` also supports streaming: ```typescript const stream = await env.AI.run("auto", { prompt: "Write one short sentence.", stream: true, }); return new Response(stream, { headers: { "Content-Type": "text/event-stream; charset=utf-8", }, }); ``` ### Usage ```bash curl -X POST https://your-deployment.ploy.app/ai \ -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "user", "content": "What is JavaScript?"}, {"role": "assistant", "content": "JavaScript is a programming language..."}, {"role": "user", "content": "How do I use async/await?"} ] }' ``` ## LangChain Integration Use [LangChain](https://js.langchain.com/) for advanced AI features like agents and tools: ### Installation ```json title="package.json" { "dependencies": { "@langchain/core": "^1.1.0", "@langchain/openai": "^1.1.3", "langchain": "^1.1.1", "zod": "^3.24.1" } } ``` ### Creating Tools Define tools that the AI can use: ```typescript title="src/index.ts" import { ChatOpenAI } from "@langchain/openai"; import { createAgent, tool } from "langchain"; import * as z from "zod"; interface Env { PLOY_AI_URL: string; PLOY_AI_TOKEN: string; } // Define a tool for getting weather information const getWeather = tool((input) => `It's always sunny in ${input.city}!`, { name: "get_weather", description: "Get the weather for a given city", schema: z.object({ city: z.string().describe("The city to get the weather for"), }), }); export default { async fetch(request, env) { const url = new URL(request.url); if (url.pathname === "/health") { return new Response("ok"); } if (url.pathname === "/ai") { try { const prompt = url.searchParams.get("prompt") || "just reply 'OK'"; // Initialize OpenAI-compatible model const model = new ChatOpenAI({ model: "glm-4.6v-flash", apiKey: env.PLOY_AI_TOKEN, configuration: { baseURL: env.PLOY_AI_URL, }, }); // Create agent with tools const agent = createAgent({ model, tools: [getWeather], }); // Invoke agent const result = await agent.invoke({ messages: [{ role: "user", content: prompt }], }); // Extract response const lastMessage = result.messages[result.messages.length - 1]; const content = typeof lastMessage.content === "string" ? lastMessage.content : JSON.stringify(lastMessage.content); // Return in OpenAI format return new Response( JSON.stringify({ choices: [ { message: { role: "assistant", content: content, }, }, ], }), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } catch (error) { return new Response( JSON.stringify({ error: error instanceof Error ? error.message : String(error), }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } } return new Response("LangChain agent example!"); }, }; ``` ## Token Usage and Billing Monitor token consumption in API responses: ```typescript const data = await response.json(); // Extract token usage const usage = data.usage; console.log(`Prompt tokens: ${usage.prompt_tokens}`); console.log(`Completion tokens: ${usage.completion_tokens}`); console.log(`Total tokens: ${usage.total_tokens}`); // Track costs (example rates) const cost = ( usage.prompt_tokens * 0.00001 + usage.completion_tokens * 0.00002 ).toFixed(4); console.log(`Estimated cost: $${cost}`); ``` Token usage varies by model. Larger models (like GPT-5) cost more per token than smaller models (like GPT-4o-mini). ## Examples ### Summarization Service ```typescript export default { async fetch(request, env) { if (request.method !== "POST") { return new Response("Method Not Allowed", { status: 405 }); } const { text } = await request.json(); const response = await fetch(`${env.PLOY_AI_URL}/chat/completions`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${env.PLOY_AI_TOKEN}`, }, body: JSON.stringify({ model: "glm-4.6v-flash", messages: [ { role: "system", content: "You are a summarization assistant. Provide concise summaries.", }, { role: "user", content: `Summarize the following text:\n\n${text}`, }, ], max_tokens: 150, }), }); const data = await response.json(); const summary = data.choices[0].message.content; return new Response(JSON.stringify({ summary }), { headers: { "Content-Type": "application/json" }, }); }, }; ``` ## Next Steps * [Agent SDK](https://docs.meetploy.com/agent-sdk) - Build AI agents with tools, hooks, and durable workflows * [Sandboxes](https://docs.meetploy.com/sandboxes) - Give agents an isolated environment to run code * [Workers Guide](https://docs.meetploy.com/workers) - Learn more about building workers * [Configuration](https://docs.meetploy.com/platform/configuration) - Configure your Ploy project * [LangChain Documentation](https://js.langchain.com/) - Explore LangChain features # React components URL: https://docs.meetploy.com/auth/components # React components `@meetploy/auth-react` gives React apps ready-made auth UI and hooks. It works with Next.js, Vite, TanStack Start, and any other React setup deployed on Ploy. ```bash pnpm add @meetploy/auth-react ``` ## Set up the provider Wrap your app in `AuthProvider`. It loads the current user and the project's enabled sign-in methods. ```tsx import { AuthProvider } from "@meetploy/auth-react"; export function App({ children }: { children: React.ReactNode }) { return {children}; } ``` In Next.js, put it in `app/layout.tsx`. The components are client components, so they work inside Server Component layouts. `apiUrl` defaults to `/_ploy/auth`. After configuring [shared sessions](https://docs.meetploy.com/auth/subdomains), use `` to call a sibling auth host. Requests include credentials; the browser origin must have the same scheme and port and be under the shared domain. [Passkeys](https://docs.meetploy.com/auth/passkeys#domains) must be migrated when that domain changes. ## Components | Component | What it renders | | ------------- | ---------------------------------------------------------------------------------------------------------------------- | | `SignInForm` | Every enabled method: provider buttons, a passkey button, the email and password form, and **Email me a sign-in link** | | `SignUpForm` | Sign-up with every enabled method, including passkey sign-up and extra metadata fields | | `UserButton` | An avatar that opens a menu with the user's name and email, **Manage account**, and **Sign out** | | `UserProfile` | An account page: profile, password, connected Google, Apple, and GitHub accounts, passkeys, and sign out | | `SignedIn` | Its children, only when a user is signed in | | `SignedOut` | Its children, only when nobody is signed in | All of them follow your project's [sign-in methods](https://docs.meetploy.com/auth#configure-sign-in-methods), so turning a method on in the dashboard shows it everywhere without a redeploy. ### A typical header ```tsx import { SignedIn, SignedOut, UserButton } from "@meetploy/auth-react"; export function Header() { return (
Sign in
); } ``` ### Sign-in and sign-up pages ```tsx "use client"; import { SignInForm } from "@meetploy/auth-react"; export default function LoginPage() { return ( location.assign("/signup")} /> ); } ``` `SignUpForm` takes the same props plus `fields`, a list of extra metadata fields such as `["name", "company"]`. | Prop | Description | | --------------------------------- | ------------------------------------------------- | | `redirectTo` | Navigate here after success | | `onSuccess`, `onError` | Callbacks with the user or the error | | `onSignUpClick` / `onSignInClick` | Show a link to the other form | | `theme` | `"auto"` (default), `"light"`, or `"dark"` | | `appearance` | Colors, radius, and font; see [Theming](#theming) | | `className` | Extra class on the root element | ### Account page ```tsx "use client"; import { UserProfile } from "@meetploy/auth-react"; export default function AccountPage() { return ; } ``` Users can change their password (or set one if their account has none), connect another provider (when it is enabled), disconnect one, add and remove passkeys, and sign out. Ploy refuses to remove the last way a user can sign in. Disconnecting a provider also deletes its stored tokens, but does not revoke the grant at the provider. For additional scopes and server-only API access, see [social sign-in](https://docs.meetploy.com/auth/social#call-the-provider-api). When [sign-in links](https://docs.meetploy.com/auth/emails#sign-in-links) are on, `SignInForm` offers **Email me a sign-in link** and then shows a **Check your inbox** screen. When [sign-in codes](https://docs.meetploy.com/auth/emails#sign-in-codes) are on, it offers **Email me a sign-in code** and then shows **We emailed you a code** with a 6-digit field that accepts pasting. `SignUpForm` offers the same email option next to the password and passkey sign-up. Call `sendMagicLink(email)`, `sendEmailCode(email)`, `verifyEmailCode(email, code)`, and `changePassword({ currentPassword, newPassword })` from `useAuth()` to build your own. ## Theming Every component follows the system color scheme by default, and switches to dark mode inside a `.dark` class (Tailwind's convention). Force a mode with `theme="light"` or `theme="dark"`. Change colors, corner radius, and font with `appearance`, on one component or on `AuthProvider` for all of them: ```tsx ``` | Variable | CSS custom property | | ------------------------ | -------------------------------- | | `colorPrimary` | `--ploy-auth-primary` | | `colorPrimaryHover` | `--ploy-auth-primary-hover` | | `colorPrimaryForeground` | `--ploy-auth-primary-foreground` | | `colorBackground` | `--ploy-auth-background` | | `colorText` | `--ploy-auth-foreground` | | `colorTextSecondary` | `--ploy-auth-muted` | | `colorBorder` | `--ploy-auth-border` | | `colorInputBackground` | `--ploy-auth-input-background` | | `colorInputBorder` | `--ploy-auth-input-border` | | `colorDanger` | `--ploy-auth-danger` | | `borderRadius` | `--ploy-auth-radius` | | `fontFamily` | `--ploy-auth-font-family` | `appearance` values apply in both light and dark mode. For different values per mode, set the custom properties in your own CSS instead: ```css .ploy-auth-root { --ploy-auth-primary: #4f46e5; } .dark .ploy-auth-root { --ploy-auth-primary: #818cf8; } ``` ## Server-side lifecycle hooks [Auth lifecycle hooks](https://docs.meetploy.com/auth/hooks) run in your worker, not in React. Component sign-up/sign-in flows respect before-hook refusals; the React hooks below only read client auth state. ## Hooks `useAuth()` exposes the state and every action, for building your own UI: | Field | Description | | --------------------------------------------------------------------------------------- | ---------------------------------------------------- | | `user`, `isLoading`, `isAuthenticated` | Current session | | `config` | Enabled methods from `/_ploy/auth/config` | | `redirectError` | `ploy_auth_error` code after a failed social sign-in | | `signIn`, `signUp` | Email and password | | `signInWithProvider(provider, { redirectTo })` | Start Google, Apple, or GitHub sign-in | | `signInWithPasskey`, `signUpWithPasskey`, `addPasskey`, `listPasskeys`, `removePasskey` | Passkeys | | `listIdentities`, `unlinkIdentity` | Linked provider accounts | | `signOut` | Revoke the session | The session lives in an `HttpOnly` cookie, so your code does not manage tokens. `AuthProvider` checks `/me` when mounted; it is not a background keep-alive timer. Browser `/me` checks renew due [sliding sessions](https://docs.meetploy.com/auth/sessions). Verify the user on the server with the [`PLOY_AUTH` binding](https://docs.meetploy.com/auth#server-side-authentication) or the [Next.js helpers](https://docs.meetploy.com/auth/nextjs). # Emails, sign-in links and passwords URL: https://docs.meetploy.com/auth/emails # Emails, sign-in links and passwords Ploy Auth sends these emails for your app, through [Ploy Email](https://docs.meetploy.com/email): | Email | Sent when | | ------------------- | ---------------------------------------------------------------------------- | | Verify your email | A user signs up with a password, or asks for the link again | | Sign-in link | A user asks for a [sign-in link](#sign-in-links) instead of using a password | | Sign-in code | A user asks for a [sign-in code](#sign-in-codes) | | Reset your password | A user asks for a reset on the **Forgot password?** page | | Password changed | A password was reset, changed, or added, as a notice to the account owner | The emails show your project name and work without any code in your app. You can change their wording with [email templates](#email-templates). Auth emails are off until email sending is enabled for your organization under **Dashboard → Email**. Until then, sign-in links, sign-in codes and password reset are unavailable and email verification is not enforced. Everything else keeps working. ## Email verification After a password sign-up, Ploy Auth emails a verification link. It is valid for 24 hours. Opening it marks the account as verified (`emailVerified: true`) and sends the user back to your app with `?ploy_auth_status=email_verified`; an invalid or expired link adds `?ploy_auth_error=invalid_token` instead. Users who sign in with Google, Apple, or GitHub are verified when the provider confirms their email, and users who sign in with a sign-in link are verified by opening it, so they never get this email. ### Require a verified email **Require email verification** is on by default for new auth setups. Change it under **Auth → Settings → Emails** to opt out or enable it for an older setup; existing settings are unchanged. For a new production binding, `auth.require_email_verification: false` in `ploy.yaml` seeds an opt-out. When verification is required: * Sign-up still creates the account and sends the link, but responds with `emailVerificationRequired: true` and no session. * Password and passkey sign-in for an unverified password account fail with `403` and code `email_not_verified`. The error only appears after the correct password, so it does not reveal which emails have accounts. * The [hosted sign-in page](https://docs.meetploy.com/auth/hosted-pages) and `SignInForm` then offer **Resend verification email**. * Opening the verification link also signs the user in, so they never type their password twice. It does so on any device the first time it verifies the address. After that, only in the browser that signed up or was refused with `email_not_verified`, so the link is not a lasting login for anyone it is forwarded to; elsewhere it just reports the address as verified. * A page waiting in the sign-up browser can poll `POST /email/verify/continue`: it answers `403 email_not_verified` until the address is verified, wherever that happens, then starts the session. Without the browser's pending-verification cookie it answers `401 no_pending_verification`. * A [sign-in link](#sign-in-links) or [code](#sign-in-codes) always works: using it proves the address. The setting has no effect while auth emails are off, so users are never locked out by an email that can't be sent. ## Sign-in links A sign-in link (often called a magic link) lets users sign in with just their email address. Turn on **Magic link (email sign-in link)** under **Auth → Settings → Sign-in methods**. It counts as a sign-in method, so it can be the only one, but it only works while auth emails are enabled; the dashboard shows a hint when they are not. When it is on, the [hosted sign-in page](https://docs.meetploy.com/auth/hosted-pages) and `SignInForm` offer **Email me a sign-in link**. Without password sign-in it becomes the main action of the email form. * The link is valid for 15 minutes and works once. Only a hash of it is stored. * Opening the link shows a confirmation page with a **Continue as** button. The link itself never signs anyone in, so email security scanners that open links ahead of the user don't use it up. * For an address without an account, the link creates the account when sign-ups are allowed. **Require name** applies: send `metadata.name` with the request, or the request fails with code `name_required` and the forms ask for the name. * The response is the same whether or not an account exists, and no email is sent for unknown addresses while sign-ups are off. * Opening the link marks the email as verified. If the account was never verified, its password and passkeys are removed first, so someone who registered an address they don't own loses access. The owner can then [set a password](#change-or-set-a-password). * After confirming, the user lands on the `redirect` passed with the request, signed in. An expired or used link returns there with `?ploy_auth_error=invalid_token`. ```typescript await fetch("/_ploy/auth/magic-link", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: "user@example.com", redirect: "/dashboard" }), }); ``` ## Sign-in codes A sign-in code is a 6-digit one-time code sent by email. It suits apps whose users read their mail on another device, such as a phone, where opening a link would sign in the wrong browser. Turn on **Email code** under **Auth → Settings → Sign-in methods**. Like sign-in links, it counts as a sign-in method and only works while auth emails are enabled. When it is on, the [hosted sign-in page](https://docs.meetploy.com/auth/hosted-pages) and `SignInForm` offer **Email me a sign-in code**. After the user enters their email, they see **We emailed you a code** and a code field that accepts typing or pasting; a complete code signs them in. * The code is valid for 10 minutes and works once. It is stored only as a keyed hash, never in plain text. * Each address has one active code: requesting a new one replaces the previous code. * After 5 wrong attempts the code stops working and the user has to request a new one (code `too_many_attempts`). Attempts also count toward the per-IP sign-in limit. * A wrong, expired, or used code fails with `400` and code `invalid_code`. The answer is the same for addresses without an account. * New accounts, **Require name**, sign-ups being off, and unverified accounts follow the same rules as [sign-in links](#sign-in-links): using the code verifies the email address. ```typescript await fetch("/_ploy/auth/email-code", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: "user@example.com" }), }); const res = await fetch("/_ploy/auth/email-code/verify", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: "user@example.com", code: "123456" }), }); const { user } = await res.json(); ``` ### Links and codes together With both sign-in links and codes on, users get a single email with the code and a sign-in link, and either one signs them in. `POST /magic-link` and `POST /email-code` then send the same email, valid for 10 minutes; the forms request it with `/email-code` and show the code field. ## Password reset When password sign-in is on and auth emails are enabled, the hosted sign-in page and `SignInForm` show **Forgot password?**. It opens `/_ploy/auth/forgot-password`, which emails a link to `/_ploy/auth/reset-password`. * The link is valid for one hour and works once: it stops working as soon as the password changes. * Setting the new password signs the user out on every device and marks their email as verified. * The forgot-password page responds the same whether or not an account exists, so it can't be used to find out who has an account. Accounts that only use passkeys, social sign-in, or sign-in links have no password and get no email. After the reset the user lands on the sign-in page with a confirmation and continues to the `redirectTo` you passed to `/forgot-password`. ## Change or set a password Signed-in users can change their password, or add one to an account created with a sign-in link, a passkey, or a social provider. `UserProfile` has a **Password** section for this; from your own UI, `POST /password/change` with the session cookie or an `Authorization: Bearer` header: ```typescript await fetch("/_ploy/auth/password/change", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ currentPassword, newPassword }), }); ``` * `currentPassword` is required when the account already has a password; a wrong one fails with `401` and code `invalid_credentials`. `GET /me` returns `hasPassword` so you know whether to ask for it. * The new password must meet the same rules as at sign-up (code `weak_password` otherwise). * Every other session of the user is signed out; the current one stays signed in. * The owner gets a notice email when auth emails are enabled. Password sign-in must be on for the project. ## Sender settings Configure the sender under **Auth → Settings → Emails**: | Setting | Description | | ------------ | -------------------------------------------------------------------------------------------------- | | Send from | Your organization's `.ploy.email` domain (the default) or one of its verified custom domains | | Address | The part before the `@`, for example `noreply` (the default) or `hello` | | Display name | The name shown in the inbox. Defaults to the project name | The settings show a preview of the From address, for example `Acme `. If a custom domain stops being verified, emails are sent from the `ploy.email` domain until it is verified again. See [Email](https://docs.meetploy.com/email) to add a custom domain. ## Email templates Change the wording of each auth email under **Auth → Settings → Email templates**. Pick the email (Verify email, Sign-in link, Sign-in code, Reset password, Password changed) and override any of these fields; empty fields keep the default text: | Field | Max length | Description | | ------------ | ---------- | -------------------------------------------------- | | Subject | 200 | The subject line | | Heading | 200 | The title at the top of the email | | Body | 2000 | The message. Separate paragraphs with a blank line | | Button label | 50 | The text of the button (not in Password changed) | The fields are plain text and can use these placeholders: | Placeholder | Value | | ---------------- | ------------------------------------------------------------ | | `{{app_name}}` | Your project name | | `{{email}}` | The recipient's address | | `{{link}}` | The link in the email, in emails that have one | | `{{code}}` | The sign-in code, in sign-in code emails | | `{{expires_in}}` | How long the link or code is valid, for example `10 minutes` | Placeholders that don't apply to an email, and unknown ones, are left as written. **Reset to default** clears the overrides of the selected email, and the preview next to the fields shows the email as it will be sent. Your text is always placed into the standard email layout and escaped, so HTML in a template shows up as text. The button, the link, the code, and the security note at the bottom are always included, so a template can't break sign-in or hide what the email is for. ## Rate limits To protect your users' inboxes, verification, sign-in link, sign-in code, and reset emails are limited to 3 per hour per email address and 10 per hour per IP address. Further requests return `429` with `code: "rate_limited"` and a `Retry-After` header. Password changes share the sign-in limits. Emails also count toward your project's daily email limit. ## Endpoints | Endpoint | Method | Body | Description | | ----------------------- | ------ | ----------------------------------- | ------------------------------------------------------- | | `/email/verify/request` | POST | `{ email, redirect? }` | Send the verification email again. Always returns `200` | | `/email/verify` | GET | `?token=&redirect=` | The link in the verification email | | `/magic-link` | POST | `{ email, redirect?, metadata? }` | Email a sign-in link. Always returns `200` | | `/magic-link/verify` | GET | `?token=&redirect=` | The link in the email: a page to confirm the sign-in | | `/magic-link/verify` | POST | `{ token }` | Use the link and start a session. Returns `{ user }` | | `/email-code` | POST | `{ email, redirect?, metadata? }` | Email a sign-in code. Always returns `200` | | `/email-code/verify` | POST | `{ email, code }` | Use the code and start a session. Returns `{ user }` | | `/password/forgot` | POST | `{ email, redirect? }` | Send a password reset email. Always returns `200` | | `/password/reset` | POST | `{ token, password }` | Set a new password with the token from the reset link | | `/password/change` | POST | `{ currentPassword?, newPassword }` | Change or set the signed-in user's password | | `/forgot-password` | GET | `?redirectTo=` | Hosted page to request a reset link | | `/reset-password` | GET | `?token=&redirectTo=` | Hosted page to choose a new password | `redirect` and `redirectTo` accept a path or a URL on your app's origin, like everywhere else in Ploy Auth. `/email/verify/request`, `/magic-link`, `/email-code`, and `/password/forgot` return `403` with code `email_unavailable` while auth emails are off, `/magic-link` returns `magic_link_disabled` while sign-in links are off, and `/email-code` returns `email_code_disabled` while sign-in codes are off. `GET /config` reports `emailVerificationRequired`, `passwordResetEnabled`, `magicLink`, and `emailCode` so you can adapt your own UI. With `@meetploy/auth-react`, use the hook instead of calling the endpoints: ```tsx import { PloyAuthError, useAuth } from "@meetploy/auth-react"; const { user, signIn, resendVerification, sendMagicLink, sendEmailCode, verifyEmailCode, requestPasswordReset, resetPassword, changePassword, } = useAuth(); try { await signIn(email, password); } catch (error) { if (error instanceof PloyAuthError && error.code === "email_not_verified") { await resendVerification(email); } } await sendMagicLink(email, { redirectTo: "/dashboard" }); await sendEmailCode(email); await verifyEmailCode(email, code); // signs in, returns the user await requestPasswordReset(email, { redirectTo: "/account" }); await resetPassword(token, newPassword); await changePassword({ currentPassword: user?.hasPassword ? currentPassword : undefined, newPassword, }); ``` ## Lifecycle hooks [Auth hooks](https://docs.meetploy.com/auth/hooks) apply to both magic-link and email-code sign-in. For new users, approval runs when credentials are verified, not when the email is requested. `afterEmailVerified` runs when an account becomes verified, including accounts created already verified by social sign-in, magic link, or email code. Merely verifying an existing account by email link does not create a session. ## Local development Under `ploy dev` nothing is sent. Every auth email lands in a local inbox instead: open the dev dashboard and choose **Auth → Emails** to read it and click its links. The terminal also prints each email's link. Sign-in links and sign-in codes are always on locally, next to passwords and passkeys, so local sign-in emails carry both the link and the code. Email verification is required by default for new local setups; turn off **Require email verification** in the dev dashboard's auth settings to opt out. Existing local settings are preserved. # Hooks URL: https://docs.meetploy.com/auth/hooks # Hooks Auth hooks let your app take part in sign-up and sign-in. Export them from your worker as `auth`, next to `fetch`, and Ploy Auth calls them for every sign-in method: password, sign-in links and codes, passkeys, and Google, Apple, and GitHub. * **Before hooks** run before the action and can refuse it. `beforeSignUp` can also change the new account's metadata. * **After hooks** are notifications. They run once the action is done and never slow it down or make it fail. ```typescript title="src/index.ts" import type { Database, PloyHandler } from "@meetploy/types"; interface Env { DB: Database; } export default { async fetch(request, env) { return new Response("Hello!"); }, auth: { beforeSignUp(event) { if (!event.email.endsWith("@example.com")) { return { allow: false, message: "Sign up with your work email." }; } return { metadata: { ...event.metadata, plan: "free" } }; }, async afterEmailVerified(event, env) { await addToNewsletter(event.user.email); }, }, } satisfies PloyHandler; ``` Hooks run in your deployment, with the same `env` bindings as `fetch`. Ploy calls them over its internal network; they are not reachable from the internet. ## Turn hooks on Turn on **Auth hooks** under **Auth → Settings → Sign-ups and sessions**. Only organization owners and admins can change it. While it is off, Ploy Auth never calls your worker for auth events. Each project's preview deployments call their own hooks. `ploy dev` always runs the hooks your local worker exports, so you can try them before turning them on. ## Hooks | Hook | Runs | Event fields | | --------------------- | ------------------------------------------------------------------------ | ----------------------------------------- | | `beforeSignUp` | Before an account is created | `email`, `metadata`, `method`, `provider` | | `beforeSignIn` | Before an existing user gets a session | `user`, `method`, `provider` | | `afterSignUp` | After an account is created | `user`, `method`, `provider` | | `afterSignIn` | After a session is created, including the first one after sign-up | `user`, `method`, `provider`, `newUser` | | `afterSignOut` | After a user signs out | `userId` | | `afterEmailVerified` | Once an address is verified, including accounts created already verified | `user` | | `afterPasswordReset` | After a password is reset through the email link | `user` | | `afterPasswordChange` | After a signed-in user changes or adds a password | `user`, `kind` (`changed` or `set`) | | `afterIdentityLinked` | After a Google, Apple, or GitHub account is linked, including on sign-up | `user`, `provider`, `email` | Every event also has an `id`, unique per event, an `occurredAt` timestamp, and the client's `ip` when it is known. `user` has the same shape as [`/me`](https://docs.meetploy.com/auth#endpoints) returns. `method` is one of `password`, `oauth`, `magic_link`, `email_code`, or `passkey`; `provider` is `google`, `apple`, or `github` for `oauth` and `null` otherwise. Hooks receive `(event, env, ctx)`, like the other handlers. Types for every event are exported from `@meetploy/types`. ### When `beforeSignUp` runs `beforeSignUp` runs right before the account is created, so it always sees the final email and metadata: | Method | Runs when | | --------------------- | ----------------------------------------------------------- | | Password | The sign-up request arrives | | Google, Apple, GitHub | The provider sends the user back, for a new account | | Sign-in link or code | The link or code is used, for an address without an account | | Passkey | The passkey ceremony starts, before the browser prompt | A sign-in link or code for a new address is still sent; refusing the sign-up in `beforeSignUp` stops the account from being created when it is used. `beforeSignIn` does not run for the session that follows a sign-up, since `beforeSignUp` already approved it. For password and passkey sign-in, it only runs after the credential checked out, so it never sees failed attempts. ## Refuse a sign-up or sign-in Return `{ allow: false }` from a before hook, optionally with a `message` for the user. Returning `false` works too. Returning nothing allows the action. ```typescript auth: { async beforeSignUp(event, env) { if (!event.ip) { return; } await env.DB.prepare("INSERT INTO signup_attempts (ip) VALUES (?)") .bind(event.ip) .run(); const recent = await env.DB.prepare( "SELECT COUNT(*) AS n FROM signup_attempts WHERE ip = ? AND created_at > datetime('now', '-1 hour')", ) .bind(event.ip) .first<{ n: number }>(); if ((recent?.n ?? 0) > 5) { return { allow: false, message: "Too many sign-ups. Try again later." }; } }, async beforeSignIn(event, env) { const suspension = await env.DB.prepare("SELECT user_id FROM suspended_users WHERE user_id = ?") .bind(event.user.id) .first(); if (suspension) { return { allow: false, message: "This account is suspended." }; } }, }, ``` Keep suspension, roles, and paid entitlements in server-owned tables, not user metadata. Metadata originates from sign-up input and is returned to the user; never store secrets there or treat it as trusted authorization state. The example assumes your app owns the `signup_attempts` and `suspended_users` tables. A refused request fails with `403` and code `signup_blocked` or `signin_blocked`. JSON requests, `SignInForm`, and `SignUpForm` show your message. Redirect flows (social sign-in and sign-in links opened from email) add `?ploy_auth_error=signup_blocked` or `signin_blocked` and show a generic message, because the error travels in the URL. ## Change the new account Return `{ metadata }` from `beforeSignUp` to create the account with different metadata. It replaces the metadata entirely, so spread `event.metadata` to keep what the user sent. It must be an object of at most 1 KiB of UTF-8 JSON, or `null`. Hook responses are capped at 16 KiB; oversized or malformed before-hook responses fail closed. ```typescript beforeSignUp(event) { return { metadata: { ...event.metadata, name: event.metadata?.name ?? event.email.split("@")[0], signedUpWith: event.method, }, }; }, ``` ## Timeouts and failures Before hooks fail closed. If `beforeSignUp` or `beforeSignIn` throws, returns something invalid, or does not answer within 5 seconds, the sign-up or sign-in fails with `503` and code `hook_failed`, and the user sees "Sign-in is temporarily unavailable." A check that silently passed while your code was broken would let in exactly the users it is meant to stop. After hooks start in the background after the corresponding database operation; the auth response does not wait for delivery. Each attempt gets 10 seconds; a hook that throws, times out, or cannot be reached is retried twice, after 2 and 10 seconds. Retries carry the same event `id`. Errors your hooks throw appear in the deployment's logs. Delivery is **best effort, not durable**: events and retries are held in memory, not persisted in an outbox. A service restart can lose them, and delivery stops after the final failed attempt. Different events can run concurrently and arrive out of order. Do not use these notifications as the sole record for billing, access control, or required provisioning; reconcile against your auth database. For work you successfully receive, enqueue it in a [queue](https://docs.meetploy.com/queues) for durable processing. Use `event.id` as an idempotency key at the destination. A timeout cancels the HTTP call but cannot roll back work already performed by your hook, so a retry can overlap or repeat side effects. A before-hook timeout likewise does not undo its external side effects. Hook events contain public user fields and event metadata, not passwords, password hashes, session cookies, or provider tokens. Do not put credentials in user metadata or in refusal messages. Refusal messages are limited to 300 characters and are visible to the user. Keep before hooks fast: they run while the user waits. Move slow work, like calling a CRM, to an after hook or a [queue](https://docs.meetploy.com/queues). ## Next.js Add `auth` to the default handler export in the same `ploy.ts` that holds your queue and cron handlers: ```typescript title="ploy.ts" import type { PloyHandler } from "@meetploy/types"; export default { auth: { async afterSignUp(event) { console.log("New user", event.user.email); }, }, } satisfies PloyHandler; ``` ## `@meetploy/start` Register the hooks with `.auth()`: ```typescript import { ploy } from "@meetploy/start"; export default ploy() .auth({ beforeSignUp: (event) => event.email.endsWith("@example.com") ? undefined : { allow: false }, }) .build(); ``` ## Self-hosted deployment prerequisites Before enabling hooks, configure the **internal auth service** with `HANDLER_URL` pointing to the handler's **trusted internal socket** (port `8081` by default), not its public listener on `8080`. Allow the internal service to reach that socket through your network policies. Never expose the trusted socket to public traffic or customer workers. The split Compose files supply this URL; separate deployments must provide it explicitly, otherwise the development fallback is `http://localhost:8081`. For pod affinity, optionally set `HANDLER_HEADLESS_HOST` and `HANDLER_INTERNAL_PORT` on the internal service, and allow connections to the discovered handler pods. Set `CUSTOM_DOMAIN` consistently with the handler so server-side calls without a browser origin resolve the correct host. Missing connectivity makes before hooks fail closed with `hook_failed`; do not enable hooks until it is in place. See [self-hosting](https://docs.meetploy.com/self-host#auth-hook-connectivity). ## What does not run hooks * Users [imported](https://docs.meetploy.com/auth/migrate) from another provider. * Changes made directly to the auth tables in your database, including deleting users. * Reading or caching an existing session, renewing its expiry, or synchronizing its cookies; see [sessions](https://docs.meetploy.com/auth/sessions). These invoke neither `beforeSignIn` nor `afterSignIn`. * Refreshing provider access tokens with [`getProviderToken()`](https://docs.meetploy.com/auth/social#call-the-provider-api). # Hosted pages URL: https://docs.meetploy.com/auth/hosted-pages # Hosted pages Every project with auth enabled gets complete sign-in and sign-up pages at: ``` https:///_ploy/auth/sign-in https:///_ploy/auth/sign-up ``` They work with any framework, including static sites, because they need no package and no JavaScript in your app. They run on your own domain, so there is no redirect to a third-party login domain and the session cookie is set directly for your app. ## Use them Link to the page with the path to return to after sign-in: ```html Sign in ``` After a successful sign-in or sign-up the user lands on `redirectTo` with a `ploy_session` cookie. Users who are already signed in are sent straight to `redirectTo`. To reconnect a provider or approve [additional scopes](https://docs.meetploy.com/auth/social#request-additional-scopes), navigate directly to `/_ploy/auth/oauth/?redirectTo=` instead of the hosted sign-in page. Provider access tokens remain [server-only](https://docs.meetploy.com/auth/social#call-the-provider-api). `redirectTo` accepts a path or a URL on your app's origin. With [shared sessions](https://docs.meetploy.com/auth/subdomains), it also accepts sibling origins on the same scheme and port. Anything else falls back to `/`. For sign-in hosted on another subdomain, send an absolute return URL to your app. To sign out, `POST` to `/_ploy/auth/signout`. ## What they show The pages follow your project's [sign-in methods](https://docs.meetploy.com/auth#configure-sign-in-methods): Google, Apple, and GitHub buttons, passkeys, the email and password form, and **Email me a sign-in link** or **Email me a sign-in code**, each only when enabled. **Require name** adds a name field to sign-up, and when sign-ups are off the sign-up page says so. The heading shows your project name. Pages follow the visitor's light or dark system preference. If a social sign-in fails, the user returns to the page with the reason shown, for example when they cancel at the provider. ## Forgot password When password sign-in is on and auth emails are enabled, the sign-in page links to **Forgot password?**. Two more pages handle the reset: ``` https:///_ploy/auth/forgot-password?redirectTo=/dashboard https:///_ploy/auth/reset-password?token=... ``` The first asks for the email address and sends a reset link; the second, opened from that link, sets the new password and returns to sign-in. When [email verification is required](https://docs.meetploy.com/auth/emails#require-a-verified-email), sign-up tells the user to check their inbox and sign-in offers **Resend verification email**. See [Emails, sign-in links and passwords](https://docs.meetploy.com/auth/emails). ## Sign-in links When [sign-in links](https://docs.meetploy.com/auth/emails#sign-in-links) are on and auth emails are enabled, the sign-in page offers **Email me a sign-in link** next to the password form; without password sign-in it is the form's main button. The user enters their email, gets a link valid for 15 minutes, and opening it shows a confirmation page: ``` https:///_ploy/auth/magic-link/verify?token=... ``` Its **Continue as** button finishes the sign-in and returns to `redirectTo`. For a new address the link creates the account when sign-ups are allowed; with **Require name**, the sign-in page asks for the name first. ## Sign-in codes When [sign-in codes](https://docs.meetploy.com/auth/emails#sign-in-codes) are on, the sign-in and sign-up pages offer **Email me a sign-in code** (or **Email me a sign-in link** when links are on too, and the email then carries both). After the user enters their email, the page switches to a code field. Typing or pasting the 6-digit code signs the user in and returns to `redirectTo`; **Use a different email** goes back. ## Security * Every page is self-contained: no external scripts, styles, or fonts. * A strict Content Security Policy with a per-request nonce blocks injected scripts, and `frame-ancestors 'none'` prevents clickjacking. * Responses are `no-store`, so sign-in pages are never cached by a CDN. Want the forms inside your own layout instead? Use the [React components](https://docs.meetploy.com/auth/components), which show the same methods. ## With Next.js `protect()` and `authMiddleware` from [`@meetploy/nextjs`](https://docs.meetploy.com/auth/nextjs) redirect signed-out users to the hosted sign-in page by default. ## Lifecycle hooks Hosted forms invoke the same [auth lifecycle hooks](https://docs.meetploy.com/auth/hooks) as custom UIs. JSON password/passkey/email-code flows return before-hook errors with `403` (refused) or `503` (failed); magic-link and OAuth browser callbacks redirect with `ploy_auth_error`. Messages render as text, not HTML. ## Local development `ploy dev` serves the same pages from the local emulator. With Next.js and `initPloyForDev()`, the helpers point at the emulator automatically. Verification, sign-in link and code, and reset emails land in the dev dashboard under **Auth → Emails**. # Authentication URL: https://docs.meetploy.com/auth # Authentication Ploy Auth gives your app its own user accounts and sessions without running an auth server. Users are stored in one of your [databases](https://docs.meetploy.com/databases), and Ploy serves the sign-in endpoints on your app's own domain under `/_ploy/auth/*`. Your application tables can share that database and reference `ploy_users(id)` with real foreign keys; see [sharing the auth database](https://docs.meetploy.com/auth/users#same-database-foreign-keys-and-joins). Users can sign in with: | Method | Default | Configure in | | ------------------------- | ------- | ------------------------------------------------------ | | Email and password | On | Dashboard → **Auth** → **Sign-in methods** | | Sign-in link (magic link) | Off | Dashboard → **Auth** → **Sign-in methods**, with email | | Sign-in code (email code) | Off | Dashboard → **Auth** → **Sign-in methods**, with email | | Passkeys | Off | Dashboard → **Auth** → **Sign-in methods** | | Google | Off | Dashboard, with your Google OAuth client | | Apple | Off | Dashboard, with your Sign in with Apple key | | GitHub | Off | Dashboard, with your GitHub OAuth App | Every method can be turned on or off per project. See [Social sign-in](https://docs.meetploy.com/auth/social) and [Passkeys](https://docs.meetploy.com/auth/passkeys) for provider setup, [Emails, sign-in links and passwords](https://docs.meetploy.com/auth/emails) for the emails Ploy Auth sends, [Users and data](https://docs.meetploy.com/auth/users) for how accounts are stored and how to reference them from your own tables, and [Hooks](https://docs.meetploy.com/auth/hooks) to run your own code on sign-up, sign-in and other account events. ## Enable auth Add an `auth` binding to your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist auth: binding: AUTH_DB ``` On the next production deployment Ploy: 1. Finds the project's existing auth database or creates a new project-specific database and binds it to your worker as `AUTH_DB`. New projects do not share auth databases merely because they use the same binding name. 2. Creates the auth tables (`ploy_users`, `ploy_sessions`, `ploy_identities`, `ploy_passkeys`, `ploy_tokens`) in that database. 3. Generates a per-project secret for signing session tokens. It is encrypted at rest and never exposed to your code. 4. Serves the auth endpoints at `/_ploy/auth/*` and adds the `PLOY_AUTH` binding for server-side checks. Auth becomes available only after its database schema is ready. New production setups start with sign-up closed. Enable **Allow sign-ups** in the dashboard, or explicitly seed the initial settings in `ploy.yaml`: ```yaml auth: binding: AUTH_DB allow_signups: true require_email_verification: true ``` Email verification is required by default for new setups; set `require_email_verification: false` to opt out. These options only seed a new setup. Redeploying does not overwrite settings you changed in the dashboard. Requiring email verification also needs [configured auth email](https://docs.meetploy.com/auth/emails). Preview deployments use the project's production auth database, users, sessions, and sign-in settings by default. Only trusted repository branches may deploy; opening a pull request from a fork does not deploy its code. Owners and admins can turn off **Enable on previews** under **Auth → Settings**. Auth endpoints enforce the setting on each request; redeploy previews to update their database bindings. Preview deployments never provision auth or apply database migrations. Deploy production first to initialize auth. OAuth providers still need callback URLs registered for each preview origin. ## Configure sign-in methods Open **Auth** in the dashboard and select your project. The **Settings** tab has: | Setting | Description | | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Email and password | Allow sign-up and sign-in with a password. | | Magic link | Allow sign-in, and sign-up when allowed, with a one-time link sent by email. Needs email enabled for the organization. See [Sign-in links](https://docs.meetploy.com/auth/emails#sign-in-links). | | Email code | Allow sign-in, and sign-up when allowed, with a 6-digit code sent by email. Needs email enabled for the organization. See [Sign-in codes](https://docs.meetploy.com/auth/emails#sign-in-codes). | | Passkeys | Allow sign-up and sign-in with Face ID, Touch ID, Windows Hello, or a security key. | | Google, Apple, GitHub | Enter the provider credentials, then turn the provider on. Each shows the callback URL to register. | | Allow sign-ups | When off, only existing users can sign in, with any method. | | Require name | Password and passkey sign-ups must send `metadata.name`. | | Allow plus addresses | Off by default: new accounts cannot use addresses with a `+` tag, such as `name+tag@example.com`. Existing accounts still sign in. | | Block disposable emails | On by default: new accounts cannot use disposable or forwarding email providers, such as `mailinator.com` or `duck.com`, or their subdomains. Existing accounts still sign in. | | Sessions | Session lifetime, extending active sessions, maximum session age, and the session cookie cache. See [Sessions](https://docs.meetploy.com/auth/sessions). | | Share sessions | Sign users in once across a verified custom domain's subdomains. Off by default. See [Sessions across subdomains](https://docs.meetploy.com/auth/subdomains). | | Emails | Require email verification, and the address auth emails are sent from. See [Emails, sign-in links and passwords](https://docs.meetploy.com/auth/emails). | | Email templates | Change the subject and text of each auth email. See [Email templates](https://docs.meetploy.com/auth/emails#email-templates). | Changes take effect on the next request; no redeploy is needed. At least one sign-in method must stay on. Only organization owners and admins can change sign-in methods or provider credentials. Provider secrets are write-only: the dashboard shows whether one is saved, never its value. ## Endpoints All endpoints are served on your app's domain at `/_ploy/auth/*` and use the `ploy_session` cookie. | Endpoint | Method | Description | | --------------------------- | --------- | ----------------------------------------------------------- | | `/config` | GET | Enabled sign-in methods, for building your own UI | | `/signup` | POST | Create an account with email and password | | `/signin` | POST | Sign in with email and password | | `/oauth/{provider}` | GET | Start Google, Apple, or GitHub sign-in (browser navigation) | | `/callback/{provider}` | GET, POST | Provider redirect target; register it with the provider | | `/passkey/register/options` | POST | Start passkey sign-up, or add a passkey when signed in | | `/passkey/register/verify` | POST | Finish passkey registration | | `/passkey/login/options` | POST | Start passkey sign-in | | `/passkey/login/verify` | POST | Finish passkey sign-in | | `/passkeys` | GET | List the signed-in user's passkeys | | `/passkeys/{id}` | DELETE | Remove one of the signed-in user's passkeys | | `/me` | GET | The current user | | `/signout` | POST | Revoke the current session | | `/email/verify/request` | POST | Send the verification email again | | `/email/verify` | GET | Verification link target | | `/email/verify/continue` | POST | Sign in the waiting sign-up browser once verified | | `/password/forgot` | POST | Email a password reset link | | `/password/reset` | POST | Set a new password with a reset token | | `/password/change` | POST | Change or set the signed-in user's password | | `/magic-link` | POST | Email a sign-in link | | `/magic-link/verify` | GET, POST | Sign-in link target: confirm page, then sign in | | `/email-code` | POST | Email a sign-in code | | `/email-code/verify` | POST | Sign in with an emailed code | See [Emails, sign-in links and passwords](https://docs.meetploy.com/auth/emails) for the email endpoints, password changes, and the hosted reset pages. Errors are JSON with a human-readable `error` and a stable `code`: ```json { "error": "Invalid credentials", "message": "Invalid credentials", "code": "invalid_credentials" } ``` ### Email and password ```typescript const response = await fetch("/_ploy/auth/signup", { method: "POST", credentials: "include", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: "user@example.com", password: "securepassword123", metadata: { name: "Jane Doe" }, // optional, up to 1 KB }), }); const { user } = await response.json(); // The ploy_session cookie is now set ``` `/signin` takes `{ email, password }` and returns `{ user }` the same way. Emails are trimmed and lowercased. When [email verification is required](https://docs.meetploy.com/auth/emails#require-a-verified-email), `/signup` responds with `{ user, emailVerificationRequired: true }` and no cookie, and `/signin` fails with code `email_not_verified` until the user opens the link in their verification email. ### Social sign-in Social sign-in is a full-page redirect. Send the browser to the provider endpoint with the page to return to: ```typescript window.location.href = "/_ploy/auth/oauth/google?redirectTo=" + encodeURIComponent("/dashboard"); ``` After the provider confirms the user, they land on `redirectTo` with a session cookie. If sign-in fails, they land there with a `ploy_auth_error` query parameter instead. `redirectTo` must be a path or a URL on the same origin, or a sibling origin on the same scheme and port when [sessions are shared](https://docs.meetploy.com/auth/subdomains); anything else falls back to `/`. ### Current user ```typescript const response = await fetch("/_ploy/auth/me", { credentials: "include" }); const { user } = await response.json(); ``` ```typescript interface PloyUser { id: string; email: string; emailVerified: boolean; hasPassword: boolean; // false for sign-in link, passkey, and social-only accounts createdAt: string; updatedAt: string; metadata: Record | null; } ``` ## Server-side authentication Your worker gets a `PLOY_AUTH` binding. Pass it the session token from the `ploy_session` cookie or an `Authorization: Bearer` header: ```typescript title="app/api/protected/route.ts" import { getPloyContext } from "@meetploy/nextjs"; export async function GET(request: Request) { const token = request.headers .get("Cookie") ?.match(/(?:^|;\s*)ploy_session=([^;]+)/)?.[1]; if (!token) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } const { env } = getPloyContext(); const user = await env.PLOY_AUTH.getUser(token); if (!user) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } return Response.json({ userId: user.id }); } ``` | Method | Returns | | ----------------------------------- | ------------------------------------------------------------------------------------------------------------ | | `getUser(token)` | The `PloyUser`, or `null` if the session is invalid | | `verifyToken(token)` | `true` if the session is valid and not revoked | | `getProviderToken(token, provider)` | The user's [social provider access token](https://docs.meetploy.com/auth/social#call-the-provider-api) for calling its API, or `null` | | `getSignInMethods(userIds)` | How each of up to 100 users can sign in: `password`, linked `providers`, and `passkeys` count | The session methods check the session against the database, so a signed-out or revoked session is rejected immediately. `getSignInMethods` takes user IDs instead of a session, for screens such as an admin user list. It answers for any user of the project, so it is server-only: requests through `/_ploy/auth` are refused. Check that the caller is allowed to see other users before calling it. Unknown IDs are left out of the result. ```typescript const [methods] = await env.PLOY_AUTH.getSignInMethods([user.id]); // { userId: "…", password: false, providers: ["github"], passkeys: 0 } ``` ## Sessions * Session tokens are signed with your project's secret and stored only as SHA-256 hashes, so a leaked database does not leak usable sessions. * The `ploy_session` cookie is `HttpOnly`, `SameSite=Lax`, and `Secure` on HTTPS. * Signing out revokes the session server-side, not just the cookie. Browser mutations reject untrusted `Origin` values with `403 invalid_origin`, including same-site sibling attacks. * Sessions last 7 days by default and are extended while the user stays active. See [Sessions](https://docs.meetploy.com/auth/sessions). * Sessions belong to the host that started them, unless you [share them across subdomains](https://docs.meetploy.com/auth/subdomains) of a verified custom domain. ## Built-in protection Ploy Auth applies these limits to every project. Requests over a limit get `429` with a `Retry-After` header. | Limit | Default | | --------------------------------------------------------------------------------------------- | ------------------------------------------ | | Sign-up, password sign-in and change, passkey verification, sign-in link use, OAuth callbacks | 30 per 5 minutes per IP | | OAuth starts and passkey challenges | 60 per 5 minutes per IP | | Password sign-in and change attempts for one email address | 10 per 15 minutes | | Verification, sign-in link, and reset emails | 3 per hour per address, 10 per hour per IP | | `/me` and `/signout` | 600 per minute per IP | Also built in: * **Password hashing** with scrypt. See [Users and data](https://docs.meetploy.com/auth/users#password-hashing). * **Uniform failures**: a wrong password and an unknown email return the same `401` and take the same time. * **CSRF-safe flows**: OAuth uses `state` and PKCE (Google, GitHub); passkey challenges are single-use. Both are bound to a short-lived signed cookie. * **No open redirects**: `redirectTo` is restricted to your app's origin, or its sibling subdomains when [sessions are shared](https://docs.meetploy.com/auth/subdomains). * **Account takeover protection** when linking providers by email. See [Social sign-in](https://docs.meetploy.com/auth/social#account-linking). ## Local development `ploy dev` runs the same endpoints against a local SQLite database. Email and password, sign-in links, and passkeys work on `localhost` out of the box; emails land in the dev dashboard's local inbox. To try social sign-in locally, put the provider credentials in your project's `.env`; see [Social sign-in](https://docs.meetploy.com/auth/social#local-development). ## Integrations Pick the level of control you need: | Option | Package | Best for | | ------------------------------------ | ---------------------- | ------------------------------------------------------------------------------------- | | [Hosted pages](https://docs.meetploy.com/auth/hosted-pages) | none | Any framework, static sites, the fastest start: link to `/_ploy/auth/sign-in` | | [React components](https://docs.meetploy.com/auth/components) | `@meetploy/auth-react` | Drop-in `SignInForm`, `SignUpForm`, `UserButton`, `UserProfile` inside your own pages | | [Next.js helpers](https://docs.meetploy.com/auth/nextjs) | `@meetploy/nextjs` | `currentUser()`, `protect()` and route middleware for the App Router | | [Endpoints](#endpoints) | none | Fully custom UI in any language | Starting fresh? Pick the **Next.js with Auth** template when creating a project in the dashboard, or copy one of the examples: [`nextjs-auth`](https://github.com/meetploy/ploy/tree/main/examples/nextjs-auth) and [`vite-react-auth`](https://github.com/meetploy/ploy/tree/main/examples/vite-react-auth). Coming from another provider? See [Migrating to Ploy Auth](https://docs.meetploy.com/auth/migrate). ## Next steps * [Social sign-in](https://docs.meetploy.com/auth/social) - Set up Google, Apple, and GitHub * [Passkeys](https://docs.meetploy.com/auth/passkeys) - Passwordless sign-in * [Sessions across subdomains](https://docs.meetploy.com/auth/subdomains) - One sign-in across your subdomains * [Users and data](https://docs.meetploy.com/auth/users) - Tables, hashing, and linking users to your data * [Hosted pages](https://docs.meetploy.com/auth/hosted-pages) - Sign-in without writing UI * [React components](https://docs.meetploy.com/auth/components) - Drop-in forms and account widgets * [Next.js helpers](https://docs.meetploy.com/auth/nextjs) - Server-side sessions and route protection # Migrating to Ploy Auth URL: https://docs.meetploy.com/auth/migrate # Migrating to Ploy Auth Ploy Auth covers the common auth building blocks with no separate service to run: users live in a database in your organization and sign-in runs on your app's domain. This page maps the concepts you know from Supabase Auth and Clerk. ## From Supabase Auth | Supabase | Ploy Auth | | --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `auth.users` table | `ploy_users` in your auth database ([Users and data](https://docs.meetploy.com/auth/users)) | | `auth.identities` | `ploy_identities` | | `supabase.auth.signUp({ email, password })` | `useAuth().signUp(email, password)` or `POST /_ploy/auth/signup` | | `supabase.auth.signInWithPassword(...)` | `useAuth().signIn(email, password)` or `POST /_ploy/auth/signin` | | `supabase.auth.signInWithOAuth({ provider })` | `useAuth().signInWithProvider("google")` or `/_ploy/auth/oauth/google` | | `supabase.auth.getUser()` on the server | `currentUser()` from `@meetploy/nextjs/auth`, or `env.PLOY_AUTH.getUser(token)` | | `@supabase/ssr` cookie clients and middleware | Built in: the `ploy_session` cookie is set by Ploy; use [`authMiddleware`](https://docs.meetploy.com/auth/nextjs#protect-routes-with-middleware) | | Auth UI blocks | [`SignInForm`, `SignUpForm`](https://docs.meetploy.com/auth/components) or the [hosted pages](https://docs.meetploy.com/auth/hosted-pages) | | `supabase.auth.signInWithOtp({ email })` | [Sign-in links](https://docs.meetploy.com/auth/emails#sign-in-links) or [sign-in codes](https://docs.meetploy.com/auth/emails#sign-in-codes) | | `supabase.auth.resetPasswordForEmail(...)` | [Password reset](https://docs.meetploy.com/auth/emails#password-reset) via **Forgot password?** or `/_ploy/auth/forgot-password` | | Provider settings in the Supabase dashboard | Dashboard → **Auth** → **Settings** | | `user_id uuid references auth.users` | `user_id TEXT REFERENCES ploy_users(id)` in the same database, or an ID reference in a separate database; see [Referencing users](https://docs.meetploy.com/auth/users#referencing-users-from-your-data) | **Differences to plan for:** * **No row-level security.** Access rules live in your server code: resolve the user with `currentUser()` or `PLOY_AUTH`, then filter by `user_id`. * **Foreign keys need the same database.** Store application tables alongside `ploy_users` for enforced references and SQL joins; see [sharing the auth database](https://docs.meetploy.com/auth/users#same-database-foreign-keys-and-joins). If you choose a separate database, reference users by ID and clean up application rows yourself when deleting a user. * **Auth emails need a sending domain.** Email verification, sign-in links and codes, and password reset are sent with Ploy Email; see [Emails, sign-in links and passwords](https://docs.meetploy.com/auth/emails). * **Not yet available:** phone sign-in and MFA. ## From Clerk | Clerk | Ploy Auth | | -------------------------------------------- | --------------------------------------------------------------------------------------- | | `` | `` from `@meetploy/auth-react` | | ``, `` | ``, `` | | `` | `` | | `` | `` | | ``, `` | ``, `` (client in `auth-react`, server in `@meetploy/nextjs/auth`) | | `appearance={{ variables }}` | `appearance={{ variables }}` ([Theming](https://docs.meetploy.com/auth/components#theming)) | | `clerkMiddleware()` + `createRouteMatcher()` | `authMiddleware({ protectedRoutes })` + `createRouteMatcher()` | | `auth()`, `currentUser()` | `auth()`, `currentUser()` from `@meetploy/nextjs/auth` | | `auth.protect()` | `protect()` | | Account Portal | [Hosted pages](https://docs.meetploy.com/auth/hosted-pages) on your own domain | | `user.publicMetadata` | `user.metadata`, set at sign-up | **Differences to plan for:** * **Middleware checks presence, not validity.** Clerk verifies sessions in middleware; Ploy's middleware only checks the cookie, so confirm the user with `currentUser()` or `protect()` in the page. * **Email verification is built in.** Ploy Auth sends verification, sign-in link or code, and password reset emails; **Require email verification** is on by default for new setups to keep unverified users out, and can be turned off under **Auth → Settings → Emails**. See [Emails, sign-in links and passwords](https://docs.meetploy.com/auth/emails). * **Not yet available:** organizations, MFA, phone verification, and impersonation. ## Moving existing users Organization owners and admins can import existing users, keeping the user IDs referenced by their application data. Deploy the production project with `auth` configured first, and wait for its auth database to be initialized. Create a private JSON file with a `users` array, then import it using the auth binding ID, project ID, or project name. The CLI requires the organization ID explicitly: ```bash ploy api auth list --org ploy api auth import my-project --org --file users.json ``` ```json title="users.json" { "users": [ { "id": "existing-user-id", "email": "person@example.com", "emailVerified": true, "identities": [ { "provider": "google", "providerUserId": "existing-google-subject", "email": "person@example.com", "emailVerified": true } ] } ] } ``` The API equivalent is `POST /orgs/{orgId}/auth-bindings/{authBindingId}/users/import` with the same JSON body. Each request accepts **1–100 users**, up to **3 social identities per user**, and at most **512 KiB**. A successful response is `{ "imported": 1 }`. Emails are trimmed and lowercased; IDs are preserved exactly. All users and identities in one request are inserted atomically. A conflicting user ID, email, or provider account returns `409` and leaves the whole batch unchanged; imports never overwrite or merge accounts. Larger migrations must be split into separate batches, which are not atomic as a group. ### Passwords from Better Auth Map Better Auth's `user.id`, `user.email`, and `user.emailVerified` directly. Read password hashes from the user's credential account, not from the user row. For social accounts, `providerUserId` is the source account's **`accountId`** (the provider's user ID), not its database row `id`; `provider` corresponds to `providerId`. Do not import credential accounts as social identities. Better Auth's default scrypt hashes can be reused without knowing users' passwords or asking them to reset. Include the exported `passwordHash` and **`"passwordHashFormat": "better-auth"`** for each password user. This format supports the native `<32-character hex salt>:<128-character hex key>` hash using scrypt `N=16384, r=16, p=1`, a 64-byte key, and NFKC-normalized passwords. Custom Better Auth hashing functions need their own compatibility review. Ploy preserves the salt as the original UTF-8 hex string and stores an explicitly tagged scrypt value. The original password continues to work. After the first successful password sign-in, Ploy upgrades the hash to its current [password hashing configuration](https://docs.meetploy.com/auth/users#password-hashing), without changing the user's ID. Raw colon-separated hashes require the explicit source format because older Ploy PBKDF2 hashes use the same syntax. Already-tagged `scrypt$N$r$p$salt$key` hashes use `"passwordHashFormat": "ploy"` (the default). Both the salt and key are unpadded base64url; the salt must be 16–64 bytes and the key 64 bytes. Import rejects invalid parameters, memory requirements above 64 MiB, and work above four times Ploy's default `N*r*p`. Verification uses the parameters encoded in each imported hash rather than treating all scrypt hashes as the same configuration. Other algorithms such as bcrypt are not supported by this import; use password reset or another sign-in method instead. ### Social sign-in and cutover Use the provider's stable user ID, not the source auth system's account-row ID. Enable the matching Google, Apple, or GitHub provider in Ploy with compatible OAuth application credentials; merely importing an identity does not enable that provider. Only mark emails verified if the source system actually verified them. If Google or GitHub OAuth credentials already exist in the same project's environment variables, an organization owner or admin can copy them server-side without exposing their secret values: ```text POST /orgs/{orgId}/auth-bindings/{authBindingId}/providers/google/import-env ``` ```json { "clientIdKey": "GOOGLE_CLIENT_ID", "clientSecretKey": "GOOGLE_CLIENT_SECRET" } ``` Use `github` in the path with `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` for GitHub. Only these exact provider-specific key pairs are accepted; unrelated secrets cannot be copied into the publicly readable client ID field. The source is the binding's own project environment, the same values used for production; callers cannot select another project or preview. The response only confirms the provider, enabled state, and that a secret is present. Existing provider rows are left unchanged unless `"overwrite": true` is explicitly included. Imported providers default to disabled; configure their callback URL for Ploy before enabling them in **Auth → Settings**, or explicitly include `"enabled": true` at cutover. Apple credentials must be configured separately. Imports do not copy active sessions, provider access or refresh tokens, granted scopes, passkeys, timestamps, or profile metadata. Configure [additional scopes](https://docs.meetploy.com/auth/social#request-additional-scopes) in the dashboard; imported identities return `null` from [`getProviderToken`](https://docs.meetploy.com/auth/social#call-the-provider-api) until users sign in with the provider again. Freeze source account changes during the final export/import to avoid missing users or password changes, test a small batch first, and retain a source backup for rollback. Importing users works while **Allow sign-ups** is off; that setting only controls new self-service registrations. Password hashes are sensitive credentials. Keep export files outside source control, restrict file permissions, and delete them securely when migration is complete. Never include real hashes in logs, issues, or support messages. # Next.js helpers URL: https://docs.meetploy.com/auth/nextjs # Next.js helpers `@meetploy/nextjs` includes server-side helpers for Ploy Auth in the App Router. Pair them with the [React components](https://docs.meetploy.com/auth/components) for the client side. ```bash pnpm add @meetploy/nextjs @meetploy/auth-react ``` ## Read the user on the server ```tsx title="app/dashboard/page.tsx" import { currentUser } from "@meetploy/nextjs/auth"; export default async function Dashboard() { const user = await currentUser(); return

{user ? `Welcome, ${user.email}` : "Not signed in"}

; } ``` | Helper | Returns | | ---------------------------- | ----------------------------------------------------------------------------------------- | | `currentUser()` | The `PloyUser`, or `null` | | `auth()` | `{ userId, user, token }`, all `null` when signed out | | `protect(options?)` | The `PloyUser`; redirects to sign-in when signed out | | `getSessionToken()` | The raw session token from the `ploy_session` cookie or an `Authorization: Bearer` header | | `signInUrl(returnTo?)` | URL of the [hosted sign-in page](https://docs.meetploy.com/auth/hosted-pages) | | `getProviderToken(provider)` | The user's [provider access token](https://docs.meetploy.com/auth/social#call-the-provider-api), or `null` | | ``, `` | Server Components that render children by session state | User and provider-token lookups check the session against the database through the `PLOY_AUTH` binding, so signed-out and revoked sessions are rejected immediately. User lookups are deduplicated per request. `getSessionToken` returns a session candidate, not an authentication guarantee. It checks shared-domain candidates through the binding when duplicate cookies exist, but can fall back to a raw host-only cookie or Bearer header. Use `auth()` or `currentUser()` for a verified session; `getProviderToken()` validates the selected user before requesting provider credentials. `getProviderToken` is server-only and returns a provider API credential, not a session token; never include it in props sent to Client Components or in browser responses. Configure [additional scopes](https://docs.meetploy.com/auth/social#request-additional-scopes) in the dashboard. ### Require a user ```tsx title="app/settings/page.tsx" import { protect } from "@meetploy/nextjs/auth"; export default async function Settings() { const user = await protect({ returnTo: "/settings" }); return

Signed in as {user.email}

; } ``` `protect()` redirects to `/_ploy/auth/sign-in?redirectTo=/settings`. Pass `signInUrl: "/login"` to use your own page. With [shared sessions](https://docs.meetploy.com/auth/subdomains), `signInUrl` can be an absolute sibling sign-in URL, such as `https://auth.example.com/_ploy/auth/sign-in`. `protect({ signInUrl, returnTo: "/settings" })` and `authMiddleware({ protectedRoutes, signInUrl })` make the return URL absolute so the user returns to this app. Server-side checks still use this project's `PLOY_AUTH` binding. ### Route Handlers and Server Actions ```typescript title="app/api/posts/route.ts" import { getPloyContext } from "@meetploy/nextjs"; import { auth } from "@meetploy/nextjs/auth"; export async function GET() { const { userId } = await auth(); if (!userId) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } const { env } = getPloyContext(); const { results } = await env.DB.prepare( "SELECT * FROM posts WHERE user_id = ?", ) .bind(userId) .all(); return Response.json({ posts: results }); } ``` ## Protect routes with middleware ```typescript title="middleware.ts" import { authMiddleware } from "@meetploy/nextjs/auth-middleware"; export default authMiddleware({ protectedRoutes: ["/dashboard", "/settings", /^\/admin/], }); export const config = { matcher: ["/((?!_next|_ploy|.*\\..*).*)"], }; ``` On Next.js 16, name the file `proxy.ts`. A string matches the path and everything below it; a RegExp is tested against the pathname. Signed-out visitors are redirected to the hosted sign-in page with `redirectTo` set to the page they asked for. Middleware only checks that a session cookie is present; it can't validate it, because the signing secret never leaves Ploy. Always confirm the user in the page or route with `currentUser()` or `protect()`. Server Components can't set cookies, so middleware also keeps [extended sessions](https://docs.meetploy.com/auth/sessions#extend-active-sessions) alive in the browser: when a session is due for a refresh, it calls `/_ploy/auth/me` once and passes the renewed `ploy_session` cookie on with the response. The `ploy_session_fresh` cookie avoids repeated checks until the next refresh deadline. The response also synchronizes the browser cookie if an earlier server-side binding call already extended the database session. Overlapping host-only/shared session or freshness cookies force a synchronization even when a freshness marker is present. Middleware forwards every `Set-Cookie` write and deletion separately, preserving its `Domain` scope. Pass `refreshSession: false` to turn it off, for example when your client code already calls `/_ploy/auth/me`. ## Lifecycle hooks Add `auth` to the default handler export in `ploy.ts` for [before/after auth hooks](https://docs.meetploy.com/auth/hooks#nextjs). These run for actual sign-up, sign-in, sign-out and other lifecycle changes. Reading or caching a session, extending its expiry, and refreshing provider credentials invoke neither `beforeSignIn` nor `afterSignIn`. Enable deployed hooks in the dashboard. ## Local development With `initPloyForDev()` in `next.config`, `ploy dev` provides the `PLOY_AUTH` binding and points the helpers and React components at the local emulator. See the [Next.js auth guide](https://docs.meetploy.com/start/auth) for the full setup. # Passkeys URL: https://docs.meetploy.com/auth/passkeys # Passkeys Passkeys replace passwords with a key pair stored on the user's device or in their password manager. Sign-in is a fingerprint, face scan, or device PIN, and there is nothing to phish or leak: Ploy stores only the public key. ## Enable passkeys Open **Auth** → **Settings** in the dashboard, turn on **Passkeys**, and save. No provider setup is needed. Passkeys can be the only sign-in method or sit alongside passwords and social sign-in. ## What users can do | Flow | How | | ---------------- | ---------------------------------------------------------------------------------------------------------- | | Sign up | Enter an email and create a passkey instead of a password. Requires **Allow sign-ups**. | | Sign in | Choose **Sign in with a passkey**; the browser offers the passkeys saved for your domain. No email needed. | | Add a passkey | A signed-in user (any method) registers a passkey for their account. | | Remove a passkey | A signed-in user deletes one of their passkeys. The last remaining sign-in method cannot be removed. | Passkey sign-up refuses an email that already has an account; the user signs in first and then adds a passkey. This stops anyone from attaching their passkey to someone else's account. ## With React `SignInForm` shows a passkey button and `SignUpForm` offers passkey sign-up when passkeys are on. For a custom UI or an account settings page, use `useAuth`: ```tsx "use client"; import { useAuth } from "@meetploy/auth-react"; export function PasskeySettings() { const { signInWithPasskey, addPasskey, listPasskeys, removePasskey } = useAuth(); return ( <> ); } ``` | Method | Description | | ------------------------------------- | ----------------------------------------------- | | `signInWithPasskey()` | Prompt for a saved passkey and sign in | | `signUpWithPasskey(email, metadata?)` | Create an account secured by a new passkey | | `addPasskey(name?)` | Register another passkey for the signed-in user | | `listPasskeys()` | The signed-in user's passkeys | | `removePasskey(id)` | Delete one of the signed-in user's passkeys | ## Domains A passkey belongs to the domain it was created on. A passkey made on `app.example.com` works only there, not on your default deployment URL or a preview URL. Point users at one canonical domain for sign-in. With [shared sessions](https://docs.meetploy.com/auth/subdomains) on, passkeys belong to the shared domain instead: a passkey created on `app.example.com` with `example.com` shared also works on `api.example.com`. Passkeys created before you change the setting keep their old domain. Before the change, have users add an alternative sign-in method; afterward, use it to sign in, add and test a new passkey, and only then remove the old one. Do not rely on an existing shared session: changing or disabling its domain rejects that session. See the [migration checklist](https://docs.meetploy.com/auth/subdomains#changing-the-setting) to avoid locking out passkey-only users. Passkey requests must come from your app's own pages: Ploy checks the browser's `Origin` against the domain serving `/_ploy/auth`, or sibling origins on the same scheme and port when shared sessions are enabled. ## Lifecycle hooks For new accounts, [`beforeSignUp`](https://docs.meetploy.com/auth/hooks) runs before registration options are issued; `afterSignUp` and `afterSignIn` follow successful verification. A passkey login calls `beforeSignIn` only after the credential verifies. Adding a key to an already signed-in account does not create a session or emit sign-up/sign-in hooks. ## Local development Browsers allow passkeys on `localhost` without HTTPS, so `ploy dev` supports passkeys out of the box. Passkeys created locally only work locally. # React with Vite URL: https://docs.meetploy.com/auth/react # React with Vite This guide adds Ploy Auth to a React app built with Vite: drop-in forms in the browser and a worker route that knows who is signed in. The complete code is in [`examples/vite-react-auth`](https://github.com/meetploy/ploy/tree/main/examples/vite-react-auth). ## 1. Configure the project ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist assets: binding: ASSETS not_found_handling: single-page-application run_worker_first: - /api/* - /_ploy/* auth: binding: AUTH_DB ``` `run_worker_first` sends `/_ploy/*` past the single-page fallback, so the [auth endpoints](https://docs.meetploy.com/auth#endpoints) and [hosted pages](https://docs.meetploy.com/auth/hosted-pages) are reachable during local development. ```bash pnpm add @meetploy/auth-react pnpm add -D @meetploy/cli @meetploy/vite ``` ```typescript title="vite.config.ts" import { ploy } from "@meetploy/vite"; import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [react(), ...ploy()], }); ``` ## 2. Wrap the app ```tsx title="src/main.tsx" import { AuthProvider } from "@meetploy/auth-react"; import { createRoot } from "react-dom/client"; import App from "./App"; createRoot(document.getElementById("root")!).render( , ); ``` ## 3. Show sign-in or the account ```tsx title="src/App.tsx" import { SignedIn, SignedOut, SignInForm, UserButton, UserProfile, } from "@meetploy/auth-react"; export default function App() { return (
); } ``` To host auth on a sibling subdomain, configure [shared sessions](https://docs.meetploy.com/auth/subdomains) first and pass `apiUrl="https://auth.example.com/_ploy/auth"` to `AuthProvider`. The forms show whatever sign-in methods are enabled for the project. See [React components](https://docs.meetploy.com/auth/components) for every component, prop, and theming option. ## 4. Protect a worker route The browser sends the `ploy_session` cookie with same-origin requests. Verify it in the worker with `env.PLOY_AUTH`: ```typescript title="worker/index.ts" export default { async fetch(request, env) { const url = new URL(request.url); if (url.pathname === "/api/profile") { const token = request.headers .get("Cookie") ?.match(/(?:^|;\s*)ploy_session=([^;]+)/)?.[1]; const user = token ? await env.PLOY_AUTH.getUser(token) : null; if (!user) { return Response.json({ error: "Unauthorized" }, { status: 401 }); } return Response.json({ userId: user.id }); } return new Response("Not found", { status: 404 }); }, } satisfies Ploy; ``` From React, call it with a plain `fetch("/api/profile")`. Run `ploy types` to add `PLOY_AUTH` to your generated `env.d.ts`. The binding extends due sessions in the database, but cannot renew browser cookies. `AuthProvider` checks `/_ploy/auth/me` on mount, not on a timer. For a long-lived single-page view, make another same-origin `/me` request before the idle lifetime ends to renew its cookie. See [Sessions](https://docs.meetploy.com/auth/sessions) for refresh intervals, limits, and revocation behavior. To call Google or GitHub APIs for the user, configure [additional scopes](https://docs.meetploy.com/auth/social#request-additional-scopes) and call `env.PLOY_AUTH.getProviderToken(sessionToken, provider)` inside the worker. Provider tokens are not exposed by `useAuth()`; return only the API data your UI needs. ## Server-side lifecycle hooks Add an `auth` property alongside `fetch` on your worker's default export; see [auth hooks](https://docs.meetploy.com/auth/hooks). If you use Ploy Start, register `.auth({ ... })` before `.build()` ([example](https://docs.meetploy.com/auth/hooks#meetploystart)). Hooks run on the server, not in `AuthProvider` or `useAuth()`. Deployed hooks require dashboard opt-in. ## 5. Run it locally ```bash pnpm ploy dev ``` `ploy dev` serves the auth endpoints and hosted pages on your app's own origin and provides `env.PLOY_AUTH`, backed by a local database. Password sign-in and passkeys work on `localhost`; add `PLOY_AUTH_*` credentials to `.env` to try [social sign-in](https://docs.meetploy.com/auth/social#local-development). Want to skip the forms entirely? Link to `/_ploy/auth/sign-in?redirectTo=/` and use the [hosted pages](https://docs.meetploy.com/auth/hosted-pages) instead. # Sessions URL: https://docs.meetploy.com/auth/sessions # Sessions Signing in creates a session and sets the `ploy_session` cookie. The session is checked against your auth database on every request, so signing out or revoking it takes effect immediately, unless you turn on the [cookie cache](#session-cookie-cache). * Session tokens are signed with your project's secret and stored only as SHA-256 hashes, so a leaked database does not leak usable sessions. * The `ploy_session` cookie is `HttpOnly`, `SameSite=Lax`, and `Secure` on HTTPS. * Signing out revokes the session server-side, not just the cookie. Changing or resetting a password signs out the user's other sessions. ## Settings Open **Auth** in the dashboard, select your project, and go to **Settings** → **Sign-ups and sessions**. Only organization owners and admins can change them. | Setting | Default | Description | | ---------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------- | | Session lifetime | 7 days | How long a session lasts after it was last extended, or after sign-in when sessions are not extended. 5 minutes to 90 days. | | Extend active sessions | On | Extend a session to the full lifetime again when it is used. | | Refresh interval | 24 hours | How long after the last extension a session is extended again. Must be shorter than the session lifetime. | | Maximum session age | 400 days | Sign users out this long after sign-in, however active. At least the session lifetime, at most 400 days. | | Session cookie cache | Off | Answer `/_ploy/auth/me` from a signed cookie for up to 10 minutes instead of reading the database. | The same settings are available with `ploy api auth update`: `--session-expiry`, `--session-update-age`, `--session-max-lifetime`, and `--session-cookie-cache`, all in seconds. A refresh interval of `0` keeps sessions at a fixed expiry; a maximum age of `none` removes the optional lower cap, not the 400-day signing-token limit. The API and CLI allow idle lifetimes from 300 to 7,776,000 seconds and positive refresh intervals of at least 1 second, strictly shorter than that lifetime. A configured maximum age must be from 3,600 to 34,560,000 seconds and at least the idle lifetime. The dashboard uses fractional days for lifetimes and fractional hours for refresh intervals. When an API or CLI update shortens the idle lifetime without specifying a refresh interval, an interval that would reach or exceed the new lifetime is adjusted to half that lifetime (up to 24 hours). Explicit invalid intervals are rejected. ## Extend active sessions With **Extend active sessions** on, users who keep using your app stay signed in. When a session is used and it was last extended more than the refresh interval ago, Ploy Auth moves its expiry to the session lifetime from now and sends the `ploy_session` cookie again with the new lifetime. With the defaults, a due renewal sets expiry to 7 days from that check. Daily session checks keep it alive until its signing token expires, at most 400 days after sign-in. Checks inside the 24-hour refresh interval do not move expiry, so the remaining time after the last check can be up to 24 hours shorter than the full 7-day lifetime. Expiry writes are throttled by the refresh interval rather than every request; overlapping requests may attempt the same renewal. Sessions are extended whenever the session is checked: * Browser requests to `/_ploy/auth/*`, such as `/me` from the [React components](https://docs.meetploy.com/auth/react), renew the cookie directly. * `PLOY_AUTH.getUser()` and `verifyToken()` extend the session in the database. They can't set cookies, so for apps that only read the session on the server, the [Next.js middleware](https://docs.meetploy.com/auth/nextjs#protect-routes-with-middleware) passes the renewed cookie on to the browser. * API clients that send `Authorization: Bearer` keep the same token; its session is extended in the database. Turn **Extend active sessions** off to stop further extensions. New sessions end one session lifetime after sign-in; existing sessions retain the expiry they already reached. Ploy Auth sets a `ploy_session_fresh` cookie next to `ploy_session` that expires when the session is next due for a refresh. Middleware uses it to avoid repeated `/_ploy/auth/me` checks until refresh is due. If older host-only cookies overlap a shared session, middleware synchronizes them even while a freshness marker is present. Renewing an existing session, serving `/me` from the signed cache, or refreshing provider credentials does not create a session and invokes neither `beforeSignIn` nor `afterSignIn`. Use [auth lifecycle hooks](https://docs.meetploy.com/auth/hooks) to observe actual sign-ins and new sessions, including the initial session after sign-up. ## Maximum session age The maximum session age caps how long extending can keep a session alive. A user who signs in on Monday with a maximum age of 30 days must sign in again 30 days later, even if they used the app every day. Without a maximum age, sessions can be extended for up to 400 days. Lowering the maximum age stops existing sessions from being extended past it, but does not shorten an expiry already stored in the database. Raising it cannot extend an existing signing token; sign in again to receive the longer limit. ### Existing sessions Sessions created before sliding sessions was enabled keep their original signing-token expiry, even if their database expiry is extended. They cannot gain the new 400-day limit without signing in again. Existing projects whose idle lifetime is 24 hours or less start with a refresh interval of half their idle lifetime, rather than the unusable 24-hour default. Local emulator settings are adjusted the same way. Changing the idle lifetime or refresh interval applies to subsequent database checks; it does not rewrite existing tokens or immediately revoke existing sessions. With [sessions across subdomains](https://docs.meetploy.com/auth/subdomains), refreshes preserve the token's signed cookie scope. Session, cache, and freshness cookies all use that scope. A host-only session remains host-only after sharing is enabled; sign in again to get a shared session. Disabling or changing a shared domain invalidates its signed sessions, including cached ones. ## Session cookie cache With the session cookie cache on, a successful `/_ploy/auth/me` sets a signed `ploy_session_data` cookie with the user for the cache duration. Until it expires, `/me` answers from that cookie without rereading the auth session or user rows, which makes frequent session checks from the browser cheaper and faster. A cached session is not checked against the database until the cache expires. Signing out on another device, changing the password elsewhere, or revoking the session takes up to the cache duration to take effect for a browser holding the cache. Signing out in that browser clears its cache immediately. Keep the duration short. Reducing it does not shorten an already issued cache cookie; disabling the cache makes subsequent requests check the database. The cache covers `/_ploy/auth/me` only. Shared-domain eligibility is still validated on every request, including cache hits; a revoked or changed domain does not get the cache's revocation grace period. Changing account data such as the password clears the cache in the browser that made the change. `PLOY_AUTH.getUser()`, `verifyToken()`, and every other endpoint always check the database. While a session is served from the cache it is not extended. The cache expires no later than the next refresh deadline or session expiry, so it cannot hide a due extension until the session has already expired. # Social sign-in URL: https://docs.meetploy.com/auth/social # Social sign-in Ploy Auth supports Google, Apple, and GitHub. You bring your own OAuth credentials, so the consent screen shows your app's name and users' accounts belong to you. ## Set up a provider 1. Create OAuth credentials with the provider (below). 2. Register the callback URL for every domain users sign in from: ``` https:///_ploy/auth/callback/ ``` The dashboard shows it for your project's production URL. Add the same path for each custom domain and any preview URL you want to sign in on. 3. In the dashboard, open **Auth** → **Settings**, enter the credentials under the provider, turn it on, and click **Save settings**. The provider appears in `GET /_ploy/auth/config` and in the `SignInForm` and `SignUpForm` components right away. ### Google 1. In Google Cloud Console, open **APIs & Services** → **Credentials** and create an **OAuth client ID** of type **Web application**. 2. Add the callback URL under **Authorized redirect URIs**. 3. Copy the **Client ID** and **Client secret** into Ploy. Ploy requests the `openid email profile` scopes and uses PKCE. To call Google APIs, add their scopes under [Additional scopes](#request-additional-scopes) and enable the APIs in Google Cloud Console. ### GitHub 1. In GitHub, open **Settings** → **Developer settings** → **OAuth Apps** → **New OAuth App**. 2. Set **Authorization callback URL** to the callback URL. 3. Generate a client secret and copy the **Client ID** and secret into Ploy. Ploy requests `read:user user:email` and uses the account's primary verified email. GitHub accounts without a verified email cannot sign in. To call the GitHub API with more access, such as `repo`, add the scopes under [Additional scopes](#request-additional-scopes). ### Apple Sign in with Apple needs a paid Apple Developer account. 1. Under **Certificates, Identifiers & Profiles**, create an **App ID** with **Sign in with Apple** enabled. 2. Create a **Services ID**, enable **Sign in with Apple**, and add your domain and the callback URL as a return URL. Apple requires HTTPS. 3. Under **Keys**, create a key with **Sign in with Apple** enabled and download the `.p8` file. 4. In Ploy, enter: | Field | Value | | ----------------- | -------------------------------------------------- | | Services ID | The Services ID identifier, e.g. `com.example.web` | | Team ID | Your 10-character Apple Developer team ID | | Key ID | The key's 10-character ID | | Private key (.p8) | The full contents of the `.p8` file | Ploy signs a short-lived client secret with the key on every sign-in, so there is nothing to rotate every six months. Apple sends the user's name only on their first sign-in; Ploy stores it in `metadata.name` when it creates the account. Users who choose **Hide My Email** get a private relay address. The private key and client secrets are encrypted at rest and never returned by the API. To rotate one, paste the new value and save. ## Start sign-in With `@meetploy/auth-react`, enabled providers show up in `SignInForm` and `SignUpForm` automatically, or call `signInWithProvider`: ```tsx const { signInWithProvider } = useAuth(); ; ``` Without React, navigate to the endpoint: ```typescript window.location.href = "/_ploy/auth/oauth/github?redirectTo=" + encodeURIComponent("/dashboard"); ``` ## Request additional scopes By default Ploy only asks for the scopes it needs to read the user's identity. To call a provider's API for the user, add scopes in the dashboard: open **Auth** → **Settings**, enter them under the provider in **Additional scopes**, separated by spaces, and click **Save settings**. | Provider | Always requested | Example additional scopes | | -------- | ---------------------- | ----------------------------------------------------------------------- | | GitHub | `read:user user:email` | `repo` for private repositories, `read:org` for organization membership | | Google | `openid email profile` | `https://www.googleapis.com/auth/calendar.readonly` | | Apple | `name email` | Apple offers no other scopes | Only organization owners and admins can change provider settings. Google and GitHub each accept up to 50 additional scope tokens, each at most 256 characters; whitespace, commas, quotes and backslashes cannot appear inside a token. Separate tokens with spaces in the dashboard. The identity scopes are always requested, and duplicates are removed. When you change the scopes, users who already signed in keep their current token until they sign in with the provider again; the provider then asks them to approve the new scopes. Until then, [`getProviderToken`](#call-the-provider-api) lists the scopes they have not approved in `missingScopes`. For Google, Ploy requests offline access and a fresh consent screen while additional scopes are set. This lets an existing grant issue a new refresh token too, including when a previously stored refresh token expired or was revoked. Google may require verification for sensitive or restricted scopes. Removing a configured scope does not revoke tokens or permissions already granted at the provider. Revoke the grant in the provider's account settings if access must be removed. ## Call the provider API When a user signs in with a provider, Ploy stores the provider's access token, refresh token, expiry, and granted scopes on the identity. On deployments, access and refresh tokens are encrypted with a key derived from the auth binding's signing secret, held by the platform rather than your worker or auth database. Ciphertexts are bound to the identity and token column. Direct database reads return ciphertext, not usable tokens. The key stays stable across redeploys and OAuth credential changes. Replacing the auth binding or its signing secret makes existing encrypted tokens unreadable; users must sign in again. Your server code and anyone with write access to the auth database remain trusted: encryption is not a substitute for restricting database access. Read the signed-in user's token in server code. With Next.js: ```typescript title="app/api/repos/route.ts" import { getProviderToken } from "@meetploy/nextjs/auth"; export async function GET() { const github = await getProviderToken("github"); if (!github || github.missingScopes.length > 0) { return Response.json( { connect: "/_ploy/auth/oauth/github?redirectTo=/repos" }, { status: 403 }, ); } const response = await fetch("https://api.github.com/user/repos", { headers: { Authorization: `Bearer ${github.accessToken}`, Accept: "application/vnd.github+json", "User-Agent": "my-app", }, }); return Response.json(await response.json()); } ``` In any worker, pass the session token to the `PLOY_AUTH` binding: ```typescript const github = await env.PLOY_AUTH.getProviderToken(sessionToken, "github"); ``` | Field | Value | | --------------- | ---------------------------------------------------------------------- | | `provider` | `google`, `apple` or `github` | | `accessToken` | Send it as `Authorization: Bearer ` to the provider's API | | `expiresAt` | ISO 8601 expiry, or `null` when the token does not expire | | `scopes` | The scopes the user granted | | `missingScopes` | Additional scopes you configured that the user has not approved yet | When the access token expires within a minute, Ploy refreshes it first if the provider issued a refresh token: Google with additional scopes, Apple, and GitHub Apps with expiring user tokens. GitHub OAuth App tokens have no scheduled expiry but can still be revoked. The refresh token itself is never returned. Concurrent refreshes are serialized through a short database lease, including across replicas; an older refresh cannot replace tokens from a newer sign-in. `missingScopes` compares configured scope names with the returned grant list. Providers can normalize scope names or return broader scopes; check provider documentation when interpreting the list. Network errors and temporary refresh contention throw instead of returning `null`; retry these failures rather than forcing the user to reconnect. `getProviderToken` returns `null` when the session is invalid, when the user has no stored token for the provider, or when the token expired and cannot be refreshed. Users who signed in before tokens were stored also get `null`. In each case, send the user to `/_ploy/auth/oauth/?redirectTo=`: a signed-in user is linked again, and Ploy stores the new token and scopes. Provider tokens are for server code only. They are available through the `PLOY_AUTH` binding and never through `/_ploy/auth/*` from the browser. Keep them on the server and call the provider from there. Unlinking an identity deletes its tokens; to revoke the grant itself, the user removes your app in the provider's account settings. ## Errors When sign-in does not complete, the user is sent back to `redirectTo` with a `ploy_auth_error` parameter. `useAuth().redirectError` exposes it and removes it from the URL. | Code | Meaning | | -------------------------- | ------------------------------------------------------------------------------------------ | | `access_denied` | The user cancelled at the provider | | `account_exists` | An account with this email exists and the provider did not verify the email | | `email_required` | The provider did not share a verified email address | | `signups_disabled` | No account exists for this identity and sign-ups are off | | `plus_address_not_allowed` | No account exists and the provider's email has a `+` tag the project refuses | | `email_domain_blocked` | No account exists and the provider's email is on a blocked disposable or forwarding domain | | `invalid_state` | The sign-in attempt expired (after 10 minutes) or was tampered with | | `provider_disabled` | The provider was turned off during sign-in | | `rate_limited` | Too many attempts from this IP | | `oauth_failed` | The provider rejected the code exchange | ## Account linking Ploy keeps one user per email address and links provider identities to it: 1. A returning identity (same provider and provider user ID) signs in to the user it is linked to, even if the email at the provider changed. 2. If the user is already signed in, the new identity is linked to their account. 3. If the provider reports a **verified** email that matches an existing user, the identity is linked to that user. 4. Otherwise a new user is created, if sign-ups are allowed. A provider email that is not verified is never linked to an existing account. **Takeover protection.** Ploy does not verify emails for password and passkey sign-ups, so anyone could register an address they don't own. When a verified provider identity links to such an unverified account, Ploy first removes its password and passkeys and revokes its sessions, then marks the email verified. The owner of the email keeps the account; whoever registered it without owning it loses access. ## Lifecycle hooks [Before hooks](https://docs.meetploy.com/auth/hooks) can reject a new social account (`beforeSignUp`) or a new session (`beforeSignIn`). A refused OAuth callback redirects with `ploy_auth_error=signup_blocked`, `signin_blocked`, or `hook_failed`; refusal text is not copied into the redirect URL. Social profile data and metadata are not authorization policy. ## Local development `ploy dev` reads provider credentials from your project's `.env`. A provider is enabled when all its variables are set: ```bash title=".env" PLOY_AUTH_GOOGLE_CLIENT_ID=... PLOY_AUTH_GOOGLE_CLIENT_SECRET=... PLOY_AUTH_GITHUB_CLIENT_ID=... PLOY_AUTH_GITHUB_CLIENT_SECRET=... PLOY_AUTH_APPLE_CLIENT_ID=... PLOY_AUTH_APPLE_TEAM_ID=... PLOY_AUTH_APPLE_KEY_ID=... PLOY_AUTH_APPLE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----" ``` Set additional scopes with `PLOY_AUTH_GITHUB_SCOPES` and `PLOY_AUTH_GOOGLE_SCOPES`, separated by spaces, e.g. `PLOY_AUTH_GITHUB_SCOPES="repo read:org"`. These are development environment settings, not `ploy.yaml` fields; deployed credentials and scopes are managed in the dashboard. `getProviderToken` works locally through the same server helpers. The local emulator uses a built-in development signing secret, not the platform-held production key. Do not treat local token ciphertext as protected from someone who can read the emulator database; use test accounts and keep local data private. Register `http://localhost:/_ploy/auth/callback/` with the provider, where `` is your dev server's port. Google and GitHub accept `localhost` callbacks; Apple only accepts HTTPS, so test Apple on a deployment. # Sessions across subdomains URL: https://docs.meetploy.com/auth/subdomains # Sessions across subdomains By default the `ploy_session` cookie belongs to the host that set it. A user who signs in on `app.example.com` is signed out on `api.example.com`, even when both serve the same project. ## Share sessions across subdomains To sign users in once for every subdomain of a domain: 1. Add the subdomains your project serves under **Settings** → **Domains** and verify them, for example `app.example.com` and `api.example.com`. 2. Open **Auth** → **Settings** in the dashboard, select the project, and under **Sign-ups and sessions** pick the domain in **Share sessions across subdomains**, for example `example.com`. 3. Save. Only organization owners and admins can change this setting. From then on, a sign-in on any host under the domain sets the session cookie for the whole domain, so the session is valid on `example.com` and all of its subdomains. ### Which domains are allowed The list offers verified project domains and their parents. Ploy checks eligibility when you save and on every auth request, including server-side binding checks: * It must be a verified custom domain that serves this project, or a parent of one. `example.com` is allowed once `app.example.com` is verified. * It must not cover a verified custom domain of another organization, including verified redirect-only domains. A pending, unverified registration alone does not establish ownership or invalidate your shared sessions. * Public suffixes such as `com`, `co.uk` or `github.io`, IP addresses, and Ploy's own domains (deployment and preview URLs and `ploy.email` domains) are never allowed. A session cookie on a shared domain would be readable by every other app on it. If the domain is removed, loses verification, or overlaps a verified domain of another organization, existing shared sessions and sign-in flows are rejected, including bearer-token and server-side binding checks. New sign-ins use host-only cookies. Hosts outside the configured domain, such as your default deployment URL, always set host-only cookies. Every host under the domain receives the session cookie and may make credentialed auth requests, including other projects or services on sibling subdomains. Verification of one subdomain does not prove control of every sibling: only share a parent domain whose entire subtree you control and trust. ### What changes with a shared domain | Area | Behavior | | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | Cookies | New sign-in flow cookies use the configured domain. Session, optional cache, and freshness cookies retain the session token's signed scope. Signing out revokes the session across subdomains and clears shared cookies plus host-only predecessors on the current host. | | Redirects | `redirectTo` may point to sibling origins with the same scheme and port as the auth host, not just the current host. | | Origin checks | Form posts and passkey requests are accepted from sibling origins under the domain, and from nothing broader. | | Cross-origin APIs | Pages on a sibling subdomain can call the auth endpoints with credentials, for example `app.example.com` calling `https://auth.example.com/_ploy/auth/me`. | | Passkeys | The passkey relying party becomes the shared domain, so one passkey works on every subdomain. See [Passkeys](https://docs.meetploy.com/auth/passkeys#domains). | ### Changing the setting New sign-ins use the new setting immediately. Existing host-only sessions are not promoted by [sliding-session refreshes](https://docs.meetploy.com/auth/sessions#existing-sessions); their session, cache, and freshness cookies stay host-only until users sign in again to share them. If a sibling still has an older host-only cookie, Ploy prefers the valid shared session and expires that host-only copy. Shared sessions and pending flows are rejected when their signed domain no longer matches an eligible configured domain. On a host under the former domain, reading a rejected session, signing in again, or signing out expires the old shared cookie. A server cannot remove cookies from every browser or from hosts outside its cookie scope. An old Domain cookie can still be delivered to a sibling server until the browser clears it or it expires, even though Ploy rejects it. Before transferring or relinquishing a domain or any sibling host, disable sharing, have users sign out, and allow the longest previously issued browser session-cookie lifetime (and the 10-minute flow-cookie lifetime) to elapse. Rejected shared sessions are not renewed; the signing-token ceiling does not extend an already issued browser cookie. Do not treat removing domain verification as browser-cookie erasure. Passkeys are bound to their relying party. Before changing the setting, enable an alternative sign-in method and have passkey-only users add a password or link an enabled social provider while their old session still works. After the change, they sign in with that method, add a new passkey under the new relying party, verify it works, and only then remove the old passkey. Changing or disabling an existing shared domain rejects its sessions, so an existing shared session alone is not a migration path. When first enabling sharing, existing host-only sessions remain usable. Plan this before enabling, changing, or disabling sharing. ## Serving auth from another subdomain Every host of the project serves `/_ploy/auth/*`. With a shared domain your app can also use the endpoints of a sibling host: ```tsx title="app/providers.tsx" {children} ``` For Next.js, pass that host's sign-in page as `signInUrl`, for example `authMiddleware({ protectedRoutes, signInUrl: "https://auth.example.com/_ploy/auth/sign-in" })` or `protect({ signInUrl, returnTo })`. Both send users back to the absolute URL of the page they came from. `currentUser()` reads the shared cookie and checks it with the `PLOY_AUTH` binding, so server-side checks work on every host the project serves. For cookie renewal in server-only apps, use the [Next.js auth middleware](https://docs.meetploy.com/auth/nextjs#protect-routes-with-middleware); the binding can extend the database session but cannot send cookies to the browser. Cached `/me` responses still enforce shared-domain eligibility. Sessions belong to the project that owns the auth binding. Another project on a sibling subdomain can call the endpoints above from the browser, but its own `PLOY_AUTH` binding does not accept this project's sessions. ## Local development This is a dashboard/API auth-binding setting, not a `ploy.yaml` key. For custom integrations, PATCH the organization auth binding with `cookieDomain: "example.com"` (or `null` to disable it); save-time validation and owner/admin permissions are the same as in the dashboard. `ploy dev` supports the same setting in the dev dashboard's auth settings. Locally the domain must be a `localhost` subdomain, for example `myapp.localhost`, which shares the session between `app.myapp.localhost` and `api.myapp.localhost`. Ports never separate cookies, so apps on different `localhost` ports already share a session without it. # Users and data URL: https://docs.meetploy.com/auth/users # Users and data Ploy Auth keeps your application's users, not Ploy dashboard accounts, in a regular SQLite [database](https://docs.meetploy.com/databases) in your organization. You can store your own tables in the same database and link them to users with foreign keys; a separate application database is optional. ## Where users live `auth.binding` in `ploy.yaml` names your application's auth database binding. New setups create a project-scoped database on the first production deploy. The same database is bound to your worker as `env.AUTH_DB` when the binding is `AUTH_DB`. Existing setups keep their database IDs. | Table | Contents | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `ploy_users` | One row per user: `id`, `email` (unique, lowercase), `email_verified`, `password_hash`, `metadata` (JSON), `created_at`, `updated_at` | | `ploy_sessions` | One row per session: `user_id`, SHA-256 `token_hash`, `expires_at`, `revoked` | | `ploy_identities` | Linked Google, Apple, and GitHub accounts: `user_id`, `provider`, `provider_user_id`, `email`, `email_verified`, `profile` (name and avatar), encrypted [provider tokens](https://docs.meetploy.com/auth/social#call-the-provider-api) and granted `scopes` | | `ploy_passkeys` | Registered passkeys: `user_id`, credential `id`, `public_key`, signature `counter`, `transports`, `name`, `last_used_at` | | `ploy_tokens` | Single-use [sign-in links](https://docs.meetploy.com/auth/emails#sign-in-links) and short-lived provider-refresh leases: `purpose`, SHA-256 `token_hash`, `email`, `user_id`, `expires_at`, `used_at` | `password_hash` is an empty string for users who only use social sign-in, passkeys, or sign-in links. Expired tokens are deleted automatically a day after they expire. Sessions, identities, and passkeys reference `ploy_users(id)` with `ON DELETE CASCADE`, so deleting a user removes those auth records. Your own tables follow the deletion policy you define. Ploy creates and upgrades these tables itself. Treat them as read-only from your code and use the [endpoints](https://docs.meetploy.com/auth#endpoints) to change accounts. Older setups may share an organization database between projects. Ploy does not move or split existing users automatically. Check each project's auth database before importing users; a shared database means shared users. ## Password hashing New passwords are hashed with **scrypt** (N = 214, r = 8, p = 5, 16-byte random salt, 64-byte key), one of the OWASP-recommended configurations. The stored value records its parameters: ```text scrypt$16384$8$5$$ ``` Accounts created before scrypt use PBKDF2-HMAC-SHA512 with 100,000 iterations (`:`). They keep working and are rehashed with scrypt on the user's next successful sign-in. The same upgrade path applies if the parameters are raised later. Passwords must be 8 to 128 characters. Unknown emails get the same response and the same default hashing cost as a wrong password for a current Ploy hash. Owners and admins can [import existing users](https://docs.meetploy.com/auth/migrate#moving-existing-users), including Better Auth scrypt password hashes and social identities, without changing their IDs. Better Auth's `N=16384, r=16, p=1` hashes use more memory but less total hashing work than Ploy's default; they are verified with their original parameters and upgraded after a successful password sign-in. Raw Better Auth hashes must be labeled explicitly during import because their `salt:hash` syntax is also used by Ploy's legacy PBKDF2 hashes. ## Referencing users from your data Use `ploy_users.id` as the user key in your own tables. Treat it as an opaque string: older accounts have short IDs and newer ones UUIDs. ### Same database: foreign keys and joins Use the auth database for your application tables when you want SQLite to enforce relationships to users. `env.AUTH_DB` is a normal database binding: it can query your own tables as well as read the auth tables. To apply your [migrations](https://docs.meetploy.com/databases#migrations) to that database, give it a second, non-auth binding: 1. Deploy production with `auth.binding: AUTH_DB` so Ploy initializes auth. 2. Open **Auth** in the dashboard, select your project, and copy its **Database** name. 3. Add a `db` binding using that exact database name, then deploy production again: ```yaml title="ploy.yaml" auth: binding: AUTH_DB db: DB: ``` Replace `` with the name from the dashboard. `AUTH_DB` and `DB` then point to the **same database**, not copies. New auth databases are project-scoped; do not assume the name is `auth_db`. An older setup may still use that name. Ploy creates or upgrades its auth tables before applying application migrations. The migration runner excludes the **auth binding name**, not every binding pointing at the same database, so it can apply your migrations through `DB`. With only one non-auth binding, use `migrations/`; with multiple non-auth bindings, use `migrations/DB/`. ```sql title="migrations/001_create_posts.sql" CREATE TABLE posts ( id INTEGER PRIMARY KEY, user_id TEXT NOT NULL REFERENCES ploy_users(id) ON DELETE CASCADE, title TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE INDEX posts_user_id ON posts(user_id); ``` The database service enables foreign-key enforcement. Inserts with an unknown `user_id` fail, and deleting a user deletes their posts in this example. Choose your own policy: `ON DELETE RESTRICT` blocks deletion while posts exist; `ON DELETE SET NULL` retains posts but requires a nullable `user_id`. Tables in the same database can also use SQL joins with `ploy_users`. The bindings are aliases, not permission boundaries: both can write every table in that database. Keep application writes and migrations limited to your own tables. Do not insert, update, delete, rename, or drop Ploy-managed auth tables; use the auth endpoints and dashboard for account changes. Exclude those tables from ORM-generated schema changes and leave `ploy_internal_db_migrations` to Ploy. A foreign key enforces existence, not authorization: resolve the signed-in user on the server and scope application queries to their ID. ### Separate databases: application-managed references Keep a separate database if you prefer that separation: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist auth: binding: AUTH_DB db: DB: app ``` ```sql title="migrations/001_create_posts.sql" CREATE TABLE posts ( id INTEGER PRIMARY KEY, user_id TEXT NOT NULL, title TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')) ); CREATE INDEX posts_user_id ON posts(user_id); ``` The tables live in different databases, so there is no SQL foreign key between them. Resolve the user from the session, then query with the ID: ```typescript const user = await env.PLOY_AUTH.getUser(token); if (!user) { return new Response("Unauthorized", { status: 401 }); } const { results } = await env.DB.prepare( "SELECT * FROM posts WHERE user_id = ? ORDER BY created_at DESC", ) .bind(user.id) .all(); ``` For admin views that need user details next to your data, read `ploy_users` through `env.AUTH_DB` and merge in code. Store app-specific profile data in your own tables keyed by `user_id`, or in `metadata` for a few small fields set at sign-up. When you delete a user, also delete or anonymize their rows in the separate application database. SQLite cannot enforce foreign keys or perform ordinary joins across these bindings, and auth deletion does not automatically clean up that database. ## Lifecycle hooks and user metadata [Lifecycle hooks](https://docs.meetploy.com/auth/hooks) can seed public user metadata at sign-up and notify your application of new users and sessions. Metadata can originate from client input; keep permissions, suspensions, and entitlement decisions in server-owned tables, and never put credentials or secrets in metadata. Notifications are best-effort, not a replacement for querying the auth database. ## Deployments and environments * **Previews share production auth by default**, including its database and users. Owners and admins can disable **Enable on previews** under **Auth → Settings**; see [preview access](https://docs.meetploy.com/auth#enable-auth). Preview deployments never provision auth or apply migrations. * **Settings apply instantly** to production auth. `auth.allow_signups` and `auth.require_email_verification` in `ploy.yaml` seed a new setup only; dashboard changes are preserved on redeploy. New setups default to sign-ups closed and email verification required. Existing settings, including verification opt-outs, stay unchanged. * **Your migrations** run on production deploys of the default branch, after Ploy has created the auth tables. * **Local development** with `ploy dev` keeps local users separate from production. Before applying migrations, it creates the production auth tables in each of the project's `db` databases and keeps their `ploy_users` rows in sync with local sign-ups, under the same IDs, so migrations and inserts referencing `ploy_users(id)` behave as in production. Like production, migrations run with foreign keys off and fail if they leave a violation. Read sessions through `PLOY_AUTH` or `/_ploy/auth/me`. # Email URL: https://docs.meetploy.com/email # Email Ploy can send transactional email for your projects, such as sign-up confirmations, password resets, and receipts. Every organization gets its own sending domain, and you can add your own domains so mail comes from addresses your users recognize. Email is sent by [Ploy Auth](https://docs.meetploy.com/auth/emails) and from your own worker code with an [email binding](https://docs.meetploy.com/email/workers). Workers can also [receive email](https://docs.meetploy.com/email/workers#receiving-email) sent to your domains. ## Request access Email sending is enabled per organization after a manual review. The review helps keep deliverability high for every organization that sends through Ploy. 1. Open the dashboard and go to **Email** in your organization's sidebar. 2. Describe what your projects will send and to whom, for example "account verification and password reset emails for users of our app". 3. Submit the request. The page shows **Under review** until we have looked at it. Only organization owners and admins can request access. If a request is not approved, the dashboard shows the reason and you can update your use case and request again. ## Your ploy.email domain Once access is approved, your organization gets a fixed sending domain of the form `.ploy.email`. Ploy manages its DNS records, so it works right away without any setup. This domain cannot be removed or renamed. ## Custom domains To send from your own domain, open **Email** in the dashboard and click **Add domain**. Use a subdomain such as `mail.example.com` rather than your apex domain. It keeps the reputation of your sending separate from your main domain. Sending email does not change your existing MX records, so the mail you receive keeps working. A custom domain needs these DNS records. The dashboard shows the exact names and values for your domain, each with a copy button: | Records | Type | Name | Purpose | | --------------- | ----- | ----------------------------- | ----------------------------------------------------------------------------------------- | | 3 DKIM records | CNAME | `._domainkey.` | Sign your messages so receivers can verify they come from you | | Bounce MX | MX | `bounce.` | Receive bounce notifications for your messages | | Bounce SPF | TXT | `bounce.` | Authorize Ploy to send on behalf of the bounce domain | | DMARC, optional | TXT | `_dmarc.` | Tell receivers how to handle unauthenticated mail; only suggested if your domain has none | The bounce records live on `bounce.`, a subdomain only used for bounces, so they never conflict with records on the domain itself. ### Domains on Ploy DNS If the domain's DNS is managed by Ploy (added under **Domains** in the dashboard with Ploy-managed DNS), Ploy adds all of these records for you. The dashboard marks the domain as **Records managed by Ploy DNS** and there is nothing to copy. That includes the DMARC record: Ploy adds `_dmarc.` with `v=DMARC1; p=none;`, a monitoring-only policy, when the zone has no DMARC record of its own. A DMARC record you already have is never replaced. To use a stricter policy, add your own `_dmarc` record before adding the email domain. ### Checking records DNS changes can take a while to show up. Ploy checks pending domains periodically, and you can click **Check now** on a domain at any time. The dashboard then shows the status of every record: * **OK**: the record is set up correctly. * **Missing**: no record was found at that name yet. * **Mismatch**: a record exists but has a different value. The dashboard lists the values it found and a hint on how to fix it. A domain is **Verified** once its required records are in place. You can remove a custom domain from the dashboard at any time; your projects can then no longer send from it. ## Limits Each project has a daily limit on the number of emails it can send. The current limit is shown on the **Email** page. If you need a higher limit, contact support and we can raise it. ## Bounces and complaints When a message bounces permanently or a recipient marks it as spam, Ploy adds the address to a suppression list and stops sending to it, which protects your domain's reputation. If bounce or complaint rates get too high, Ploy can pause sending for the organization. The **Email** page then explains why sending is paused; contact support to resume it. # Email in workers URL: https://docs.meetploy.com/email/workers # Email in workers Workers can send email through Ploy Email with a binding, and receive email sent to your domains in an `email()` handler. Ploy sends from your organization's verified domains and applies the same approval, suppression and limits as every other email your organization sends. Sending requires [email access](https://docs.meetploy.com/email#request-access) for your organization and a verified sending domain: your `.ploy.email` domain or a [custom domain](https://docs.meetploy.com/email#custom-domains). ## Configuration Add an `email` section to your `ploy.yaml`: ```yaml title="ploy.yaml" kind: worker build: pnpm build out: dist email: binding: EMAIL from: "Acme " allowed_from: - "*@acme.ploy.email" - "support@mail.acme.com" ``` | Key | Description | | -------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | | `binding` | Name of the binding in your worker's `env`, uppercase with underscores. Required when `from` or `allowed_from` is set. | | `from` | Default sender, `hello@acme.com` or `Acme `. Used when `send()` is called without `from`. | | `allowed_from` | Senders the worker may use: exact addresses or a whole domain as `*@domain`. Without it, any address on a verified domain of the organization works. | | `receive` | Addresses or whole domains (`*@domain`) whose email is delivered to the worker's `email()` handler. See [Receiving email](#receiving-email). | | `inbox` | `true` gives the project a private, receive-only inbox address. Works without email access. See [Inbox address](#inbox-address). | The settings are taken from your production deployment's `ploy.yaml`. Preview deployments use the same settings as production. Run [`ploy types`](https://docs.meetploy.com/cli/types) to add `EMAIL: EmailBinding` to your worker's `Env` type. ## Start a message from your own inbox `email.compose` is a separate, explicit opt-in. It lets an authorized mailbox start a fresh customer message from your support identity, without putting the private mailbox in the outgoing transport headers. It does not enable a public relay and does not change `relayReplies`. ```yaml title="ploy.yaml" email: binding: EMAIL from: "Acme Support " allowed_from: - "support@acme.com" receive: - "support@acme.com" compose: receive: "compose@acme.com" from: "Acme Support " senders: - "owner@example.com" # Explicit fixed decoder for providers that leave MIME headers unsigned: format: plain-utf8-quoted-printable ``` Deploy this configuration to turn it on. Remove `compose` and deploy to turn it off. The compose address is reserved by Ploy and is never delivered to the worker when enabled. Both addresses must belong to verified receiving domains on this project. The sending address must also be an exact `receive` entry, so customer replies continue into the normal support handler. Keep forwarding that address with `{ relayReplies: true }` to answer privately from your inbox. Compose a **new message**, not a reply or forward, in your normal mail app: ```text From: owner@example.com To: compose@acme.com Subject: [to:customer@example.net] Your account question Ploy-Compose: plain-utf8-quoted-printable Hello! Here is the information you requested. ``` With the fixed profile shown above, select **plain text** in your mail app, without attachments. The exact `Ploy-Compose: plain-utf8-quoted-printable` line must be the first body line, followed by one blank line. It is part of the signed payload and positively binds your intent to the fixed decoder; Ploy removes it from the customer message. Your app must send UTF-8 quoted-printable text. HTML, multipart, attachments, contradictory MIME and invalid encoded text are refused. Ploy never uses unsigned headers to choose a decoder. Omit `format` for the default signed-MIME profile, which can preserve HTML and attachments but requires every copied MIME header to be covered by valid DKIM; it does not use the plain-text prelude. Providers such as Proton commonly leave MIME headers unsigned, so use the explicit fixed profile instead of weakening sender authentication. Use exactly one bare destination in the subject instruction; no display names, Cc, Bcc, commas or multiple recipients. The actual `To` header must contain only the compose mailbox, without a +tag or a list/group. A normal, unambiguous display name added by your mail app is accepted. The subject after the instruction is 1–500 printable ASCII characters; Unicode is supported in the body, not the subject instruction. The customer sees `Your account question`, not the instruction, and receives a new message from `Acme Support `. ### Sender authentication and safety * Only 1–10 explicitly listed, exact sender mailboxes can compose. Wildcards and automatic authorization of a forwarding destination are not supported. * Ploy cryptographically verifies DKIM on the stored raw message. Its signing domain must exactly match the allowed mailbox domain (strict DMARC DKIM alignment). A forged `From`, SPF alone, or supplied `Authentication-Results` never authorizes a send. RSA keys must be at least 2048 bits; SHA-1 is refused. * The valid signature must cover `From`, `To`, `Subject`, `Date`, `Message-ID`, every copied MIME header, and the entire body, without DKIM `l=` truncation. The default profile requires the sender mail service to sign MIME headers. The fixed plain profile copies none: its interpretation comes from trusted config and the authenticated body prelude, never unsigned input metadata. * Messages must be under 1 MiB, less than one hour old (five minutes of forward clock skew is allowed), and manually composed. Replies, list mail, automated reports, copies, duplicate semantic headers and malformed instructions are refused. Owner, support, compose, private relay and bounce-handler destinations are not permitted. Normal organization sending approval, suppression and recipient limits still apply, plus a separate 25-message/project/UTC-day cap. * Each authenticated sender/Message-ID pair has a durable dispatch claim. Retries and duplicate deliveries cannot send it again or consume extra quota. An uncertain send is never automatically retried; inspect the project email history before composing a new message with a new Message-ID. Rejections are visible in email history; no automatic rejection email is sent. Ploy rebuilds the outgoing envelope and headers: public From and Reply-To, one customer recipient, a new Date and Message-ID, the clean subject, and necessary MIME headers only. Private routing, original identity, DKIM, Received, Sender, Reply-To, threading, authentication and X-headers are not carried across. **The body and attachments are user-provided content**, including signatures, quoted text, names, tracking links and attached-message metadata. Review them before sending; transport privacy does not redact that content. Delivery requires recipient-side confirmation, not merely API/SES acceptance. ## Sending email Call `send()` on the binding: ```typescript title="src/index.ts" export default { async fetch(request: Request, env: Env) { const { id } = await env.EMAIL.send({ to: "jane@example.com", subject: "Your order has shipped", text: "Your order #1234 is on its way.", html: "

Your order #1234 is on its way.

", }); return Response.json({ id }); }, }; ``` `send()` resolves once Ploy has accepted the email for delivery, with its Ploy `id` and its `messageId`, the `Message-ID` header recipients see. A reply to the email carries that `messageId` in its `In-Reply-To` header; see [Conversations](#conversations). | Option | Type | Description | | --------- | -------------------- | ---------------------------------------------------------------------------------------------------------------------------- | | `to` | `string \| string[]` | Recipients. `to`, `cc` and `bcc` together hold at most 50 addresses. | | `cc` | `string \| string[]` | Optional copy recipients. | | `bcc` | `string \| string[]` | Optional blind copy recipients. | | `from` | `string` | Sender. Defaults to `email.from`. Must be on a verified domain and allowed by `allowed_from`. | | `replyTo` | `string` | Optional Reply-To address. | | `subject` | `string` | Subject line, required. | | `text` | `string` | Plain-text body. Pass `text`, `html` or both. | | `html` | `string` | HTML body. | | `headers` | `object` | Extra headers: `In-Reply-To`, `References`, `List-Id`, `List-Unsubscribe`, `List-Unsubscribe-Post` and custom `X-*` headers. | An email goes out to all of its recipients or to none: if any recipient is refused, for example because it is on the suppression list, nothing is sent. Every recipient counts towards your project's [daily limit](https://docs.meetploy.com/email#limits). ## Errors When Ploy refuses an email, `send()` throws an error with a `code`: ```typescript try { await env.EMAIL.send({ to, subject, text }); } catch (error) { if (error instanceof Error && "code" in error) { console.warn("Email refused:", error.code, error.message); } throw error; } ``` | Code | Meaning | | ------------------------ | --------------------------------------------------------------------------- | | `invalid_request` | The message is malformed, for example without a subject or body. | | `invalid_sender` | No sender was given and `email.from` is not set, or the address is invalid. | | `sender_not_allowed` | The sender is not covered by `email.allowed_from`. | | `invalid_recipient` | A recipient address is invalid. | | `too_many_recipients` | More than 50 recipients. | | `access_not_approved` | Email sending is not enabled for your organization. | | `domain_not_verified` | The sender's domain is not a verified domain of your organization. | | `recipient_suppressed` | A recipient bounced or marked earlier mail as spam. | | `quota_exceeded` | The project reached its daily limit. | | `recipient_rate_limited` | Too many emails to the same address within an hour. | | `send_failed` | The email could not be sent. Retrying later may work. | ## Receiving email List the addresses your worker receives email at under `email.receive`, and ```yaml title="ploy.yaml" email: binding: EMAIL receive: - "support@acme.ploy.email" - "*@in.acme.com" ``` ```typescript title="src/index.ts" export default { async email(message, env, ctx) { const subject = message.headers.get("subject") ?? ""; if (subject.toLowerCase().includes("unsubscribe")) { message.setReject("Unsubscribe requests are handled elsewhere"); return; } await message.forward("team@acme.com"); await message.reply({ text: "Thanks for your message, we'll get back to you soon.", }); }, } satisfies Ploy; ``` A pattern is either an exact address or a whole domain as `*@domain`. When both match, the exact address wins. An exact address also receives its `+tag` variants: `support@acme.ploy.email` receives `support+order-42@acme.ploy.email` too. Each address can belong to only one project of your organization; a deployment that claims an address another project already receives at fails with an error in the build logs. Like the other `email` settings, `receive` is taken from your production deployment. Email arrives at the project's production deployment. The `binding` key is only needed if the worker also calls `send()`. ### The message | Property | Description | | ----------------------------------- | ------------------------------------------------------------------------------------------------ | | `from` | The envelope sender. | | `to` | The address the email was received at. | | `headers` | The message headers as a `Headers` object. | | `raw` | The full message in MIME format, as a `ReadableStream`. | | `rawSize` | The size of the raw message in bytes. | | `setReject(reason)` | Marks the email as rejected. It shows as rejected in the dashboard; the sender is not notified. | | `forward(to, headers?, options?)` | Forwards the email. It is sent from the address it was received at, with the sender as Reply-To. | | `reply({ subject?, text?, html? })` | Replies to the sender from the address the email was received at, in the same thread. | `forward()` and `reply()` send email, so they need [email access](https://docs.meetploy.com/email#request-access) and count towards your daily limit like `send()`. Messages up to 25 MB are delivered; up to 10 MB can be forwarded. ### Conversations A customer's reply goes to the address your worker sent from (or its `replyTo`), so keep that address in `email.receive`: * **Replies to received email:** `reply()` sends from the address the email arrived at, threaded on the original. When the customer answers, the email arrives at the same address and your `email()` handler runs again. * **Email your worker starts:** send `from` an address in `email.receive`, or set `replyTo` to one. A deployment whose `email.from` does not receive email logs a warning, since replies to it would be dropped. To tell conversations apart, put an ID in a `+tag`. Sending from `support+order-42@acme.ploy.email` works whenever `support@acme.ploy.email` is allowed, and the customer's reply arrives with `message.to` set to the tagged address: ```typescript title="src/index.ts" export default { async fetch(request: Request, env: Env) { const { messageId } = await env.EMAIL.send({ from: "Acme Support ", to: "jane@example.com", subject: "About your order #42", text: "Your order is delayed by a day.", }); // Store messageId to match the reply's In-Reply-To header too. return Response.json({ messageId }); }, async email(message, env) { const tag = /\+([^@]+)@/.exec(message.to)?.[1]; // "order-42" const inReplyTo = message.headers.get("in-reply-to"); // Look up the conversation by tag or inReplyTo, then answer: await message.reply({ text: "Thanks, we're on it." }); }, } satisfies Ploy; ``` `send()` and `reply()` both return the email's `messageId`; to continue a thread with `send()`, pass the last one as `In-Reply-To` and `References` in `headers`. ### Reply from your own inbox A plain `forward()` sets the original sender as Reply-To, so answering the forward from your mail app sends the reply from your own address. To answer as the address the email arrived at instead, forward with `relayReplies`: ```typescript title="src/index.ts" export default { async email(message) { await message.forward("me@example.com", undefined, { relayReplies: true }); }, } satisfies Ploy; ``` The forward's From and Reply-To are then a private address next to the receiving one, like `support+ploy-3f9a0c27d1b84e6f5a20@acme.com`. When `me@example.com` replies to it, Ploy sends the reply to the original sender from `support@acme.com`, in the same thread. Your address is not shown to the original sender, but anything in the body of your reply is, such as your signature. * **Only the forward target can reply.** The reply must come from the address you forwarded to, and its domain must pass DMARC, or SPF for the From domain itself. Other email to the address is dropped. * **Nothing else follows the forward.** The forward is addressed to the forward target only and drops the original Cc. Both From and Reply-To use the private address, so Reply All does not copy the original receiving address back into your worker. Relayed replies go to the original sender alone. * **Automatic replies are not relayed**, such as out-of-office messages and bulk mail. * **The address expires** 30 days after it was created or last relayed a reply. Relayed replies never reach your `email()` handler. They show as **Relayed** on the **Email** page and count towards your daily limit like `send()`. The receiving address needs a domain that can send, so `relayReplies` does not work for an inbox address. Removing the receiving route, transferring the project to another organization or disabling the domain stops existing relays too. Addresses matching `+ploy-<20 hexadecimal characters>@` are reserved for relays, even under a wildcard route. The receiving address must not start with `+`, and its untagged local part must leave room for the 26-character relay tag within the 64-character local-part limit. ### Delivery Valid, routed email is delivered to the worker at least once. When the handler throws or the deployment cannot be reached, Ploy tries again after 30 seconds, 2 minutes and 10 minutes before marking the email as failed. Email classified as spam or containing a virus, and email to addresses no project receives at, is not delivered. The **Email** page in the dashboard lists received emails from the last 30 days with their status. ### Delivery failures With the SES provider, Ploy queues a standard delivery-failure report when an address has no receiving route (`5.1.1`), or delivery fails permanently after retries (`5.3.0`). The report goes to the original SMTP envelope sender, not the message's `From` or `Reply-To` address. It does not expose worker errors or configuration values. Ploy also alerts verified organization owners and admins on the first worker delivery failure, limited to one alert per project per hour. A later permanent bounce of a forwarded message marks the original delivery failed and can notify its sender too: the worker completing successfully does not mean the forward reached its destination. To prevent mail loops and forged-sender backscatter, failure reports require successful SPF and DMARC checks, clean spam/virus verdicts and complete, non-automated headers. Ploy never sends reports for spam, viruses, automated messages, explicit `setReject()` decisions, or unknown/unverified domains. Reports are rate-limited, subject to suppression rules, and expire after 24 hours. Ambiguous provider outcomes are not retried, preventing duplicate reports. SMTP-only providers do not generate these native reports. ### Inbox address For automations that only need to receive email, such as parsing invoices or feeding an agent, set `inbox: true`. Ploy gives the project a private address like `3f9a0c27d1b84e6f5a20@in.ploy.email` and delivers its email to the `email()` handler. No email access or domain is needed. ```yaml title="ploy.yaml" email: inbox: true ``` The address is listed in the build logs and on the **Email** page, and stays the same across deployments. It is random, so only senders you give it to can reach it. Removing `inbox` (or the whole `email` section) releases the address; turning it on again creates a new one. An inbox address only receives: `forward()` and `reply()` fail with `invalid_sender`. Each organization's inboxes receive up to 1,000 emails per day; further email is dropped. ### Your own domain Your `.ploy.email` domain receives email without any setup. To receive at a custom domain, first enable your organization's [email access](https://docs.meetploy.com/email#request-access), then add and verify the domain on the **Email** page and turn on **Receive email**. Once email access is enabled, new domains do not need individual approval: verification and DNS setup are handled through the dashboard. Receiving adds an MX record to the domain's records: | Type | Name | Value | Priority | | ---- | ---------- | -------------------------------------- | -------- | | MX | `` | `inbound-smtp.us-east-1.amazonaws.com` | 10 | On Ploy DNS the record is added for you. The MX record sends all of the domain's email to Ploy, so use a subdomain such as `in.acme.com` rather than a domain whose mailboxes you already use. Only verified domains with receiving enabled deliver email. Turning receiving off, removing a route, or suspending email access also stops queued deliveries that have not reached the worker yet. ## Local development Under [`ploy dev`](https://docs.meetploy.com/cli/dev), nothing is sent. `send()` checks the message against your `ploy.yaml` like in production, and every email lands in the local inbox: open the dev dashboard and go to **Email** to read it. To test your `email()` handler, use **Send test email** on the same page. The email is delivered to your local worker; its replies and forwards land in the local inbox. To test `relayReplies`, send a test email from the forward target to the Reply-To address shown on the forward: the relayed reply lands in the local inbox too. # Databases URL: https://docs.meetploy.com/databases # Databases Ploy supports SQLite databases for workers and applies project migrations automatically. Databases belong to your organization and persist across deployments; bindings using the same database name in that organization share its data. Use a database when your app needs relational data that outlives a request: users, orders, content, anything you would otherwise put in Postgres or MySQL. For simple key-value data, [State](https://docs.meetploy.com/workers/state) is lighter; for files, use [File Storage](https://docs.meetploy.com/workers/file-storage). This page covers the binding and its runtime API. For framework-specific setup, see the [Next.js database guide](https://docs.meetploy.com/nextjs/database) and the [Ploy Start database guide](https://docs.meetploy.com/start/database), which adds Drizzle ORM. ## Configuration Add a database binding in your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist db: DB: default ``` The key (`DB`) is the binding name available in your worker's `env`. The value (`default`) is the database identifier. Run `ploy types` to generate TypeScript types: ```typescript title="env.d.ts" import type { Database } from "@meetploy/types"; export interface Env { DB: Database; } ``` ## Sharing a database with Ploy Auth A separate database for application data is optional. You can create your own tables in the auth database and use foreign keys to `ploy_users(id)`, including joins and your chosen deletion policy. Bind the auth database under an additional, non-auth `db` binding to run your application migrations against it. Use its actual database name from **Auth** in the dashboard, not an assumed `auth_db` name. Ploy skips the auth binding name when selecting migration targets, but not the alias. See [Users and data](https://docs.meetploy.com/auth/users#same-database-foreign-keys-and-joins) for the setup, SQL example, and local-development limitation. Keep writes and migrations away from Ploy-managed auth tables; the aliases do not restrict which tables your code can modify. Separate databases cannot enforce foreign keys between application rows and auth users. ## Basic Example ```typescript title="src/index.ts" export default { async fetch(request, env) { // Assumes the users table exists from your migrations await env.DB.prepare("INSERT INTO users (name) VALUES (?)") .bind("Alice") .run(); // Query const { results } = await env.DB.prepare("SELECT * FROM users").all(); return Response.json({ users: results }); }, } satisfies Ploy; ``` ## Migrations Create project migrations in `migrations/`. Ploy runs them in filename order and tracks applied files in `ploy_internal_db_migrations` inside the same database. For a single DB binding, you can keep migrations at the root: ```text title="migrations/" migrations/ ├── 001_create_users.sql └── 20260403171410_add_posts.sql ``` Nested migration folders are also supported. Any `.sql` file in the folder is executed, and sibling files like `snapshot.json` are ignored: ```text title="migrations/" migrations/ └── 20260403171410_init/ ├── migration.sql └── snapshot.json ``` If your project uses multiple DB bindings, scope migrations by binding name: ```text title="migrations/" migrations/ ├── DB/ │ └── 20260403171410_init/ │ └── migration.sql └── ANALYTICS_DB/ └── 001_create_events.sql ``` Production deploys on the default branch apply pending migrations before the deployment is uploaded, and the applied files are logged in the build output. During local development, `ploy dev` applies project migrations on startup. Ploy reads migrations from your repository at the deployed commit, after checking that the commit is on the default branch. Commit your migration files: files that only exist in the build output (for example, generated by the build command) are not applied, and the build log lists them. Each migration runs in a transaction together with its bookkeeping row, and Ploy records a checksum of every applied file. Applied migrations are immutable: if an applied file changes, the deploy fails. Restore the original file and add a new migration for the change. To keep migrations somewhere else, set [`migrations`](https://docs.meetploy.com/platform/configuration#migrations) in `ploy.yaml` to a path relative to the config file: ```yaml title="deploy/kr/ploy.yaml" db: DB: kr_db migrations: ../../migrations ``` ## Query Methods ### all() - Get All Rows ```typescript const { results } = await env.DB.prepare("SELECT * FROM users").all(); ``` ### first() - Get First Row ```typescript const user = await env.DB.prepare("SELECT * FROM users WHERE id = ?") .bind(1) .first(); ``` ### run() - Execute Statement ```typescript const result = await env.DB.prepare("INSERT INTO users (name) VALUES (?)") .bind("Bob") .run(); console.log(result.meta.changes); // 1 console.log(result.meta.last_row_id); // 1 ``` ### exec() - Run Raw SQL ```typescript const result = await env.DB.exec(` CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY, title TEXT); CREATE INDEX IF NOT EXISTS idx_title ON posts(title); `); console.log(result.count); // number of statements executed ``` ### withSession() - Session Compatibility Ploy exposes `withSession()` so code that expects a session object can keep using `prepare()` and `batch()` unchanged. ```typescript const session = env.DB.withSession("first-primary"); const user = await session .prepare("SELECT * FROM users WHERE id = ?") .bind(1) .first(); ``` ## Result Metadata Every query resolves to a result object with a `meta` field describing what the statement did: ```typescript const result = await env.DB.prepare("UPDATE users SET name = ? WHERE id = ?") .bind("Bob", 1) .run(); result.meta; // { // duration: 0.42, // milliseconds spent executing the statement // rows_read: 0, // rows the statement read // rows_written: 1, // rows the statement wrote // changes: 1, // rows the statement affected // last_row_id: 1, // rowid of the last inserted row, 0 if none // changed_db: true // whether the statement modified the database // } ``` Use `changes` when you need the number of rows an `INSERT`, `UPDATE`, or `DELETE` affected — for example to confirm that a conditional update actually matched a row: ```typescript const { meta } = await env.DB.prepare( "UPDATE credits SET claimed = 1 WHERE id = ? AND claimed = 0", ) .bind(grantId) .run(); if (meta.changes === 0) { // Already claimed by another request — do not grant it twice. } ``` `rows_read` and `rows_written` are usage counters that drive billing, so treat them as metering data rather than as an affected-row count. ## TypeScript Support Add generics for type-safe queries: ```typescript interface User { id: number; name: string; } const users = await env.DB.prepare("SELECT * FROM users").all(); // users.results is User[] const user = await env.DB.prepare("SELECT * FROM users WHERE id = ?") .bind(1) .first(); // user is User | null ``` Always use prepared statements with `.bind()` to prevent SQL injection. ## Limits Every statement is checked before it runs, both in production and in `ploy dev`, so oversized queries fail the same way locally as they do once deployed: | Limit | Default | | ------------------------------ | ------- | | SQL text per statement | 100 KB | | Bound parameters per statement | 100 | | Statements per `batch()` | 100 | | SQL text per `exec()` script | 1 MB | | Statements per `exec()` script | 1000 | Exceeding a limit rejects the request before it reaches SQLite — a `batch()` that breaks a limit applies none of its statements. The rejection is thrown in your worker with the reason attached, for example `DB batch failed: Statement with 301 bound params exceeds DB_MAX_SQL_BOUND_PARAMS (100)`, so the offending call is identifiable from the error alone. `exec()` gets its own, roomier caps because migrations run as a single script holding many statements. Each statement inside the script is still held to the per-statement limits, and migrations are checked during `ploy dev` too, so an oversized migration fails locally rather than at deploy time. Self-hosted deployments can raise or lower each cap with the `DB_MAX_SQL_LENGTH_BYTES`, `DB_MAX_SQL_BOUND_PARAMS`, `DB_MAX_BATCH_STATEMENTS`, `DB_MAX_EXEC_LENGTH_BYTES`, and `DB_MAX_EXEC_STATEMENTS` environment variables. Set the same values for the emulator to mirror a tuned deployment during development. ## Next Steps * [Next.js database guide](https://docs.meetploy.com/nextjs/database) - Query the database from server components and route handlers * [Ploy Start database guide](https://docs.meetploy.com/start/database) - Use Drizzle ORM with Ploy Start * [Authentication](https://docs.meetploy.com/auth) - Store users in a database binding * [Workers](https://docs.meetploy.com/workers) - Learn about Ploy workers * [Queues](https://docs.meetploy.com/queues) - Add background job processing # ploy dev URL: https://docs.meetploy.com/cli/dev # ploy dev Start the local development server with hot reloading. `ploy dev` automatically detects whether your project is a **worker**, a **Next.js** app, or a **Cloudflare Vite** app and starts the appropriate development environment. For Cloudflare Vite projects, `ploy dev` starts the Vite dev server alongside the Ploy dashboard. See the [Vite](https://docs.meetploy.com/vite) guide for how the integration works and how it's configured. ```bash ploy dev [options] ``` ## Options | Flag | Description | Default | | --------------------------- | --------------------- | ------------- | | `-p, --port ` | Server port | `3000` | | `-h, --host ` | Server host | `localhost` | | `-c, --config ` | Path to `ploy.yaml` | auto-detected | | `--no-watch` | Disable file watching | watch enabled | | `-v, --verbose` | Verbose output | `false` | | `--dashboard-port ` | Dev dashboard port | `port + 1000` | ## Worker Projects For worker projects (`kind: worker` in `ploy.yaml`), `ploy dev` starts the full local emulator with all Ploy services available: * SQLite database (D1-compatible) * Message queues * Workflows * Cache * State * File storage * Auth * Scheduled jobs ```bash ploy dev # Worker running at http://localhost:3000 # Dashboard at http://localhost:4000 ``` The dev dashboard lets you inspect queued messages, workflow runs, database tables, and other runtime state while developing locally. All services run entirely locally — no cloud connection required during development. ### Custom Port ```bash ploy dev -p 8080 # Worker at http://localhost:8080 # Dashboard at http://localhost:9080 ``` ### Custom Dashboard Port ```bash ploy dev --dashboard-port 5000 # Worker at http://localhost:3000 # Dashboard at http://localhost:5000 ``` ### Watch Mode File watching is enabled by default. Changes to your worker source files trigger a hot reload. Disable it with `--no-watch`: ```bash ploy dev --no-watch ``` ## Next.js Projects For Next.js projects, `ploy dev` starts `next dev` alongside a Ploy mock server that provides all runtime bindings (database, queues, auth, etc.) to your Next.js app. **Auto-detection**: a project is considered Next.js if: 1. `ploy.yaml` has `kind: nextjs`, **or** 2. A `next.config.ts`, `next.config.js`, `next.config.mts`, or `next.config.mjs` file exists ```bash ploy dev # Next.js at http://localhost:3000 # Ploy dashboard http://localhost:4000 ``` The `PLOY_MOCK_SERVER_URL` environment variable is automatically set so that `@meetploy/nextjs` connects to the local mock server instead of the production API. ### Minimal Next.js ploy.yaml ```yaml title="ploy.yaml" kind: nextjs db: DB: default auth: binding: PLOY_AUTH ``` ## Verbose Output Use `-v` / `--verbose` to see detailed logs from the emulator and all runtime services: ```bash ploy dev -v ``` ## Project Setup Make sure your `package.json` includes a `types` script that calls `ploy types` so that type definitions stay in sync: ```json title="package.json" { "scripts": { "dev": "ploy dev", "types": "ploy types", "build": "ploy build" } } ``` # ploy git & ploy push URL: https://docs.meetploy.com/cli/git # `ploy git` and `ploy push` These commands work with projects that deploy from [Ploy Git](https://docs.meetploy.com/platform/ploy-git). They need you to be logged in (`ploy auth login`) or an API token in `PLOY_API_TOKEN`. ## Choosing the project Every command resolves the project in this order: 1. The `--project ` flag 2. The `PLOY_PROJECT_ID` environment variable 3. The [`project`](https://docs.meetploy.com/platform/configuration#project) key in `ploy.yaml` Run `ploy api project list` to find project IDs. Projects that deploy from GitHub are refused; push to GitHub instead. ## `ploy push` Pushes a branch to the project's repository with a one-off URL. Nothing is stored in your git config. ```bash ploy push [ref] [options] ``` | Option | Description | | ------------------------ | ------------------------------------------------- | | `[ref]` | Local branch or ref to push (default: current) | | `--project ` | Project ID | | `--ttl ` | Lifetime of the push URL (default `1h`) | | `--remote-branch ` | Branch name in the Ploy Git repository | | `--force` | Force-push, using `--force-with-lease` for safety | ```bash ploy push ploy push main --project proj123 ploy push feature/login --remote-branch preview ``` ## `ploy git remote` Mints a git remote URL for the project. Use `--add` to configure a remote you can push to with plain git. ```bash ploy git remote [options] ``` | Option | Description | | ------------------ | ----------------------------------------------------- | | `--project ` | Project ID | | `--ttl ` | How long the URL stays valid, e.g. `1h`, `24h`, `30d` | | `--add` | Add the remote, or update it if it already exists | | `--set-url` | Update an existing remote | | `--name ` | Remote name (default `ploy`) | | `--read-only` | Mint a URL that can only fetch | | `--json` | Print the full URL as JSON | ```bash ploy git remote --add --ttl 30d git push -u ploy main ``` The URL contains a credential. The CLI hides it unless you pass `--json`. ## Repositories and projects ```bash # List an organization's Ploy Git repositories ploy api repository list --org org123 # Create a repository ploy api repository create my-app --org org123 --default-branch main # Mint a remote URL for a repository ploy api repository remote-url repo123 --ttl 24h --json # Delete a repository no project uses anymore (owners and admins only) ploy api repository delete repo123 --org org123 # Create a project with a new Ploy Git repository ploy api project create my-app --source ploy --org org123 # Create a project from an existing Ploy Git repository ploy api project create --source ploy --repository-id repo123 --org org123 ``` # CLI Overview URL: https://docs.meetploy.com/cli # Ploy CLI The `@meetploy/cli` package provides the `ploy` command for local development, TypeScript type generation, and building workers. ## Installation ```bash # Global install (recommended for local development) npm install -g @meetploy/cli # Or as a dev dependency in your project npm install -D @meetploy/cli ``` ## Commands | Command | Description | | -------------------------- | ------------------------------------------------- | | [`ploy dev`](https://docs.meetploy.com/cli/dev) | Start local development server with hot reloading | | [`ploy types`](https://docs.meetploy.com/cli/types) | Generate TypeScript types from `ploy.yaml` | | [`ploy vite`](https://docs.meetploy.com/cli/vite) | Run Cloudflare Vite with `ploy.yaml` config | | [`ploy push`](https://docs.meetploy.com/cli/git) | Push to the project's Ploy Git repository | | [`ploy git`](https://docs.meetploy.com/cli/git) | Mint and configure Ploy Git remote URLs | | `ploy build` | Build your worker project | | `ploy auth login` | Authenticate with the Ploy API | | `ploy auth logout` | Clear stored credentials | | `ploy api` | Interact with the Ploy platform API | ## Quick Start Create a `ploy.yaml` at the root of your project, then run: ```bash # Generate TypeScript types for your bindings ploy types # Start the local development server ploy dev ``` ## ploy.yaml The `ploy.yaml` file configures the Ploy runtime bindings available to your worker or Next.js app. The CLI reads this file for both `ploy dev` and `ploy types`. ```yaml title="ploy.yaml" kind: worker # worker | nextjs | static build: pnpm build out: dist # Runtime bindings — format is BINDING_NAME: resource_name db: DB: default queue: QUEUE: tasks workflow: FLOW: my_flow state: STATE: default ai: true auth: binding: PLOY_AUTH ``` After editing `ploy.yaml`, run `ploy types` to regenerate your TypeScript types. See the [Configuration](https://docs.meetploy.com/platform/configuration) page for the full `ploy.yaml` reference. ## Authentication To use the `ploy api` commands, authenticate first: ```bash ploy auth login ``` This opens a browser window for OAuth login. Credentials are stored in `~/.ploy/config.json`. You can also set `PLOY_API_TOKEN` as an environment variable to skip interactive login. # ploy types URL: https://docs.meetploy.com/cli/types # ploy types Generate TypeScript type definitions from your `ploy.yaml` bindings. Creates an `env.d.ts` file and updates `tsconfig.json` so that your editor and compiler know about all the runtime bindings available to your worker or Next.js app. ```bash ploy types [options] ``` ## Options | Flag | Description | Default | | --------------------- | ---------------- | ---------- | | `-o, --output ` | Output file path | `env.d.ts` | ## Usage Run `ploy types` at the root of your project after any change to `ploy.yaml`: ```bash ploy types # Generated env.d.ts ``` The generated file is automatically referenced in `tsconfig.json`. Commit it to your repository. ### Custom Output Path ```bash ploy types -o src/env.d.ts ``` ## Generated Output Given a `ploy.yaml` like: ```yaml title="ploy.yaml" kind: worker db: DB: default queue: TASKS: tasks workflow: FLOW: my_flow state: STATE: default auth: binding: PLOY_AUTH ai: true ``` `ploy types` generates: ```typescript title="env.d.ts" declare module "@meetploy/nextjs" { interface PloyEnv { vars: Record; DB: Database; TASKS: QueueBinding; FLOW: WorkflowBinding; STATE: StateBinding; PLOY_AUTH: PloyAuth; AI: Ai; PLOY_AI_URL: string; PLOY_AI_TOKEN: string; } } declare global { interface PloyEnv { vars: Record; DB: Database; TASKS: QueueBinding; FLOW: WorkflowBinding; STATE: StateBinding; PLOY_AUTH: PloyAuth; AI: Ai; PLOY_AI_URL: string; PLOY_AI_TOKEN: string; } } export {}; ``` `vars` is always present and typed as `Record`. Environment variables are not declared in `ploy.yaml`, so their keys are not known when the types are generated — see [Environment Variables](https://docs.meetploy.com/platform/env-vars). With `ai: true`, the generated types expose `env.AI.run()` first, and also include `PLOY_AI_URL` / `PLOY_AI_TOKEN` for direct gateway calls when needed. ## Supported Binding Types | ploy.yaml key | Type in PloyEnv | | ---------------- | ------------------------------------------------------------ | | `db` | `Database` per binding name | | `queue` | `QueueBinding` per binding name | | `workflow` | `WorkflowBinding` per binding name | | `state` | `StateBinding` per binding name (`KVNamespace` compatible) | | `fs` | `FileStorageBinding` per binding name | | `timer` | `TimerBinding` per binding name | | `auth` | `PloyAuth` as `PLOY_AUTH` | | `email` | `EmailBinding` as the `email.binding` name | | `ai: true` | `AI: Ai`, `PLOY_AI_URL: string`, and `PLOY_AI_TOKEN: string` | | `agentSDK: true` | All Agent SDK bindings (ai, state, fs, workflow, timer) | `StateBinding` keeps Ploy's existing binding names while supporting the Cloudflare KV methods `get`, `put`, `delete`, `getWithMetadata`, and `list`. When `@meetploy/agent-sdk` is installed in your project and `agentSDK: true` is not set in `ploy.yaml`, running `ploy types` will automatically add it for you. ## Using the Types After running `ploy types`, the `PloyEnv` global interface is available everywhere in your project. With `@meetploy/start`: ```typescript title="src/index.ts" import { ploy } from "@meetploy/start"; const worker = ploy() .get("/", {}, async (ctx) => { // ctx.env is fully typed const users = await ctx.env.DB.prepare("SELECT * FROM users").all(); return { users: users.results }; }) .build(); export default worker; ``` With a plain worker: ```typescript title="src/index.ts" export default { async fetch(request, env) { const result = await env.DB.prepare("SELECT * FROM users").all(); return Response.json(result.results); }, }; ``` With Next.js via `@meetploy/nextjs`: ```typescript title="app/api/route.ts" import { getPloyEnv } from "@meetploy/nextjs"; export async function GET() { const env = getPloyEnv(); const result = await env.DB.prepare("SELECT * FROM users").all(); return Response.json(result.results); } ``` Run `ploy types` any time you add or remove bindings in `ploy.yaml`. Add it to your `postinstall` or `prepare` script to keep types in sync automatically. ## package.json Integration ```json title="package.json" { "scripts": { "types": "ploy types", "dev": "ploy dev", "build": "ploy build", "postinstall": "ploy types" } } ``` # ploy vite URL: https://docs.meetploy.com/cli/vite # ploy vite Use `ploy vite` for Ploy Vite projects, including React apps that ship a worker from `worker/index.ts` and TanStack Start apps. For an overview of how the Vite integration works and how it's configured, see the [Vite](https://docs.meetploy.com/vite) guide. This page is the command reference. Ploy reads `ploy.yaml` and drives the Vite toolchain from it, so all of your bindings, assets, and compatibility settings live in one place. ## Commands ```bash ploy vite build [options] ploy vite dev [options] ``` ## Options | Flag | Description | Default | | ---------------------- | ----------------------------- | ------------- | | `--ploy-config ` | Path to `ploy.yaml` | auto-detected | | `...args` | Additional arguments for Vite | none | Any extra arguments are forwarded to the underlying Vite command. ## When to use it Use `ploy vite` when your project has both: * a Vite config * `@meetploy/vite` installed For plain workers, use `ploy dev` / `ploy build`. For Next.js, use `ploy dev` with `@meetploy/nextjs`. ## React + Worker Example This setup matches [examples/vite-full](https://github.com/meetploy/ploy/tree/main/examples/vite-full). ```json title="package.json" { "scripts": { "build": "tsc --noEmit && ploy vite build", "dev": "ploy vite dev", "types": "ploy types -o env.d.ts" } } ``` ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist compatibility_date: "2026-03-23" assets: binding: ASSETS not_found_handling: single-page-application run_worker_first: - /api/* - "!/api/docs/*" db: DB: default ``` ```typescript title="vite.config.ts" import { ploy } from "@meetploy/vite"; import react from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [react(), ...ploy()], }); ``` For non-TanStack projects, Ploy looks for a worker entry at `worker/index.ts` or the corresponding JavaScript/MJS variants. ## TanStack Start Example This setup matches [examples/tanstack-start-prerender](https://github.com/meetploy/ploy/tree/main/examples/tanstack-start-prerender). ```json title="package.json" { "scripts": { "build": "ploy vite build && tsc --noEmit", "types": "ploy types -o env.d.ts" } } ``` ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist compatibility_date: "2026-03-17" compatibility_flags: - nodejs_compat ``` ```typescript title="vite.config.ts" import { ploy } from "@meetploy/vite"; import { tanstackStart } from "@tanstack/react-start/plugin/vite"; import viteReact from "@vitejs/plugin-react"; import { defineConfig } from "vite"; export default defineConfig({ plugins: [ ...ploy({ viteEnvironment: { name: "ssr" } }), tanstackStart({ prerender: { enabled: true, autoSubfolderIndex: true, crawlLinks: false, failOnError: true, }, }), viteReact(), ], }); ``` When `@tanstack/react-start` is installed, Ploy automatically maps the worker entry to `@tanstack/react-start/server-entry`. ## Assets Use the top-level `assets` key in `ploy.yaml` to control static asset behavior for dynamic Vite deployments. ```yaml title="ploy.yaml" assets: binding: ASSETS not_found_handling: single-page-application run_worker_first: - /api/* - "!/api/docs/*" ``` * `binding` exposes the asset fetcher to your worker as `env.ASSETS` * `not_found_handling: single-page-application` enables SPA fallback behavior * `run_worker_first` lets API routes or other patterns bypass the asset layer ## Local Development ```bash pnpm ploy vite dev ``` This starts Vite dev mode with the config synthesized from `ploy.yaml`. If your app also uses Ploy bindings like `db`, generate types with `ploy types` first so `env.d.ts` stays current. ## Build ```bash pnpm ploy vite build ``` This runs the production Vite build using your `ploy.yaml` compatibility settings and asset config. ## Notes * Keep compatibility settings in `ploy.yaml`. * Use `assets` in `ploy.yaml` to control static file behavior. * If you need a custom Ploy config path, run `ploy vite build --ploy-config path/to/ploy.yaml`. * If you need to pass Vite's own `--config`, forward it directly: `ploy vite build -- --config vite.config.custom.ts`. # Cron Triggers URL: https://docs.meetploy.com/nextjs/cron # Cron Triggers Run recurring jobs — nightly reports, cleanup passes, billing ticks — alongside your Next.js app. ## Configuration Add cron triggers in your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist db: DB: default cron: HOURLY_CLEANUP: "0 * * * *" EVERY_10_SECONDS: "*/10 * * * * *" ``` Each key is a trigger name and each value a cron expression. The standard form has 5 fields; a 6-field expression adds a leading seconds field for sub-minute schedules. See [Cron Triggers](https://docs.meetploy.com/workers/cron) for the full expression syntax. ## Scheduled Handler Export a `scheduled` handler from your handlers module — `app/ploy.ts`, or `worker/index.ts` if you keep it out of the app directory: ```typescript title="worker/index.ts" export default { async scheduled(event, env) { await env.DB.prepare("DELETE FROM sessions WHERE expires_at < ?") .bind(Date.now()) .run(); console.log(`Ran ${event.cron} at ${String(event.scheduledTime)}`); }, } satisfies Ploy; ``` The handler receives the same `env` bindings as your routes, so it can read and write your database, send queue messages, and call the AI gateway. Use `event.cron` to tell triggers apart when you declare more than one: ```typescript async scheduled(event, env) { if (event.cron === "0 * * * *") { await runCleanup(env); return; } await runBillingTick(env); } ``` ## Local Development `ploy dev` schedules your triggers locally and delivers each one to the app's `/ploy-handler` route, which `initPloyForDev()` creates when it is missing. See [Background Handlers](https://docs.meetploy.com/nextjs#background-handlers). Execution history — including failures and durations — is visible in the dev dashboard at `http://localhost:4000`, where you can also fire a trigger by hand instead of waiting for its next tick. Triggers only fire while the dev server is running. A schedule that was due while it was stopped does not catch up. ## Next Steps * [Cron Triggers](https://docs.meetploy.com/workers/cron) - Expression syntax and worker usage * [Queues](https://docs.meetploy.com/nextjs/queues) - Process background jobs * [Database](https://docs.meetploy.com/nextjs/database) - Store data with SQLite # Database URL: https://docs.meetploy.com/nextjs/database # Database Add SQLite databases to your Next.js application with Ploy. Generated bindings work directly in `getPloyContext()`, so existing SQL access patterns transfer cleanly. ## Configuration Add a database binding in your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist db: DB: default ``` Generate types: ```bash pnpm ploy types ``` ## Migrations Create SQL migrations in `migrations/`. Ploy runs them in filename order and tracks applied files in `ploy_internal_db_migrations` inside the same database. For a single DB binding: ```text title="migrations/" migrations/ └── 20260403171410_init/ ├── migration.sql └── snapshot.json ``` Only `.sql` files are executed, so sibling files such as `snapshot.json` are ignored. If your project uses multiple DB bindings, scope migrations by binding name: ```text title="migrations/" migrations/ ├── DB/ │ └── 001_create_users.sql └── ANALYTICS_DB/ └── 20260403171410_init/ └── migration.sql ``` Production deploys on the default branch apply pending migrations before upload and log them in the build output. During local development, `ploy dev` applies project migrations on startup. To use a different directory, set [`migrations`](https://docs.meetploy.com/platform/configuration#migrations) in `ploy.yaml` to a path relative to the config file (for example, `migrations: ../db/migrations`). ## API Route Example This example assumes your `users` table already exists from a migration in `migrations/`. ```typescript title="app/api/users/route.ts" import { NextResponse } from "next/server"; import { getPloyContext } from "@meetploy/nextjs"; interface User { id: number; name: string; email: string; } export async function GET() { const { env } = getPloyContext(); const result = await env.DB.prepare("SELECT * FROM users").all(); return NextResponse.json({ users: result.results }); } export async function POST(request: Request) { const { env } = getPloyContext(); const { name, email } = await request.json(); const result = await env.DB.prepare( "INSERT INTO users (name, email) VALUES (?, ?)", ) .bind(name, email) .run(); return NextResponse.json({ success: true, meta: result.meta }); } ``` ## Server Component Example ```typescript title="app/users/page.tsx" import { getPloyContext } from "@meetploy/nextjs"; interface User { id: number; name: string; } export default async function UsersPage() { const { env } = getPloyContext(); const { results: users } = await env.DB.prepare( "SELECT * FROM users" ).all(); return (
    {users.map((user) => (
  • {user.name}
  • ))}
); } ``` ## Query Methods ### all() - Get All Rows ```typescript const { results } = await env.DB.prepare("SELECT * FROM users").all(); ``` ### first() - Get First Row ```typescript const user = await env.DB.prepare("SELECT * FROM users WHERE id = ?") .bind(1) .first(); ``` ### run() - Execute Statement ```typescript const result = await env.DB.prepare("INSERT INTO users (name) VALUES (?)") .bind("Alice") .run(); ``` ### exec() - Run Raw SQL ```typescript const result = await env.DB.exec(` CREATE INDEX IF NOT EXISTS idx_users_email ON users(email); PRAGMA optimize; `); console.log(result.count); ``` ### withSession() - Session Compatibility ```typescript const session = env.DB.withSession("first-primary"); const user = await session .prepare("SELECT * FROM users WHERE id = ?") .bind(1) .first(); ``` Always use prepared statements with `.bind()` to prevent SQL injection. ## Local Development During development, the local Ploy dashboard at `http://localhost:4000` lets you: * Browse table contents * Execute SQL queries * Inspect database structure Project migrations are applied on startup, and data persists across restarts in the `.ploy` directory. ## Next Steps * [Queues](https://docs.meetploy.com/nextjs/queues) - Process background jobs * [Workflows](https://docs.meetploy.com/nextjs/workflows) - Build durable multi-step processes # Next.js URL: https://docs.meetploy.com/nextjs # Next.js Ploy provides first-class support for Next.js applications with access to Cloudflare-compatible D1 and KV bindings, plus queues and workflows, through a simple integration package. ## Installation Install the Ploy CLI and Next.js integration: ```bash pnpm add @meetploy/cli @meetploy/nextjs ``` Add a dev script to your `package.json`: ```json title="package.json" { "scripts": { "dev": "ploy dev" } } ``` ## Configuration Create a `ploy.yaml` file in your project root: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist ``` Update your `next.config.ts` to initialize Ploy bindings in development: ```typescript title="next.config.ts" import type { NextConfig } from "next"; import { initPloyForDev } from "@meetploy/nextjs"; if (process.env.NODE_ENV === "development") { await initPloyForDev(); } const nextConfig: NextConfig = { output: "standalone", }; export default nextConfig; ``` The `initPloyForDev()` function reads your `ploy.yaml` and sets up mock bindings that proxy to the local Ploy emulator. ## Build-time page cache By default, Ploy's generated Next.js adapter disables persistent page caching. For apps that only need build-time prerenders, opt into a read-only cache: ```yaml title="ploy.yaml" kind: nextjs nextjs: cache: static ``` This serves eligible prerendered HTML and React Server Component payloads from that deployment's assets without rerendering the page. Middleware, redirects, and dynamic routes still run through the Next.js adapter. This is not a public HTTP response cache: authenticated or cookie-dependent pages must remain dynamic. Ploy's response instrumentation still applies. The cache is **read-only until the next deployment**. Do not enable it for apps that need ISR, on-demand revalidation (`revalidatePath` / `revalidateTag`), mutable cached fetches, or runtime cache writes. Builds reject timed page revalidation; other runtime revalidation APIs are not supported by this cache. No writable cache, queue, or additional bindings are provisioned. Ploy generates adapter configuration only when your app does not supply its own. Project-owned `open-next.config.ts` files, including edits to generated files, are preserved. Do not combine a custom adapter configuration with `nextjs.cache`: builds reject the conflicting policies instead of silently replacing your settings. To use Ploy's cache policy, remove the project adapter configuration. Custom configuration does not automatically stage the build-time cache, provision a writable cache, or add service bindings. Without custom configuration, omit `nextjs.cache` or set it to `disabled` to retain the default behavior. `ploy dev` continues to use Next.js's development server; validate production caching with a deployment preview. ## Usage Use `getPloyContext()` to access Ploy bindings in Server Components or API routes: ```typescript title="app/api/example/route.ts" import { NextResponse } from "next/server"; import { getPloyContext } from "@meetploy/nextjs"; export async function GET() { const { env } = getPloyContext(); // Access your bindings through env const result = await env.DB.prepare("SELECT * FROM users").all(); return NextResponse.json({ users: result.results }); } ``` ## Background Handlers Queue messages, workflow steps, and cron triggers are handled by a handlers module — `app/ploy.ts`, or `worker/index.ts` if you prefer keeping it out of the app directory: ```typescript title="app/ploy.ts" export default { async message(event, env, ctx) { // Queue messages }, async scheduled(event, env, ctx) { // Cron triggers }, } satisfies Ploy; ``` In production, Ploy bundles that module alongside your app and routes deliveries to it. Locally, they arrive over HTTP instead, so the app needs a route that re-exports the handlers: ```typescript title="app/ploy-handler/[[...path]]/route.ts" export { GET, POST } from "@meetploy/nextjs/handler"; ``` `initPloyForDev()` writes this route on first run when it is missing, so there is normally nothing to add. The file is a one-line re-export and is safe to commit. ## Local Development Run your Next.js app with Ploy: ```bash pnpm dev ``` This starts: * Your Next.js app * The Ploy emulator for databases, queues, and workflows * A local dashboard at `http://localhost:4000` for insights The local dashboard lets you inspect database contents, view queue messages, and monitor workflow executions. ## Environment Variables Read them with `process.env`, exactly as in any Next.js app: ```typescript title="app/page.tsx" export default function Page() { return

{process.env.APP_NAME}

; } ``` Values come from a `.env` file locally and from the Ploy dashboard in production. There is nothing to declare — `ploy.yaml` has no `env` section — and `getPloyContext()` is only needed for bindings such as databases and queues. The same values are on `env.vars` if you prefer reading them from the context rather than a global. See [Environment Variables](https://docs.meetploy.com/platform/env-vars) for the full details. ## Type Safety Generate TypeScript types from your `ploy.yaml`: ```bash pnpm ploy types ``` This creates an `env.d.ts` file with type-safe bindings: ```typescript title="env.d.ts" import type { Database, StateBinding } from "@meetploy/types"; declare module "@meetploy/nextjs" { interface PloyEnv { DB: Database; STATE: StateBinding; } } ``` Now `getPloyContext()` returns properly typed bindings: ```typescript const { env } = getPloyContext(); // env.DB is typed as Database // env.STATE is typed as StateBinding (Cloudflare KV-compatible) ``` ## Next Steps * [Database](https://docs.meetploy.com/nextjs/database) - Add SQLite databases to your app * [Queues](https://docs.meetploy.com/nextjs/queues) - Process background jobs * [Workflows](https://docs.meetploy.com/nextjs/workflows) - Build durable multi-step processes * [Cron Triggers](https://docs.meetploy.com/nextjs/cron) - Run scheduled jobs * [Environment Variables](https://docs.meetploy.com/platform/env-vars) - Configure your app with `process.env` # Queues URL: https://docs.meetploy.com/nextjs/queues # Queues Add message queues to your Next.js application for background job processing. ## Configuration Add a queue binding in your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist queue: TASKS: tasks ``` Generate types: ```bash pnpm ploy types ``` ## Sending Messages Send messages to the queue from API routes or Server Actions: ```typescript title="app/api/queue/route.ts" import { NextResponse } from "next/server"; import { getPloyContext } from "@meetploy/nextjs"; export async function POST(request: Request) { const { env } = getPloyContext(); const body = await request.json(); const { messageId } = await env.TASKS.send({ action: body.action, data: body.data, }); return NextResponse.json({ success: true, messageId }); } ``` ### Send with Delay ```typescript const { messageId } = await env.TASKS.send( { action: "send-reminder" }, { delaySeconds: 3600 }, // 1 hour delay ); ``` ### Batch Send ```typescript const { messageIds } = await env.TASKS.sendBatch([ { payload: { action: "task-1" } }, { payload: { action: "task-2" } }, { payload: { action: "task-3" } }, ]); ``` ## Message Handler Create a `ploy.ts` file in your app directory to handle incoming messages: ```typescript title="app/ploy.ts" export default { async message(event, env, ctx) { console.log("Processing message:", { id: event.id, queue: event.queueName, payload: event.payload, attempt: event.attempt, }); const payload = event.payload as { action: string; data?: unknown }; switch (payload.action) { case "send-email": // Process email sending break; case "generate-report": // Generate report break; default: console.log("Unknown action:", payload.action); } }, } satisfies Ploy; ``` Messages that throw an error are automatically retried with exponential backoff. Locally, messages are delivered to your app's `/ploy-handler` route, which `initPloyForDev()` creates for you. See [Background Handlers](https://docs.meetploy.com/nextjs#background-handlers). ## Complete Example Here's a complete example with database integration: ```typescript title="app/ploy.ts" export default { async message(event, env, ctx) { const payload = event.payload as { action: string; data: unknown }; // Store processed message in database await env.DB.prepare( "INSERT INTO processed_messages (message_id, payload, processed_at) VALUES (?, ?, ?)", ) .bind(event.id, JSON.stringify(payload), new Date().toISOString()) .run(); console.log("Message processed:", event.id); }, } satisfies Ploy; ``` ## Local Development During development, the local Ploy dashboard at `http://localhost:4000` lets you: * View pending and processed messages * Manually retry failed messages * Inspect message payloads ## Next Steps * [Database](https://docs.meetploy.com/nextjs/database) - Store data with SQLite * [Workflows](https://docs.meetploy.com/nextjs/workflows) - Build durable multi-step processes * [Cron Triggers](https://docs.meetploy.com/nextjs/cron) - Run scheduled jobs # Workflows URL: https://docs.meetploy.com/nextjs/workflows # Workflows Build long-running, multi-step processes that survive failures with automatic retries and state persistence. ## Configuration Add a workflow binding in your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist workflow: DATA_FLOW: data_processing ``` The key (`DATA_FLOW`) is the binding name. The value (`data_processing`) must match the workflow function name in your code. You can use the expanded form to configure retries per workflow: ```yaml title="ploy.yaml" workflow: DATA_FLOW: name: data_processing retries: 5 # Retry failed steps up to 5 times (default: 3) ``` Generate types: ```bash pnpm ploy types ``` ## Triggering Workflows Trigger workflows from API routes or Server Actions: ```typescript title="app/api/workflow/route.ts" import { NextResponse } from "next/server"; import { getPloyContext } from "@meetploy/nextjs"; export async function POST(request: Request) { const { env } = getPloyContext(); const body = await request.json(); const { executionId } = await env.DATA_FLOW.trigger({ action: body.action, value: body.value, }); return NextResponse.json({ success: true, executionId }); } ``` ### Get Execution Status ```typescript export async function GET(request: Request) { const { env } = getPloyContext(); const url = new URL(request.url); const executionId = url.searchParams.get("executionId"); const execution = await env.DATA_FLOW.getExecution(executionId); return NextResponse.json({ id: execution.id, status: execution.status, // "running" | "completed" | "failed" output: execution.output, }); } ``` ### Cancel Execution ```typescript await env.DATA_FLOW.cancel(executionId); ``` ## Workflow Definition Define workflows in your `ploy.ts` file: ```typescript title="app/ploy.ts" interface WorkflowInput { action: string; value: number; } interface WorkflowOutput { action: string; originalValue: number; processedValue: number; } export default { workflows: { data_processing: { handler: async ({ input, env, step, }: WorkflowContext): Promise => { // Step 1: Validate input const validation = await step.run("validate", async () => { if (!input.action) { throw new Error("Missing action"); } return { valid: true, action: input.action }; }); // Step 2: Process the value const processed = await step.run("process", async () => { let result: number; switch (input.action) { case "double": result = input.value * 2; break; case "square": result = input.value * input.value; break; default: result = input.value; } return { processedValue: result }; }); // Step 3: Store result await step.run("store", async () => { await env.DB.prepare( "INSERT INTO results (action, input, output) VALUES (?, ?, ?)", ) .bind(input.action, input.value, processed.processedValue) .run(); }); return { action: input.action, originalValue: input.value, processedValue: processed.processedValue, }; }, }, }, } satisfies Ploy; ``` ## Inputs and Outputs There are two levels of persisted workflow data: * **Execution input**: the payload passed to `env.DATA_FLOW.trigger(...)` * **Execution output**: the final value returned by the workflow handler For deeper debugging, each step can also persist its own snapshots: * **Step input**: optional metadata passed with `step.run(..., { input })` * **Step output**: the value returned from the step callback ```typescript const processed = await step.run( "process", async () => { return { processedValue: input.value * 2 }; }, { input: { action: input.action, value: input.value, }, }, ); ``` This is especially useful when a workflow transforms data between steps and you want the dashboard to show what each step actually received. ## Step API ### step.run Execute a named step. Results are persisted, so re-runs skip completed steps: ```typescript const result = await step.run("step-name", async () => { return { data: "value" }; }); ``` ### step.sleep Pause execution for a duration (in milliseconds): ```typescript await step.sleep(5000); // Wait 5 seconds ``` Generated worker runtimes use the configured callback retry default (normally three). The Next.js development route defaults to zero; set per-step `{ retries: 3 }` explicitly when testing callback retries there. Use `{ retries: false }` (or `{ retries: 0 }`) for non-idempotent effects. Callback retries and completion acknowledgements are separate. Once a callback succeeds, transient completion failures retry only the acknowledgement, at most twice more with the same serialized output. Every acknowledgement checks the HTTP status and success response. Exhausted or rejected acknowledgements surface an infrastructure error without rerunning successful callbacks, invoking `onError`, or marking the workflow failed. Workflow completion follows the same rule. This does not guarantee exactly-once effects across a crash: an external operation may succeed before its completion is persisted. Even with `retries: false`, a later replay can execute an uncommitted step again. Use provider idempotency keys or reconcile uncertain effects. Unique step names identify persisted results, not atomic external side effects. Reported acknowledgement uncertainty holds the running execution out of automatic failure/recovery until investigation or explicit cancellation. An unreported host failure or a lost entire execution response can still trigger best-effort recovery and replay uncommitted work. With suspendable dispatch, sleep persists a wake-up deadline and returns control to the broker/emulator until that deadline. Replay reuses the persisted deadline and skips completed elapsed sleeps. Legacy non-suspendable dispatch still uses a process-local timer and is not host-failure durable. ## Error Handling Each workflow definition supports an optional `onError` callback that runs when the handler throws. Use it for cleanup, alerting, or releasing locks: ```typescript workflows: { data_processing: { handler: async ({ input, env, step }) => { // ... workflow steps }, onError: async (error, { env }) => { console.error("Workflow failed:", error.message); // Release locks, send alerts, clean up resources }, }, }, ``` The `onError` hook runs **before** the workflow is marked as failed. If `onError` itself throws, the error is ignored and the workflow still fails normally. Locally, workflow steps are dispatched to your app's `/ploy-handler` route, which `initPloyForDev()` creates for you. See [Background Handlers](https://docs.meetploy.com/nextjs#background-handlers). ## Local Development During development, the local Ploy dashboard at `http://localhost:4000` lets you: * View workflow executions * Inspect step results * Monitor execution status [Screenshot: Workflow executions list in the local Ploy dashboard] Open an execution to inspect execution input/output, step-level input/output, retry attempts, and timing details. [Screenshot: Workflow execution detail view showing execution and step inputs and outputs] ## Next Steps * [Database](https://docs.meetploy.com/nextjs/database) - Store data with SQLite * [Queues](https://docs.meetploy.com/nextjs/queues) - Process background jobs # Configuration URL: https://docs.meetploy.com/platform/configuration # Configuration Ploy uses a `ploy.yaml` file in the root of your repository to configure build settings and deployment options. This file provides fine-grained control over how your project is built and deployed. Authentication session settings, including the [shared session domain](https://docs.meetploy.com/auth/subdomains), are managed in the dashboard or auth-binding API, not as `ploy.yaml` keys. *** ## Quick Start Create a `ploy.yaml` file in your repository root: ```yaml kind: static build: npm run build out: dist ``` Commit and push the file to trigger a deployment with your custom configuration. *** ## Configuration Options ### `kind` **Type:** `"static" | "nextjs" | "dynamic" | "worker"` **Required:** No (auto-detected if omitted) Specifies the project type: * **`static`**: Static site generation (React, Vue, Angular, HTML, etc.) * **`nextjs`**: Next.js applications with server-side rendering support * **`dynamic`**: Worker-based applications and full-stack runtimes * **`worker`**: Alias for `dynamic` ```yaml kind: static ``` If `kind` is set to `static`, the `build` command is **required**. **Example - Static React App:** ```yaml kind: static build: npm run build out: dist ``` **Example - Next.js App:** ```yaml kind: nextjs build: npm run build out: .next ``` **Example - Cloudflare Vite / TanStack Start App:** ```yaml kind: dynamic build: pnpm build out: dist ``` *** ### `project` **Type:** `string` **Required:** No The ID of the Ploy project this directory deploys to. [`ploy push`](https://docs.meetploy.com/cli/git) and `ploy git remote` use it when you don't pass `--project`. ```yaml kind: worker project: proj_abc123 ``` ### `build` **Type:** `string` **Required:** Yes (when your project needs a build step) The command to run to build your project. This is typically a script defined in your `package.json`. ```yaml build: npm run build ``` **Common examples:** ```yaml # npm build: npm run build # pnpm build: pnpm build # yarn build: yarn build # Custom script build: npm run build:production ``` The `build` command is required for static apps and most dynamic apps, including Vite, TanStack Start, and worker bundles built during deployment. *** ### `assets` **Type:** `object` **Required:** No Configures uploaded static assets for dynamic projects such as Cloudflare Vite apps. Set static asset behavior here in `ploy.yaml`. ```yaml assets: binding: ASSETS not_found_handling: single-page-application run_worker_first: - /api/* - "!/api/docs/*" ``` **Fields:** * `binding`: Optional binding name exposed to your worker. Must be uppercase with underscores. * `not_found_handling`: One of `none`, `404-page`, or `single-page-application`. * `run_worker_first`: Either `true`, `false`, or an array of route patterns. Use `run_worker_first` when your worker should handle some requests before the asset layer. In the example above, `/api/*` stays worker-first, while `/api/docs/*` is served from static assets. *** ### `out` **Type:** `string` **Required:** No (auto-detected if omitted) **Default:** Framework-specific (e.g., `dist`, `build`, `.next`) The relative path to the output directory containing your built files. ```yaml out: dist ``` **Validation rules:** * Must be a **relative path** (not absolute) * Cannot start with `/` * Cannot contain `..` (path traversal prevention) * Trailing slashes are automatically removed **Common output directories:** | Framework | Default Output | | ---------------- | ------------------- | | Vite | `dist` | | Create React App | `build` | | Next.js | `.next` | | Angular | `dist/project-name` | | SvelteKit | `build` | | Astro | `dist` | **Example:** ```yaml kind: static build: npm run build out: dist ``` **Invalid paths:** - `out: /dist` ❌ (absolute path) - `out: ../dist` ❌ (path traversal) - `out: dist/` ✅ (trailing slash auto-removed) *** ### `base` **Type:** `string` **Required:** No **Default:** Repository root The base directory where your project is located within the repository. This is useful for monorepos where your deployable project is in a subdirectory. ```yaml base: apps/web ``` **Validation rules:** * Must be a **relative path** (not absolute) * Cannot start with `/` * Cannot contain `..` (path traversal prevention) * Trailing slashes are automatically removed **Monorepo example:** ``` my-monorepo/ ├── apps/ │ ├── web/ ← Your Next.js app │ └── api/ ├── packages/ │ └── ui/ └── ploy.yaml ``` ```yaml kind: nextjs base: apps/web build: npm run build out: .next ``` When using `base`, all paths (like `out`) are relative to the base directory, not the repository root. *** ### Monorepos Ploy detects monorepos automatically — there is no `monorepo` field. A repository is treated as a monorepo when it contains workspace indicators (`pnpm-workspace.yaml`, `package.json` with `workspaces`, `turbo.json`, etc.) **or** when more than one `ploy.yaml` is present in the repository. When a monorepo is detected and a project has a `base` field, Ploy installs dependencies from the repository root (so workspace dependencies resolve) and runs the build command from `base`. ``` my-monorepo/ ├── apps/ │ ├── web/ │ │ └── ploy.yaml ← Config for web app │ └── docs/ │ └── ploy.yaml ← Config for docs app ├── packages/ │ └── ui/ └── package.json ``` **`apps/web/ploy.yaml`:** ```yaml kind: nextjs base: apps/web build: pnpm build --filter web ``` **`apps/docs/ploy.yaml`:** ```yaml kind: nextjs base: apps/docs build: pnpm build --filter docs ``` Each app's `ploy.yaml` is a complete configuration on its own — it is not merged with a root config unless it opts in with [`extends`](#extends). To exclude directories that happen to contain a `ploy.yaml` (e.g., `examples/`, `templates/`, fixtures) from monorepo detection, add a `ploy-workspace.yaml` at the repository root: ```yaml # ploy-workspace.yaml exclude: - examples/** - templates/** ``` `node_modules/` is always excluded. *** ### `migrations` **Type:** `string` **Required:** No **Default:** `migrations/` in the project directory The directory holding your [database migrations](https://docs.meetploy.com/databases#migrations). The path is resolved relative to the directory containing `ploy.yaml`, so it can point outside that directory — useful when several configs (for example, one per region) share the same migrations: ``` my-app/ ├── deploy/ │ ├── eu/ │ │ └── ploy.yaml │ └── kr/ │ └── ploy.yaml ├── migrations/ │ └── 001_init.sql └── src/ ``` **`deploy/kr/ploy.yaml`:** ```yaml kind: worker db: DB: kr_db migrations: ../../migrations ``` **Validation rules:** * Must be a **relative path** (not absolute) * Must resolve to a directory inside the repository * Trailing slashes are automatically removed The directory supports the same layouts as the default `migrations/` folder, including per-binding subdirectories. *** ### `extends` **Type:** `string` **Required:** No Path to another `ploy.yaml` to inherit from, relative to the file that declares it. Use it to deploy several variants of the same app — for example one per region — that differ only in which resources they bind: ``` my-app/ ├── ploy.yaml # project "my-app" ├── deploy/ │ └── kr/ │ └── ploy.yaml # project "kr" ├── migrations/ │ └── 001_init.sql └── src/ ``` **`ploy.yaml`:** ```yaml kind: worker name: my-app build: pnpm build db: DB: main_db cache: CACHE: main_cache cron: CLEANUP: "0 * * * *" ``` **`deploy/kr/ploy.yaml`:** ```yaml extends: ../../ploy.yaml db: DB: kr_db cache: CACHE: kr_cache ``` The `kr` project builds the same app from the repository root, keeps the `CLEANUP` cron and build command, and binds `kr_db` and `kr_cache` instead. **Merge rules** (the extending file wins): * **Single values** such as `kind`, `build`, `out`, `main`, `base`, `compatibility_date`, `log_level`, and `ai` are replaced. * **Binding maps** (`db`, `queue`, `cache`, `state`, `fs`, `sandbox`, `service`, `workflow`, `cron`, `timer`) are merged per binding. Set a binding to `null` to drop an inherited one: ```yaml extends: ../../ploy.yaml cron: CLEANUP: null # this variant runs no cleanup cron ``` * **Objects and lists** (`auth`, `assets`, `compatibility_flags`, `deploy`) are replaced as a whole. * **`name` and `dev` are not inherited**, so a variant never clashes with its parent's project name or local dev port. The name defaults to the variant's directory (`kr` above). * An inherited **`migrations`** path keeps pointing at the same directory. **App directory:** a variant builds from its `base` when one is set (inherited or its own), otherwise from the directory of the top-most config it extends — the repository root in the example above. Unless `migrations` is set, migrations are read from `migrations/` in the app directory, so every variant applies the same migrations to its own databases. **Validation rules:** * Must be a **relative path** that stays inside the repository * A config can extend a config that itself uses `extends`, up to 5 levels deep; circular chains are rejected * The merged result must be a valid `ploy.yaml` Resources are scoped to your organization by name. Two projects that bind the same resource name share that resource, so give each variant its own names when the data must stay separate. To run a variant locally, pass its config from the app directory: ```bash ploy dev -c deploy/kr/ploy.yaml ``` *** ### `auth` **Type:** `{ binding: string }` **Required:** No Enable [Ploy Auth](https://docs.meetploy.com/auth) for this project: ```yaml auth: binding: AUTH_DB ``` OAuth provider credentials and [additional scopes](https://docs.meetploy.com/auth/social#request-additional-scopes) are managed in **Auth → Settings**, not in `ploy.yaml`. For local development, use the provider-specific [`PLOY_AUTH_*` environment variables](https://docs.meetploy.com/auth/social#local-development). Access and refresh tokens are managed by Ploy; retrieve provider access tokens only through the [server SDK](https://docs.meetploy.com/auth/social#call-the-provider-api), not a browser fetch. [Lifecycle hooks](https://docs.meetploy.com/auth/hooks) are exported in your worker or `ploy.ts`, not declared as a YAML handler or URL. Enable deployed hooks using **Auth → Settings → Auth hooks** (owners and admins only); they default to off. The auth-binding settings API exposes this as `hooksEnabled`. Local `ploy dev` always calls exported hooks. *** ### `agentSDK` **Type:** `boolean` **Required:** No **Default:** `false` Enables the [Agent SDK](https://docs.meetploy.com/agent-sdk) bindings. When set to `true`, Ploy automatically configures all bindings required by `@meetploy/agent-sdk`: * `ai: true` (AI gateway) * `state: { PLOY_AGENT_STATE: ploy_agent_state }` (durable key-value storage) * `fs: { PLOY_AGENT_FILES: ploy_agent_files }` (file storage) * `workflow: { PLOY_AGENT_WORKFLOW: ploy_agent_run }` (durable workflow) * `timer: { PLOY_AGENT_SCHEDULER: ploy_agent_scheduler }` (scheduled tasks) ```yaml kind: worker agentSDK: true ``` You can still add extra bindings alongside `agentSDK: true` — they will be merged with the defaults. Running `ploy dev` will warn you if `@meetploy/agent-sdk` is installed but `agentSDK: true` is not set. Running `ploy types` will automatically add it. *** ### `agentRules` **Type:** `boolean` **Required:** No **Default:** `true` When `ploy dev` detects an AI coding agent, it creates or refreshes version-matched instructions in the project's `AGENTS.md` or `CLAUDE.md`. These instructions direct the agent to documentation bundled with the installed `@meetploy/cli` version. Disable this behavior for a project with: ```yaml agentRules: false ``` *** ### `email` **Type:** `object` **Required:** No Configures [Ploy Email](https://docs.meetploy.com/email/workers) for the worker: a binding to send email, and the addresses it receives email at. ```yaml email: binding: EMAIL from: "Acme " allowed_from: - "*@acme.ploy.email" ``` * **`binding`**: name of the binding in `env`. Required when `from` or `allowed_from` is set. * **`from`**: default sender for `send()`. * **`allowed_from`**: senders the worker may use, as exact addresses or `*@domain`. Without it, any address on a verified domain of the organization is allowed. * **`receive`**: addresses or whole domains (`*@domain`) whose email is delivered to the worker's `email()` handler. See [Receiving email](https://docs.meetploy.com/email/workers#receiving-email). * **`inbox`**: `true` gives the project a private, receive-only `@in.ploy.email` address, without email access. See [Inbox address](https://docs.meetploy.com/email/workers#inbox-address). Only production deployments update these settings; preview deployments use the production settings. *** ### `skew_protection` **Type:** `boolean` **Required:** No **Default:** `true` Controls [Skew Protection](https://docs.meetploy.com/platform/skew-protection), which pins a client's framework-managed requests to the deployment that served its page. Enabled by default; set to `false` to opt out. ```yaml kind: nextjs skew_protection: false ``` *** ### `deploy` **Type:** `object` **Required:** No Skips deployments for some pushes. Ploy normally deploys every push to every branch. ```yaml deploy: ignored_branches: ^(assets|dependabot)/ skip_markers: - "[no deploy]" ``` * **`ignored_branches`**: a regular expression. Pushes to a branch that matches it are not deployed. Patterns with nested repetition such as `(a+)+`, back-references, or more than two unbounded quantifiers (`*`, `+`, `{n,}`) are rejected. * **`skip_markers`**: extra commit message markers. A push is not deployed when its latest commit message contains one of them, ignoring case. These markers skip a deployment even without any configuration: `[skip deploy]`, `[deploy skip]`, `[skip ci]`, `[ci skip]` and `[skip]`. ```bash git commit -m "docs: fix typo [skip deploy]" ``` Ploy reads `deploy` from the `ploy.yaml` at the pushed commit. To apply one set of rules to every project in a repository, put `deploy` in [`ploy-workspace.yaml`](https://docs.meetploy.com/features/monorepos#ploy-workspaceyaml) instead. When the pushed commit has no such file, for example on a branch that only holds assets, Ploy reads it from the production branch. You can also set both rules in **Project Settings** → **Preferences** → **Deploy Rules**; all three sources apply. A deployment you start manually from the dashboard ignores these rules. *** ## Complete Examples ### Static Vite + React App ```yaml kind: static build: npm run build out: dist ``` ### Next.js App ```yaml kind: nextjs build: pnpm build out: .next ``` ### Monorepo with Turborepo Project structure: ``` my-app/ ├── apps/ │ ├── web/ # Next.js frontend │ └── docs/ # Documentation site ├── packages/ │ └── ui/ # Shared UI components ├── package.json # Root with workspaces ├── turbo.json └── ploy.yaml ``` `ploy.yaml` for deploying the `web` app: ```yaml kind: nextjs base: apps/web build: npm run build out: .next ``` ### Custom Output Directory ```yaml kind: static build: npm run build:prod out: public/dist ``` ### SPA with Custom Base Path ```yaml kind: static build: npm run build out: build base: packages/client ``` *** ## Configuration Priority Ploy uses the following priority order for configuration: 1. **`ploy.yaml`** (highest priority) - Explicit configuration file 2. **Dashboard settings** - Manual overrides in project settings 3. **Auto-detection** (lowest priority) - Framework detection Settings in `ploy.yaml` will **override** dashboard settings and auto-detection. This ensures your repository configuration is the source of truth. *** ## Validation Errors Common validation errors and how to fix them: ### "Build command is required when kind is 'static'" ```yaml # ❌ Missing build command kind: static out: dist # ✅ Fixed kind: static build: npm run build out: dist ``` ### "Out path must be relative, not absolute" ```yaml # ❌ Absolute path kind: static build: npm run build out: /dist # ✅ Fixed - relative path kind: static build: npm run build out: dist ``` ### "Out path cannot contain '..'" ```yaml # ❌ Path traversal kind: static build: npm run build out: ../dist # ✅ Fixed kind: static build: npm run build out: dist ``` ### "Base path must be relative, not absolute" ```yaml # ❌ Absolute path kind: static base: /apps/web build: npm run build # ✅ Fixed kind: static base: apps/web build: npm run build ``` *** ## Best Practices 1. **Commit `ploy.yaml` to version control** - Keep configuration in sync with code 2. **Use `kind: static` for most frameworks** - Only use `nextjs` for Next.js apps requiring SSR 3. **Use relative paths** - Never use absolute paths or `..` for security 4. **Match your framework's output directory** - Check your framework's documentation for the correct `out` path *** ## Troubleshooting ### My build is failing 1. Check that your `build` command works locally: `npm run build` 2. Verify the `out` directory exists after building 3. Review deployment logs for specific error messages ### My monorepo isn't building correctly 1. Verify your root `package.json` has workspace configuration (or a `pnpm-workspace.yaml` exists) 2. Check that the `base` path points to the correct app directory 3. Ensure build commands are run from the base directory 4. To exclude unrelated `ploy.yaml` files (e.g., in `examples/`), add a `ploy-workspace.yaml` with an `exclude:` list at the repo root ### Configuration changes aren't taking effect 1. Ensure `ploy.yaml` is committed to your repository 2. Push your changes to trigger a new deployment 3. Check deployment logs to see which configuration was used 4. Verify there are no YAML syntax errors in your file *** ## Next Steps * Review the [Platform overview](https://docs.meetploy.com/platform) for how deployments work * Learn about [Self-Hosting](https://docs.meetploy.com/self-host) to deploy Ploy on your infrastructure * Check out the [example projects](https://github.com/meetploy/ploy/tree/main/examples) for inspiration # Deploy to Ploy button URL: https://docs.meetploy.com/platform/deploy-to-ploy # Deploy to Ploy button Add a Deploy to Ploy button to a README, docs page, or website so users can create a repository from your GitHub template and deploy it in one guided flow. ## Add the button Replace the example repository URL with the URL of your public GitHub template: ```md [![Deploy to Ploy](https://meetploy.com/button.svg)](https://meetploy.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Facme%2Fmy-template) ``` The destination is `https://meetploy.com/new/clone`. URL-encode the value of `repository-url` and any optional parameters. ## Prepare the template The source repository must: * Be public * Be marked as a template on GitHub * Contain at least one valid `ploy.yaml` If the repository contains multiple valid Ploy projects, the user chooses which `ploy.yaml` to deploy. A single project is selected automatically. ## Customize the link Use query parameters to provide defaults and explain which secrets the template needs. | Parameter | Description | | ----------------- | ---------------------------------------------------------------------------------- | | `repository-url` | Required. Public GitHub template repository URL. | | `repository-name` | Default name for the new repository. | | `project-name` | Default name for the Ploy project. | | `ploy-config` | Path to the `ploy.yaml` to use when the template contains multiple projects. | | `env` | Comma-separated environment variable names, such as `DATABASE_URL,OPENAI_API_KEY`. | | `envDescription` | Instructions shown above the secret fields. | | `envLink` | HTTPS link to instructions for finding the secret values. | For example: ```text https://meetploy.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Facme%2Fmy-template&repository-name=my-app&project-name=my-app&env=DATABASE_URL%2COPENAI_API_KEY&envDescription=Add%20the%20credentials%20required%20by%20this%20template.&envLink=https%3A%2F%2Fexample.com%2Fdocs ``` When a template declares optional environment variables in the deploy link, their values are entered directly in Ploy after the repository is connected. They are not copied into the repository or included in the deployment URL. Templates that do not declare variables skip this step. Deployment attempts expire after 24 hours if no repository was created. Once the repository exists, the flow remains resumable so users can finish GitHub App setup and deployment later. ## Next steps * [Configuration](https://docs.meetploy.com/platform/configuration) - Configure projects with `ploy.yaml` * [Environment Variables](https://docs.meetploy.com/platform/env-vars) - Manage variables and secrets after deployment # Environment Variables URL: https://docs.meetploy.com/platform/env-vars # Environment Variables Environment variables are not declared anywhere. Every variable you set in the Ploy dashboard is available to your build and to your worker at runtime under `env.vars`, and during local development the same applies to every entry of your project's `.env` file. `ploy.yaml` used to have an `env` section. It has been removed — frameworks like Next.js inject variables through their own mechanisms, and libraries you depend on can read variables you never wrote down. Declaring every variable up front only got in the way. ## Accessing Variables All variables are available under `env.vars` in your worker: ```typescript title="src/index.ts" export default { async fetch(request, env) { return Response.json({ appName: env.vars.APP_NAME, apiUrl: env.vars.API_URL, }); }, } satisfies Ploy; ``` In a Next.js app you keep using `process.env` as usual — Ploy's Next.js adapter injects the variables for you: ```typescript title="app/api/config/route.ts" export async function GET() { return Response.json({ apiUrl: process.env.API_URL }); } ``` `ploy types` generates a `vars` property typed as `Record`. Because variables are never declared, the CLI cannot know their names: ```typescript title="env.d.ts" declare global { interface PloyEnv { vars: Record; } } ``` ## Local Development with `.env` Create a `.env` file in your project directory: ```bash title=".env" APP_NAME=my-app SECRET_KEY=my-local-secret API_URL=http://localhost:3000/api ``` When you run `ploy dev`, every entry of that file is loaded and exposed under `env.vars`. Add `.env` to your `.gitignore` file. Never commit secrets to version control. ## Production: Dashboard Variables In production, `env.vars` is populated from the environment variables set on your project. The same values are also exported into the build environment, so they are available to `next build` and any other build step. ### Setting Variables in the Dashboard 1. Go to your project settings in the Ploy dashboard 2. Navigate to the **Environment Variables** section 3. Add the variables your project needs Variables can be added one at a time, or pasted in bulk in `KEY=value` form — for example straight from your local `.env` file. ### Secret vs Plaintext When adding variables in the dashboard, you can choose between: * **Secret**: The value is encrypted and never displayed after creation. Use for API keys, tokens, and passwords. * **Plaintext**: The value is stored and displayed in plain text. Use for non-sensitive configuration. ## Variables Ploy Sets For You Ploy injects a few variables of its own into every deployment: | Variable | Description | | -------------------- | ----------------------------------------------------------------------- | | `PLOY_URL` | The project's primary URL | | `PLOY_SHA_URL` | The immutable URL for this commit | | `PLOY_BRANCH_URL` | The URL for this branch | | `PLOY_LIVE_URL` | The URL of the current production deployment | | `PLOY_BRANCH` | The branch this deployment was built from | | `PLOY_COMMIT` | The commit this deployment was built from | | `PLOY_DEPLOYMENT_ID` | This deployment's id (see [skew protection](https://docs.meetploy.com/platform/skew-protection)) | ## Full Example ### Project Structure ``` my-worker/ ├── .env # Local values (gitignored) ├── ploy.yaml # Project configuration ├── env.d.ts # Generated types ├── package.json ├── tsconfig.json └── src/ └── index.ts ``` ### ploy.yaml ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist ``` ### .env ```bash title=".env" APP_NAME=my-app SECRET_KEY=dev-secret-key-123 API_URL=https://api.dev.example.com ``` ### src/index.ts ```typescript title="src/index.ts" export default { async fetch(request, env) { const url = new URL(request.url); if (url.pathname === "/config") { return Response.json({ appName: env.vars.APP_NAME, apiUrl: env.vars.API_URL, // Never expose secrets in responses! }); } // Use SECRET_KEY for authentication const authHeader = request.headers.get("Authorization"); if (authHeader !== `Bearer ${env.vars.SECRET_KEY}`) { return new Response("Unauthorized", { status: 401 }); } return Response.json({ message: "Authenticated" }); }, } satisfies Ploy; ``` ## Next Steps * [Workers](https://docs.meetploy.com/workers) - Learn about Ploy workers * [Configuration](https://docs.meetploy.com/platform/configuration) - Full `ploy.yaml` reference * [Databases](https://docs.meetploy.com/databases) - Add persistent SQLite databases # Platform URL: https://docs.meetploy.com/platform # Platform Ploy turns a Git repository into running deployments. Pick a source, add a `ploy.yaml`, and every push builds and deploys. This section covers everything around that loop: where your code comes from, how a project is configured, how environments and secrets reach your build and runtime, and how branches, monorepos, and templates map to deployments. ## How a deployment works 1. **Push** to a connected GitHub repository or to a [Ploy Git](https://docs.meetploy.com/platform/ploy-git) repository. 2. Ploy **reads `ploy.yaml`** at the pushed commit to find the project `kind`, build command, output directory, and bindings. 3. The **build** runs with your dashboard [environment variables](https://docs.meetploy.com/platform/env-vars) available, and the result is uploaded. 4. The deployment goes **live**: pushes to the production branch replace production, and every other branch gets a preview deployment with its own URL. 5. **Roll back** by redeploying any earlier deployment from the dashboard. Pushes can be skipped per branch pattern or commit-message marker with the [`deploy`](https://docs.meetploy.com/platform/configuration#deploy) section of `ploy.yaml`, or from **Project Settings → Preferences → Deploy Rules**. ## Project types `kind` in `ploy.yaml` tells Ploy how to build and run a project: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist db: DB: default ``` | Kind | Use it for | | --------- | ----------------------------------------------------------------------------------------------------------------- | | `static` | Static sites built with any framework — only the `out` directory is served | | `nextjs` | Next.js apps with server-side rendering, through [`@meetploy/nextjs`](https://docs.meetploy.com/nextjs) | | `dynamic` | [Workers](https://docs.meetploy.com/workers), [Vite](https://docs.meetploy.com/vite) and [TanStack Start](https://docs.meetploy.com/tanstack-start) apps, and other worker + assets projects | | `worker` | Alias for `dynamic` | Bindings such as `db`, `queue`, `workflow`, `cron`, `ai`, and `auth` are declared next to the build settings. The full reference is on the [Configuration](https://docs.meetploy.com/platform/configuration) page. ## In this section ## Related * [CLI](https://docs.meetploy.com/cli) — `ploy dev` runs your project locally with emulated bindings; `ploy push` and `ploy git` work with Ploy Git repositories. * [Self-hosting](https://docs.meetploy.com/self-host) — run the whole platform on your own infrastructure. # Monorepos URL: https://docs.meetploy.com/platform/monorepos # Monorepos Ploy detects monorepos automatically — there is no `monorepo: true` flag. A repository is treated as a monorepo when it contains workspace indicators (`pnpm-workspace.yaml`, `package.json` with `workspaces`, `turbo.json`, etc.) **or** when more than one `ploy.yaml` is present. Each `ploy.yaml` becomes its own deployable project. You can keep an `apps/api`, an `apps/web`, and a `packages/worker-jobs` in the same repo, deploy them as three independent Ploy projects, and share resources (databases, queues, workflows) between them by pointing them at the same resource name. ## Layout ``` my-app/ ├── ploy-workspace.yaml # optional — workspace-level config ├── apps/ │ ├── api/ │ │ └── ploy.yaml # → project "api" │ └── web/ │ └── ploy.yaml # → project "web" ├── packages/ │ └── worker-jobs/ │ └── ploy.yaml # → project "worker-jobs" ├── package.json └── pnpm-workspace.yaml ``` Each `ploy.yaml` is a complete config on its own unless it opts into inheriting from another one with [`extends`](#variants-of-one-app). Project names default to the parent directory; override with the `name:` field if you need something different. ```yaml title="apps/api/ploy.yaml" kind: worker name: api # optional — defaults to "api" build: pnpm build --filter api db: DB: default # shares the "default" DB with any other project that names it queue: TASKS: tasks ``` ## Sharing resources between projects Resources are addressed by their **resource name** (the lowercase string on the right side of the binding map). Two projects that bind to the same resource name read and write the same underlying resource — locally and in production. ```yaml title="apps/api/ploy.yaml" db: DB: default ``` ```yaml title="apps/web/ploy.yaml" db: DB: default # same DB as apps/api ``` To keep separate resources, use distinct names: ```yaml # apps/api/ploy.yaml db: DB: api_db # apps/web/ploy.yaml db: DB: web_db ``` Only one project may own migrations for a shared resource. If two projects both ship `migrations/DB/*.sql` for the same resource name, Ploy errors out with both project names so you can pick a single owner. ## Variants of one app To deploy the same app more than once — for example per region or per customer — with different resources, add a `ploy.yaml` per variant that [`extends`](https://docs.meetploy.com/platform/configuration#extends) the main one and overrides only the bindings that differ: ``` inferray/ ├── ploy.yaml # project "inferray" ├── deploy/ │ └── kr/ │ └── ploy.yaml # project "kr" ├── migrations/ # applied to both projects' databases └── src/ ``` ```yaml title="ploy.yaml" kind: worker name: inferray build: pnpm build db: DB: inferray cache: CACHE: inferray cron: SYNC: "*/15 * * * *" ``` ```yaml title="deploy/kr/ploy.yaml" extends: ../../ploy.yaml db: DB: instagewe cache: CACHE: instagewe ``` Both projects build from the repository root and share everything else in the main config — build command, crons, compatibility settings. Each deploy reads the variant file and the config it extends, so a change to the main `ploy.yaml` reaches every variant on its next deploy. Resources stay organization-wide and are matched by name: `kr` gets its own `instagewe` database and cache because it uses different names. Any binding a variant doesn't override keeps the main project's resource name, so both projects share that resource. Locally, `ploy dev` from the repo root skips variants so the same app doesn't start twice. Run a variant on its own with: ```bash $ ploy dev -c deploy/kr/ploy.yaml ``` ## `ploy-workspace.yaml` A workspace config at the repo root is **optional**. Add one when you need to: * Exclude `ploy.yaml` files that aren't deployable (e.g., examples, fixtures, templates) * Skip deployments for some branches or commits across every project * Set workspace-level dev port ranges * Pin the local dashboard port ```yaml title="ploy-workspace.yaml" exclude: - examples/** - templates/** deploy: ignored_branches: ^(assets|dependabot)/ ports: worker: from: 8800 # auto-allocate worker ports starting here dashboard: port: 9787 ``` `node_modules/` is always excluded by default. `deploy` takes the same fields as a project's [`deploy`](https://docs.meetploy.com/configuration#deploy) section and applies to every project in the repository, on top of each project's own rules. ## Local development Run `ploy dev` from the **repo root** to bring up all projects together: ```bash $ ploy dev Ploy workspace dev Dashboard: http://localhost:9787 api worker http://localhost:8787 web worker http://localhost:8788 ``` What this gives you: * **One shared `.ploy/` directory** at the repo root — all SQLite DBs, file storage, and emulator state live here. Resources with the same name across projects share the same files, exactly as in production. * **One shared dashboard** at `http://localhost:9787` exposing every project's bindings and the resources they touch. * **One workerd per project** on auto-allocated ports starting at `8787`. Override per-project with `dev: { port: 8800 }` in that project's `ploy.yaml`. * **Single `Ctrl-C`** stops everything cleanly. To run a subset: ```bash $ ploy dev --project=api $ ploy dev --project=api,web ``` Running `ploy dev` from inside a single project's directory still works the old way: that project alone is started with its own `.ploy/` and dashboard. This preserves backward compatibility for repos that aren't yet set up as workspaces. ## Cloud deployments When you connect a GitHub repository, Ploy scans it for `ploy.yaml` files (using the GitHub API — no clone needed) and shows the detected list in the dashboard. You select which entries to enable as projects. Each row defaults its name to the parent directory; override inline. After the initial connect, pushes to the default branch are diffed against the enabled set: * A `ploy.yaml` that already maps to a project triggers a build for **just that project**. * A new `ploy.yaml` that wasn't previously enabled appears as a "new project detected" entry. Nothing deploys until you explicitly enable it. * A `ploy.yaml` that's removed from the repo leaves the corresponding project untouched (archive or delete it manually if no longer needed). This means adding a deploy target to an existing monorepo is just `git add apps/billing/ploy.yaml && git push` — Ploy will surface the new project for confirmation rather than auto-deploying. ## How `base` interacts with monorepos In a monorepo, the build runs from the project's directory (the directory containing its `ploy.yaml`). Dependencies are installed from the **repo root** so workspace packages resolve. You don't need to set `base:` — it's inferred from the `ploy.yaml` location. The `base:` field is only required if your `ploy.yaml` lives at the **repo root** but the deployable code lives in a subdirectory. In that case `base:` tells the builder where to run the build: ```yaml title="ploy.yaml at repo root" kind: nextjs base: apps/web build: pnpm build --filter web ``` For per-project `ploy.yaml` files in subdirectories, omit `base:` — it's inferred. ## Migration from `monorepo: true` The `monorepo: true` flag has been removed from `ploy.yaml`. Remove it from your config files; Ploy now detects monorepos automatically from workspace indicators in your repo. If you previously had: ```yaml title="apps/web/ploy.yaml (old)" kind: nextjs base: apps/web monorepo: true build: pnpm build --filter web ``` Update to (drop both `monorepo` and `base` — the latter is inferred from the file's location): ```yaml title="apps/web/ploy.yaml (new)" kind: nextjs build: pnpm build --filter web ``` A validation error will point out any remaining `monorepo:` keys when you next run `ploy build` or push to a connected repo. # Move a project's source URL: https://docs.meetploy.com/platform/move-source # Move a project's source A project deploys from exactly one repository. Open **Settings → Source** to see which one and to move the project. Only organization owners and admins can move a project, and every move asks you to type `MOVE` to confirm. ## GitHub to Ploy Git **Move to Ploy Git** copies every branch and tag from the GitHub repository into a new Ploy Git repository. When the copy finishes, the project deploys from Ploy Git and pushes to GitHub no longer deploy. 1. Go to **Settings → Source**. 2. Optionally change the new repository's name. 3. Click **Move to Ploy Git** and confirm. The project keeps deploying from GitHub until the copy has finished. If the copy fails, nothing changes and you can try again. ## Ploy Git to GitHub **Move to GitHub** creates a new GitHub repository under your account, pushes the full history to it, and switches the project to it. You need a connected GitHub account and the Ploy GitHub App installed on the new repository's account. ## Mirror GitHub with Ploy Git **Mirror GitHub with Ploy Git** keeps GitHub as the source of truth. Ploy creates a Ploy Git repository that follows the GitHub repository, and the project deploys from the mirror once the first sync has finished. Keep pushing to GitHub as usual. Mirroring is only offered when it is enabled on your Ploy installation. ## What stays the same Moving a project keeps its deployments, domains, environment variables, bindings, and production branch. Only the repository it deploys from changes. # Ploy Git URL: https://docs.meetploy.com/platform/ploy-git # Ploy Git Ploy Git is a git repository hosted by Ploy. Push to it with any git client, from your laptop, a CI job, or an AI agent, and Ploy builds and deploys every push. You don't need a GitHub account. ## Create a project from Ploy Git 1. In the dashboard, click **New Project** and pick the **Ploy Git** tab. 2. Enter a repository name and the production branch (default `main`). 3. Click **Create project**, then **Generate push URL**. 4. Add the remote and push: ```bash git remote add ploy https://••••••@//.git git push -u ploy main ``` The dashboard remembers which source you picked, so the next new project opens on the same tab. During onboarding, choose **Ploy Git** under **Where does your code live?** to create your first repository without connecting GitHub. ## Push URLs A push URL is a normal git remote URL with a short-lived credential embedded in it. * URLs are minted on demand and never stored by Ploy. * Choose how long a URL stays valid: 1 hour, 24 hours, or 30 days. * The dashboard hides the credential until you reveal it. * Generate a new URL at any time from **Settings → Source → Push URL**. When a URL expires, update your remote with `git remote set-url ploy `. A push URL can push to your repository. Treat it like a password and regenerate it if it leaks. Owners, admins, and developers can create Ploy Git repositories and push URLs. Viewers cannot. ## Push from the CLI The CLI mints a fresh URL for each push, so nothing is written to your git config: ```bash ploy push --project ``` Or configure a long-lived `ploy` remote: ```bash ploy git remote --project --ttl 30d --add git push -u ploy main ``` Add `project: ` to your [`ploy.yaml`](https://docs.meetploy.com/platform/configuration#project) to drop the `--project` flag. See [`ploy git`](https://docs.meetploy.com/cli/git) for every option. ## Branches and deployments * Pushes to the production branch deploy to production. * Pushes to any other branch create a preview deployment with its own URL. * Tags and branch deletions do not deploy. * Change the production branch in **Settings → Source → Default Branch**. A project created from an empty repository waits for the first push before it deploys. ## Multiple projects Several projects can deploy from one Ploy Git repository, for example one per `ploy.yaml` in a monorepo. When a push to the production branch adds a new `ploy.yaml`, the dashboard offers to create a project for it. See [Monorepos](https://docs.meetploy.com/platform/monorepos). ## Move between GitHub and Ploy Git You can move an existing project from GitHub to Ploy Git, or back to GitHub, with its full history. See [Move a project's source](https://docs.meetploy.com/platform/move-source). # Product Analytics URL: https://docs.meetploy.com/platform/product-analytics # Product Analytics Open **Analytics → Product analytics** to understand actions inside your application. **People** lets you find a signed-in user by user ID, email or customer organization ID, then inspect their retained activity across product events, Web pageviews and instrumented HTTP requests. [Screenshot: People search and a consented user's connected activity journey] ## Three complementary views | View | Measures | Collection | | --------------------- | ---------------------------------------------------------------------------- | ----------------------------------- | | **Traffic** | Requests, errors, bandwidth and performance, including APIs, assets and bots | Automatic server-side request logs | | **Web analytics** | Browser pageviews, estimated visitors and sessions | Optional first-party browser script | | **Product analytics** | Application events, identified users and conversion journeys | Explicit, consented instrumentation | A single visit can produce many requests and several product events. The counters are intentionally different. Correlation supplies links between records; it does not combine the counters or prove someone is human. Organization-level **Analytics** offers Traffic and a project chooser for Product analytics. Web analytics is available within individual projects. Old Product analytics URLs redirect to the corresponding Analytics view. ## Configure collection and privacy Only organization owners and admins can change collection settings or publish keys. In **Product analytics → Settings**: 1. Enable product event collection and register the custom event names and properties you intend to collect. 2. Add the exact origins allowed to use browser publish keys. Keep server keys private. 3. Enable **identified users** if you want to explicitly associate events with a stable application user ID, email or customer organization ID. 4. Separately enable **cross-view correlation** if you want consenting browser activity linked to Web pageviews and instrumented same-origin requests. Both identity and correlation default off. They are independent of the optional **verified Ploy Auth actors** setting. Product data follows the configured retention period, at most 30 days. Browser identifiers and identity labels are not authentication credentials. ## Identify a user after sign-in The `@meetploy/analytics` SDK currently ships in the Ploy workspace; its first npm publication is a separate release prerequisite. The HTTP contract below is available without installing the SDK. ```typescript import { createAnalyticsClient } from "@meetploy/analytics/client"; const analytics = createAnalyticsClient({ endpoint: "https://analytics.example/v1/product-analytics/ingest", publicKey: "pa_pub_YOUR_BROWSER_KEY", // requireExplicitConsent: true, // Require a separate opt-in when needed. // correlate: false, // Disable automatic signed-in journeys. }); // After successful signup/sign-in or restoring an authenticated session. // This enables collection and cross-view linking without another prompt. analytics.identify("user_123", { email: "person@example.com", organizationId: "customer_org_456", }); analytics.track("signup.completed"); // Explicitly instrument application API calls, not document/OAuth navigation. await analytics.fetch("/api/checkout", { method: "POST" }); await analytics.flush(); // On logout: clear queued old-user data, identity labels and shared context. analytics.reset(); // On consent withdrawal: stop collection and clear in-memory state. analytics.setConsent(false); ``` Call `identify()` after successful sign-up, sign-in and session restoration on each new page load: it automatically starts collection and cross-view linking, while the SDK's context stays memory-only. Anonymous collection still requires `setConsent(true)`. Project-level **identified users**, **cross-view correlation** and Web analytics settings remain separate and are never enabled by this call. An explicit `setConsent(false)` is never overridden by sign-in or identification, including when set before the first login. To resume, call `setConsent(true)` explicitly. Permission and opt-out state are memory-only, so reapply any saved application preference before identification on a new page load. Configure `requireExplicitConsent: true` when a separate consent action is required; then identification returns false until permission is granted. `correlate: false` disables linking independently. Signing in is not itself universal legal consent: provide appropriate notice and use the lawful basis applicable to your users and intended collection. Use a **stable application user ID** as the first argument. Email and organization ID are optional, and either or both can be supplied. An organization ID is a grouping/filter attribute, not a user ID: people in the same organization must have distinct user IDs. Repeated `identify()` calls can update traits. Omitted traits preserve their stored values. Changing the distinct user ID resets the anonymous context; still call `reset()` explicitly on logout. Identity is never read automatically from the page, browser storage or authentication cookies. The SDK stores its anonymous context only in memory. A new page load creates a new anonymous context; an explicit later `identify()` call can connect consenting contexts to a browser-asserted profile within retention. Once a profile is server-asserted, browser claims cannot change it, attach new contexts or extend its expiry. To link another browser context to that profile, authenticate the user on your server and send `server.identify(anonymousId, userId, traits)` using that browser's consented anonymous context. With `requireExplicitConsent: true`, calls before consent do not collect identity. The optional `@meetploy/analytics/ploy-auth` adapter similarly activates on `identifyPloyAuth()` after successful authentication, but publishes cross-view context only after the live session is verified. Call `resetPloyAuth()` on sign-out; failed verification never falls back to anonymous tracking. Browser keys are public. A browser-asserted identity can be spoofed and must never authorize application access. Derive trusted user identity from your authenticated server session and use a secret server key when stronger application assertions are needed. Verified Ploy Auth actors remain a separate signed authentication flow. ### HTTP integration without the SDK Send events to your configured API endpoint with a publish key, explicit consent and an opaque anonymous context. `$identify` is reserved for profile updates and does not require a custom event schema. Other event names and properties must be registered in your collection settings. ```typescript // Keep this context only for the consenting browser lifetime. Rotate on logout. const anonymousId = crypto.randomUUID(); await fetch("https://analytics.example/v1/product-analytics/ingest", { method: "POST", credentials: "omit", redirect: "error", headers: { "Content-Type": "application/json", Authorization: "Bearer pa_pub_YOUR_BROWSER_KEY", }, body: JSON.stringify({ version: 1, consent: true, events: [ { id: crypto.randomUUID(), name: "$identify", version: 1, timestamp: new Date().toISOString(), anonymousId, identity: { distinctId: "user_123", email: "person@example.com", organizationId: "customer_org_456", }, }, ], }), }); ``` Only run this after the relevant consent. Browser ingestion requires an allowed exact origin. Use `pa_srv_` keys only from servers, never browsers. Server events can include the same explicit identity object and the consented anonymous context; webhook producers must retain that context themselves when relating a later purchase to an earlier visit. ### Record revenue Add `revenue` to any event your server sends with a `pa_srv_` key. The amount is an integer in the currency's minor units (cents for USD) and the currency is an uppercase ISO 4217 code. The **Revenue** view sums these amounts per currency, and the event keeps its identity, context and properties, so revenue can be related to the visit or campaign that led to it. ```typescript import { createAnalyticsServer } from "@meetploy/analytics"; const analytics = createAnalyticsServer({ endpoint: "https://analytics.example/v1/product-analytics/ingest", secretKey: process.env.ANALYTICS_SERVER_KEY!, }); analytics.setConsent(true); analytics.track("checkout.completed", { anonymousId, identity: { distinctId: "user_123" }, properties: { plan: "pro" }, revenue: { amountMinor: 1999, currency: "USD" }, }); // A refund is a $refund event with a negative amount. analytics.track("$refund", { anonymousId, identity: { distinctId: "user_123" }, revenue: { amountMinor: -1999, currency: "USD" }, }); await analytics.flush(); ``` Over HTTP, the same `revenue` object goes next to `properties` in the event. `$purchase` and `$refund` are reserved like `$identify` and need no registered schema; any other event with revenue must be registered as usual, and revenue does not count toward its 20 properties. Revenue must be positive, except on `$refund` where it must be negative. Events sent with a browser key cannot carry revenue, so the Revenue view only counts what your server reports. Send revenue only after your server has confirmed the payment with your payment provider. ## Find people and inspect events In **People**, enter an exact user ID, email or organization ID and choose **Search people**. Email lookup is case-insensitive. The optional **Organization filter** narrows results, so an email and organization can be searched together. Personal-data fields are encrypted at rest; lookup uses project-keyed hashes, not a global email index. Identity is never merged merely because two profiles share an email or organization. | Field | Meaning | | ------------------- | ----------------------------------------------------------------------- | | **User** | The application-provided stable user ID | | **Email** | The explicitly provided email, if present | | **Organization** | The application's customer organization ID, if present | | **Identity source** | Browser-asserted or server-asserted labels, not proof of authentication | | **Last seen** | The most recent retained profile update | | **View activity** | Open the user's activity journey for the selected time range | The journey shows product event names and properties, linked Web pageviews, and instrumented HTTP request method, path, status, duration and request/trace identifiers. Open **Details** for a record. Time-range filters apply to activity; the People list shows retained profiles. Queries and pagination are bounded; narrow the period if a journey exceeds the query limit. ## Connect Web visits and request traffic Enable Web analytics separately and enable Product analytics correlation. After `identify()`, the SDK shares a memory-only context by default, so the tracker can link the **current pageview** and subsequent pageviews to the shared context. **Web analytics → Recent pageviews & journeys** lets you inspect these links from the browser-traffic side. * Only explicitly instrumented, same-origin `analytics.fetch()` calls carry shared request context. Ordinary `fetch()`, assets, the initial document load, cross-origin requests and navigations are not silently instrumented. * The wrapper uses the ordinary, untrusted `Ploy-Analytics-Context` header. It is visible to your application worker, so do not forward it to third parties. It is not a trusted platform header or an authentication credential. * Redirects are rejected by the wrapper rather than directly forwarding context to another origin. Application fetch credentials/referrer options otherwise keep their normal behavior; the SDK does not read or create tracking cookies. * No IP/user-agent matching is used to join people or request records. The Web visitor estimate remains separate from the explicit identity. * The browser context is random and memory-only; there is no automatic cross-device tracking. Global Privacy Control and Do Not Track suppress correlation. * Opting into correlation can link the pageview for the **currently open page**, even if that one pageview was recorded earlier under lightweight Web analytics. Earlier visits are not reconstructed or joined by IP. If your policy requires collection and association to begin only after consent, disable automatic injection and load the manual Web tracker only after consent. * Activities already collected with consent in the same anonymous SDK context can become associated when you explicitly identify that context. Server-asserted profiles require the server to authorize each context; a public browser key cannot attach one on its own. An unlinked pageview shows **Anonymous estimate** and does not imply that all surrounding traffic belongs to that visitor. Counts can differ because of blocked scripts, missing consent, missing instrumentation, expiry and network delivery. ## Retention and deletion Profile traits, aliases and correlation links expire according to the product analytics retention setting. Expired data is not returned while background cleanup removes it. Request logs follow their own operational retention: removing an analytics identity or correlation link is not the same as deleting operational logs. Web analytics continues to follow its own retention and deletion controls. Turning **identified users** or **cross-view correlation** off stops new writes for that feature. Previously stored history remains browsable and erasable until it expires. Disabling a feature is not a deletion request. Owners and admins can choose **Erase person** from an activity view to remove the profile, currently associated identified product events and correlation links. **Erase identified people** in Settings removes all identified profiles and their currently associated data while keeping collection configuration. Both require typing `DELETE`. Aggregate Traffic and Web counts are not changed. ### Delete individual events Owners and admins can delete product events in **Events → Event explorer**. **Delete** on a row removes one event; **Delete *n* matching** removes every event the explorer lists for the selected time range and event filter, and shows the exact count before you confirm. Both require typing `DELETE`. If the number of matching events changed since the page loaded, nothing is deleted and you are asked to reload. One bulk deletion removes at most 50,000 events. Overview, dimension, funnel, retention and journey reports are calculated from the remaining events, so they reflect a deletion immediately. A profile whose contexts have no events left is removed with its aliases. If your app sends an event with a deleted event ID again, it is acknowledged as a duplicate and not stored, so client retries cannot restore it. Monthly quota already used by a deleted event is not refunded. Revenue events can also be deleted from the **Revenue** ledger, by row or for every listed event in a currency. A deleted event leaves the revenue totals, and a later resend with the same event ID is acknowledged as a duplicate without being stored. Each deletion is recorded with who deleted, when, how many rows and which filter, but not the deleted content. The record is available from the `GET /projects/{projectId}/product-analytics/deletions` API, and the delete operations are available as `DELETE /projects/{projectId}/product-analytics/events/{eventId}`, `DELETE /projects/{projectId}/product-analytics/events`, `DELETE /projects/{projectId}/product-analytics/revenue/events/{eventId}` and `DELETE /projects/{projectId}/product-analytics/revenue/events`. When a browser-asserted profile is promoted to a server-asserted one, untrusted browser contexts are detached unless the server explicitly authorizes them. These detached contexts remain pseudonymous and are not reached by a later person erasure; they follow their own expiry. Use full product analytics deletion if you need to remove all retained product events rather than only the currently associated identity. Reset and consent withdrawal clear local state and stop future SDK delivery; they do not retract requests already committed by the server. Erasure does not blacklist future uploads: stop identifying/collecting for that person in your application before erasing if collection must not resume. Full product analytics deletion remains owner/admin-only, requires typing `DELETE`, and removes configuration, keys, events, profiles and correlation links. See [Web analytics](https://docs.meetploy.com/platform/web-analytics) for its separate deletion controls. # Skew Protection URL: https://docs.meetploy.com/platform/skew-protection # Skew Protection **Version skew** happens when a user's browser is running the client bundle from one deployment while their follow-up requests hit a newer deployment that went live mid-session. The classic symptom is a `ChunkLoadError` — a code-split JavaScript chunk that no longer exists on the new deployment — along with broken client/server API contracts. Skew Protection fixes this by pinning a client's **framework-managed requests** (static chunks, navigations, prefetches) to the exact deployment that served the initial page load, for as long as that deployment is recent. Full-page navigations still get the latest deployment. ## Enabling Skew Protection is **on by default** for every project. Every successful deployment stays reachable, so pinned requests keep resolving. To opt out, set `skew_protection: false` in your `ploy.yaml`: ```yaml title="ploy.yaml" kind: dynamic build: pnpm build out: dist skew_protection: false # disable skew protection ``` ## Next.js For Next.js projects there is **nothing to configure**. Ploy injects `NEXT_DEPLOYMENT_ID` into the build, which Next.js reads natively to pin its own framework-managed requests — asset loads, client-side navigations, and prefetches all resolve to the deployment that served the page. Next.js also triggers a full reload automatically if it detects a deployment mismatch. Do not set `deploymentId` in your `next.config`. Next.js gives an explicit config value precedence over `NEXT_DEPLOYMENT_ID`, so a custom value would be sent on framework requests instead of the Ploy deployment id and those requests would fail to resolve. Leave it unset and let Ploy manage it. ### Your own client fetches Next.js pins the requests it makes for you, but not the custom `fetch` calls you write. To pin those, use `ployFetch`: ```tsx title="app/profile.tsx" "use client"; import { ployFetch } from "@meetploy/nextjs/config"; const res = await ployFetch("/api/profile"); ``` Full-page navigations (hard refresh, opening a link in a new tab) intentionally load the **latest** deployment. Skew Protection keeps the current page stable; the next full navigation picks up new deployments. ## Other frameworks Skew Protection works with any project — the edge honors a pin on every request. Pinning is only automatic for Next.js; for other frameworks and workers, attach the deployment id yourself. When enabled, these environment variables are available at both build time and runtime: | Variable | Value | | ---------------------- | ---------------------------------------------- | | `PLOY_DEPLOYMENT_ID` | The current deployment's id (always injected). | | `PLOY_SKEW_PROTECTION` | `"1"` when skew protection is enabled. | Send the id on a request using **either** the `?dpl=` query parameter or the `x-deployment-id` header: ```ts const res = await fetch(`/api/data?dpl=${process.env.PLOY_DEPLOYMENT_ID}`); // or const res = await fetch("/api/data", { headers: { "x-deployment-id": process.env.PLOY_DEPLOYMENT_ID }, }); ``` ## How it works 1. **Build** — Ploy injects the deployment id into the build (`NEXT_DEPLOYMENT_ID` for Next.js, plus `PLOY_DEPLOYMENT_ID` and `PLOY_SKEW_PROTECTION` for other frameworks). 2. **Client** — the framework (Next.js automatically) or your code attaches the deployment id to requests as `?dpl=` or `x-deployment-id`. 3. **Edge** — Ploy routes a pinned request to that exact deployment, as long as it is a successful, skew-protected deployment on the same project and branch the host resolved to, created within the max-age window (24 hours by default). Otherwise the request returns `404`, which prompts the framework to reload to the latest version. ## Next Steps * [Configuration](https://docs.meetploy.com/platform/configuration) - Full `ploy.yaml` reference * [Environment Variables](https://docs.meetploy.com/platform/env-vars) - Configure worker environment variables * [Next.js](https://docs.meetploy.com/nextjs) - Next.js integration # Web Analytics URL: https://docs.meetploy.com/platform/web-analytics # Web Analytics Web analytics counts pageviews from real browsers with a lightweight script served from your own domain. It is optional and off by default for every project. By default it sets no cookies, uses no browser storage and keeps no persistent identifier. Optional [product analytics correlation](https://docs.meetploy.com/platform/product-analytics) can explicitly link consented activity; it is separate and off by default. The project **Analytics** page has three complementary tabs: | Tab | What it counts | | --------------------- | ----------------------------------------------------------------------------------------------------- | | **Traffic** | Every request your deployments serve, including assets, APIs, bots and crawlers. Always on. | | **Web analytics** | Pageview beacons sent by browsers that ran the tracking script. Only while web analytics is enabled. | | **Product analytics** | Explicit application events, identified users and conversion journeys. Opt-in with separate settings. | ## Enabling web analytics Open your project's **Analytics** page, choose **Web analytics** and click **Enable web analytics**. Only organization owners and admins can enable, change or disable it. Changes reach your sites within about a minute. While enabled, Ploy adds one deferred script tag to successful (`200`) HTML document responses from both static sites and workers: ```html ``` The tag goes before ``, or before `` when the page has no head end tag. Ploy does not add it to other content types, `HEAD` requests, error responses, `fetch()` requests for HTML fragments, downloads, responses marked `Cache-Control: no-transform`, pages that already contain a tag for the script in their head, pages whose head has an inline script wrapped in an HTML comment (`