Merge pull request 'docs(production): standardiserad produktionsberedskap och gap-analys' (#29) from docs/prod-readiness-siax-20261111 into main
This commit was merged in pull request #29.
This commit is contained in:
@@ -1,296 +0,0 @@
|
||||
---
|
||||
name: deploy-to-vercel
|
||||
description: Deploy applications and websites to Vercel. Use when the user requests deployment actions like "deploy my app", "deploy and give me the link", "push this live", or "create a preview deployment".
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "3.0.0"
|
||||
---
|
||||
|
||||
# Deploy to Vercel
|
||||
|
||||
Deploy any project to Vercel. **Always deploy as preview** (not production) unless the user explicitly asks for production.
|
||||
|
||||
The goal is to get the user into the best long-term setup: their project linked to Vercel with git-push deploys. Every method below tries to move the user closer to that state.
|
||||
|
||||
## Step 1: Gather Project State
|
||||
|
||||
Run all four checks before deciding which method to use:
|
||||
|
||||
```bash
|
||||
# 1. Check for a git remote
|
||||
git remote get-url origin 2>/dev/null
|
||||
|
||||
# 2. Check if locally linked to a Vercel project (either file means linked)
|
||||
cat .vercel/project.json 2>/dev/null || cat .vercel/repo.json 2>/dev/null
|
||||
|
||||
# 3. Check if the Vercel CLI is installed and authenticated
|
||||
vercel whoami 2>/dev/null
|
||||
|
||||
# 4. List available teams (if authenticated)
|
||||
vercel teams list --format json 2>/dev/null
|
||||
```
|
||||
|
||||
### Team selection
|
||||
|
||||
If the user belongs to multiple teams, present all available team slugs as a bulleted list and ask which one to deploy to. Once the user picks a team, proceed immediately to the next step — do not ask for additional confirmation.
|
||||
|
||||
Pass the team slug via `--scope` on all subsequent CLI commands (`vercel deploy`, `vercel link`, `vercel inspect`, etc.):
|
||||
|
||||
```bash
|
||||
vercel deploy [path] -y --no-wait --scope <team-slug>
|
||||
```
|
||||
|
||||
If the project is already linked (`.vercel/project.json` or `.vercel/repo.json` exists), the `orgId` in those files determines the team — no need to ask again. If there is only one team (or just a personal account), skip the prompt and use it directly.
|
||||
|
||||
**About the `.vercel/` directory:** A linked project has either:
|
||||
- `.vercel/project.json` — created by `vercel link` (single project linking). Contains `projectId` and `orgId`.
|
||||
- `.vercel/repo.json` — created by `vercel link --repo` (repo-based linking). Contains `orgId`, `remoteName`, and a `projects` array mapping directories to Vercel project IDs.
|
||||
|
||||
Either file means the project is linked. Check for both.
|
||||
|
||||
**Do NOT** use `vercel project inspect`, `vercel ls`, or `vercel link` to detect state in an unlinked directory — without a `.vercel/` config, they will interactively prompt (or with `--yes`, silently link as a side-effect). Only `vercel whoami` is safe to run anywhere.
|
||||
|
||||
## Step 2: Choose a Deploy Method
|
||||
|
||||
### Linked (`.vercel/` exists) + has git remote → Git Push
|
||||
|
||||
This is the ideal state. The project is linked and has git integration.
|
||||
|
||||
1. **Ask the user before pushing.** Never push without explicit approval:
|
||||
```
|
||||
This project is connected to Vercel via git. I can commit and push to
|
||||
trigger a deployment. Want me to proceed?
|
||||
```
|
||||
|
||||
2. **Commit and push:**
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "deploy: <description of changes>"
|
||||
git push
|
||||
```
|
||||
Vercel automatically builds from the push. Non-production branches get preview deployments; the production branch (usually `main`) gets a production deployment.
|
||||
|
||||
3. **Retrieve the preview URL.** If the CLI is authenticated:
|
||||
```bash
|
||||
sleep 5
|
||||
vercel ls --format json
|
||||
```
|
||||
The JSON output has a `deployments` array. Find the latest entry — its `url` field is the preview URL.
|
||||
|
||||
If the CLI is not authenticated, tell the user to check the Vercel dashboard or the commit status checks on their git provider for the preview URL.
|
||||
|
||||
---
|
||||
|
||||
### Linked (`.vercel/` exists) + no git remote → `vercel deploy`
|
||||
|
||||
The project is linked but there's no git repo. Deploy directly with the CLI.
|
||||
|
||||
```bash
|
||||
vercel deploy [path] -y --no-wait
|
||||
```
|
||||
|
||||
Use `--no-wait` so the CLI returns immediately with the deployment URL instead of blocking until the build finishes (builds can take a while). Then check on the deployment status with:
|
||||
|
||||
```bash
|
||||
vercel inspect <deployment-url>
|
||||
```
|
||||
|
||||
For production deploys (only if user explicitly asks):
|
||||
```bash
|
||||
vercel deploy [path] --prod -y --no-wait
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Not linked + CLI is authenticated → Link first, then deploy
|
||||
|
||||
The CLI is working but the project isn't linked yet. This is the opportunity to get the user into the best state.
|
||||
|
||||
1. **Ask the user which team to deploy to.** Present the team slugs from Step 1 as a bulleted list. If there's only one team (or just a personal account), skip this step.
|
||||
|
||||
2. **Once a team is selected, proceed directly to linking.** Tell the user what will happen but do not ask for separate confirmation:
|
||||
```
|
||||
Linking this project to <team name> on Vercel. This will create a Vercel
|
||||
project to deploy to and enable automatic deployments on future git pushes.
|
||||
```
|
||||
|
||||
3. **If a git remote exists**, use repo-based linking with the selected team scope:
|
||||
```bash
|
||||
vercel link --repo --scope <team-slug>
|
||||
```
|
||||
This reads the git remote URL and matches it to existing Vercel projects that deploy from that repo. It creates `.vercel/repo.json`. This is much more reliable than `vercel link` (without `--repo`), which tries to match by directory name and often fails when the local folder and Vercel project are named differently.
|
||||
|
||||
**If there is no git remote**, fall back to standard linking:
|
||||
```bash
|
||||
vercel link --scope <team-slug>
|
||||
```
|
||||
This prompts the user to select or create a project. It creates `.vercel/project.json`.
|
||||
|
||||
4. **Then deploy using the best available method:**
|
||||
- If a git remote exists → commit and push (see git push method above)
|
||||
- If no git remote → `vercel deploy [path] -y --no-wait --scope <team-slug>`, then `vercel inspect <url>` to check status
|
||||
|
||||
---
|
||||
|
||||
### Not linked + CLI not authenticated → Install, auth, link, deploy
|
||||
|
||||
The Vercel CLI isn't set up at all.
|
||||
|
||||
1. **Install the CLI (if not already installed):**
|
||||
```bash
|
||||
npm install -g vercel
|
||||
```
|
||||
|
||||
2. **Authenticate:**
|
||||
```bash
|
||||
vercel login
|
||||
```
|
||||
The user completes auth in their browser. If running in a non-interactive environment where login is not possible, skip to the **no-auth fallback** below.
|
||||
|
||||
3. **Ask which team to deploy to** — present team slugs from `vercel teams list --format json` as a bulleted list. If only one team / personal account, skip. Once selected, proceed immediately.
|
||||
|
||||
4. **Link the project** with the selected team scope (use `--repo` if a git remote exists, plain `vercel link` otherwise):
|
||||
```bash
|
||||
vercel link --repo --scope <team-slug> # if git remote exists
|
||||
vercel link --scope <team-slug> # if no git remote
|
||||
```
|
||||
|
||||
5. **Deploy** using the best available method (git push if remote exists, otherwise `vercel deploy -y --no-wait --scope <team-slug>`, then `vercel inspect <url>` to check status).
|
||||
|
||||
---
|
||||
|
||||
### No-Auth Fallback — claude.ai sandbox
|
||||
|
||||
**When to use:** Last resort when the CLI can't be installed or authenticated in the claude.ai sandbox. This requires no authentication — it returns a **Preview URL** (live site) and a **Claim URL** (transfer to your Vercel account).
|
||||
|
||||
```bash
|
||||
bash /mnt/skills/user/deploy-to-vercel/resources/deploy.sh [path]
|
||||
```
|
||||
|
||||
**Arguments:**
|
||||
- `path` - Directory to deploy, or a `.tgz` file (defaults to current directory)
|
||||
|
||||
**Examples:**
|
||||
```bash
|
||||
# Deploy current directory
|
||||
bash /mnt/skills/user/deploy-to-vercel/resources/deploy.sh
|
||||
|
||||
# Deploy specific project
|
||||
bash /mnt/skills/user/deploy-to-vercel/resources/deploy.sh /path/to/project
|
||||
|
||||
# Deploy existing tarball
|
||||
bash /mnt/skills/user/deploy-to-vercel/resources/deploy.sh /path/to/project.tgz
|
||||
```
|
||||
|
||||
The script auto-detects the framework from `package.json`, packages the project (excluding `node_modules`, `.git`, `.env`), uploads it, and waits for the build to complete.
|
||||
|
||||
**Tell the user:** "Your deployment is ready at [previewUrl]. Claim it at [claimUrl] to manage your deployment."
|
||||
|
||||
---
|
||||
|
||||
### No-Auth Fallback — Codex sandbox
|
||||
|
||||
**When to use:** In the Codex sandbox where the CLI may not be authenticated. Codex runs in a sandboxed environment by default — try the CLI first, and fall back to the deploy script if auth fails.
|
||||
|
||||
1. **Check whether the Vercel CLI is installed** (no escalation needed for this check):
|
||||
```bash
|
||||
command -v vercel
|
||||
```
|
||||
|
||||
2. **If `vercel` is installed**, try deploying with the CLI:
|
||||
```bash
|
||||
vercel deploy [path] -y --no-wait
|
||||
```
|
||||
|
||||
3. **If `vercel` is not installed, or the CLI fails with "No existing credentials found"**, use the fallback script:
|
||||
```bash
|
||||
skill_dir="<path-to-skill>"
|
||||
|
||||
# Deploy current directory
|
||||
bash "$skill_dir/resources/deploy-codex.sh"
|
||||
|
||||
# Deploy specific project
|
||||
bash "$skill_dir/resources/deploy-codex.sh" /path/to/project
|
||||
|
||||
# Deploy existing tarball
|
||||
bash "$skill_dir/resources/deploy-codex.sh" /path/to/project.tgz
|
||||
```
|
||||
|
||||
The script handles framework detection, packaging, and deployment. It waits for the build to complete and returns JSON with `previewUrl` and `claimUrl`.
|
||||
|
||||
**Tell the user:** "Your deployment is ready at [previewUrl]. Claim it at [claimUrl] to manage your deployment."
|
||||
|
||||
**Escalated network access:** Only escalate the actual deploy command if sandboxing blocks the network call (`sandbox_permissions=require_escalated`). Do **not** escalate the `command -v vercel` check.
|
||||
|
||||
---
|
||||
|
||||
## Agent-Specific Notes
|
||||
|
||||
### Claude Code / terminal-based agents
|
||||
|
||||
You have full shell access. Do NOT use the `/mnt/skills/` path. Follow the decision flow above using the CLI directly.
|
||||
|
||||
For the no-auth fallback, run the deploy script from the skill's installed location:
|
||||
```bash
|
||||
bash ~/.claude/skills/deploy-to-vercel/resources/deploy.sh [path]
|
||||
```
|
||||
The path may vary depending on where the user installed the skill.
|
||||
|
||||
### Sandboxed environments (claude.ai)
|
||||
|
||||
You likely cannot run `vercel login` or `git push`. Go directly to the **no-auth fallback — claude.ai sandbox**.
|
||||
|
||||
### Codex
|
||||
|
||||
Codex runs in a sandbox. Check if the CLI is available first, then fall back to the deploy script. Go to the **no-auth fallback — Codex sandbox**.
|
||||
|
||||
---
|
||||
|
||||
## Output
|
||||
|
||||
Always show the user the deployment URL.
|
||||
|
||||
- **Git push:** Use `vercel ls --format json` to find the preview URL. If the CLI isn't authenticated, tell the user to check the Vercel dashboard or commit status checks.
|
||||
- **CLI deploy:** Show the URL returned by `vercel deploy --no-wait`. Use `vercel inspect <url>` to check build status and report it to the user.
|
||||
- **No-auth fallback:** Show both the preview URL and the claim URL:
|
||||
```
|
||||
Deployment successful!
|
||||
|
||||
Preview URL: https://my-app-abc123.vercel.app
|
||||
Claim URL: https://vercel.com/claim-deployment?code=...
|
||||
|
||||
View your site at the Preview URL.
|
||||
To transfer this deployment to your Vercel account, visit the Claim URL.
|
||||
```
|
||||
|
||||
**Do not** curl or fetch the deployed URL to verify it works. Just return the link.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Network Egress Error (claude.ai)
|
||||
|
||||
If deployment fails due to network restrictions on claude.ai, tell the user:
|
||||
|
||||
```
|
||||
Deployment failed due to network restrictions. To fix this:
|
||||
|
||||
1. Go to https://claude.ai/settings/capabilities
|
||||
2. Add *.vercel.com to the allowed domains
|
||||
3. Try deploying again
|
||||
```
|
||||
|
||||
### Escalated Network Access (Codex / sandboxed environments)
|
||||
|
||||
If deployment fails due to network issues (timeouts, DNS errors, connection resets) in a sandboxed environment, rerun with escalated permissions (`sandbox_permissions=require_escalated`). Do not escalate the initial CLI availability check — only escalate the actual deploy command.
|
||||
|
||||
Example guidance to the user:
|
||||
```
|
||||
The deploy needs escalated network access to deploy to Vercel. I can rerun
|
||||
the command with escalated permissions — want me to proceed?
|
||||
```
|
||||
|
||||
### CLI Auth Failure
|
||||
|
||||
If `vercel login` or `vercel deploy` fails with authentication errors, fall back to the no-auth deploy script (claude.ai or Codex variant, depending on the environment).
|
||||
@@ -1,301 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Vercel Deployment Script for Codex (via claimable deploy endpoint)
|
||||
# Usage: ./deploy-codex.sh [project-path]
|
||||
# Returns: JSON with previewUrl, claimUrl, deploymentId, projectId
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
DEPLOY_ENDPOINT="https://codex-deploy-skills.vercel.sh/api/deploy"
|
||||
|
||||
# Detect framework from package.json
|
||||
detect_framework() {
|
||||
local pkg_json="$1"
|
||||
|
||||
if [ ! -f "$pkg_json" ]; then
|
||||
echo "null"
|
||||
return
|
||||
fi
|
||||
|
||||
local content=$(cat "$pkg_json")
|
||||
|
||||
# Helper to check if a package exists in dependencies or devDependencies.
|
||||
# Use exact matching by default, with a separate prefix matcher for scoped
|
||||
# package families like "@remix-run/".
|
||||
has_dep_exact() {
|
||||
echo "$content" | grep -q "\"$1\""
|
||||
}
|
||||
|
||||
has_dep_prefix() {
|
||||
echo "$content" | grep -q "\"$1"
|
||||
}
|
||||
|
||||
# Order matters - check more specific frameworks first
|
||||
|
||||
# Blitz
|
||||
if has_dep_exact "blitz"; then echo "blitzjs"; return; fi
|
||||
|
||||
# Next.js
|
||||
if has_dep_exact "next"; then echo "nextjs"; return; fi
|
||||
|
||||
# Gatsby
|
||||
if has_dep_exact "gatsby"; then echo "gatsby"; return; fi
|
||||
|
||||
# Remix
|
||||
if has_dep_prefix "@remix-run/"; then echo "remix"; return; fi
|
||||
|
||||
# React Router (v7 framework mode)
|
||||
if has_dep_prefix "@react-router/"; then echo "react-router"; return; fi
|
||||
|
||||
# TanStack Start
|
||||
if has_dep_exact "@tanstack/start"; then echo "tanstack-start"; return; fi
|
||||
|
||||
# Astro
|
||||
if has_dep_exact "astro"; then echo "astro"; return; fi
|
||||
|
||||
# Hydrogen (Shopify)
|
||||
if has_dep_exact "@shopify/hydrogen"; then echo "hydrogen"; return; fi
|
||||
|
||||
# SvelteKit
|
||||
if has_dep_exact "@sveltejs/kit"; then echo "sveltekit-1"; return; fi
|
||||
|
||||
# Svelte (standalone)
|
||||
if has_dep_exact "svelte"; then echo "svelte"; return; fi
|
||||
|
||||
# Nuxt
|
||||
if has_dep_exact "nuxt"; then echo "nuxtjs"; return; fi
|
||||
|
||||
# Vue with Vitepress
|
||||
if has_dep_exact "vitepress"; then echo "vitepress"; return; fi
|
||||
|
||||
# Vue with Vuepress
|
||||
if has_dep_exact "vuepress"; then echo "vuepress"; return; fi
|
||||
|
||||
# Gridsome
|
||||
if has_dep_exact "gridsome"; then echo "gridsome"; return; fi
|
||||
|
||||
# SolidStart
|
||||
if has_dep_exact "@solidjs/start"; then echo "solidstart-1"; return; fi
|
||||
|
||||
# Docusaurus
|
||||
if has_dep_exact "@docusaurus/core"; then echo "docusaurus-2"; return; fi
|
||||
|
||||
# RedwoodJS
|
||||
if has_dep_prefix "@redwoodjs/"; then echo "redwoodjs"; return; fi
|
||||
|
||||
# Hexo
|
||||
if has_dep_exact "hexo"; then echo "hexo"; return; fi
|
||||
|
||||
# Eleventy
|
||||
if has_dep_exact "@11ty/eleventy"; then echo "eleventy"; return; fi
|
||||
|
||||
# Angular / Ionic Angular
|
||||
if has_dep_exact "@ionic/angular"; then echo "ionic-angular"; return; fi
|
||||
if has_dep_exact "@angular/core"; then echo "angular"; return; fi
|
||||
|
||||
# Ionic React
|
||||
if has_dep_exact "@ionic/react"; then echo "ionic-react"; return; fi
|
||||
|
||||
# Create React App
|
||||
if has_dep_exact "react-scripts"; then echo "create-react-app"; return; fi
|
||||
|
||||
# Ember
|
||||
if has_dep_exact "ember-cli" || has_dep_exact "ember-source"; then echo "ember"; return; fi
|
||||
|
||||
# Dojo
|
||||
if has_dep_exact "@dojo/framework"; then echo "dojo"; return; fi
|
||||
|
||||
# Polymer
|
||||
if has_dep_prefix "@polymer/"; then echo "polymer"; return; fi
|
||||
|
||||
# Preact
|
||||
if has_dep_exact "preact"; then echo "preact"; return; fi
|
||||
|
||||
# Stencil
|
||||
if has_dep_exact "@stencil/core"; then echo "stencil"; return; fi
|
||||
|
||||
# UmiJS
|
||||
if has_dep_exact "umi"; then echo "umijs"; return; fi
|
||||
|
||||
# Sapper (legacy Svelte)
|
||||
if has_dep_exact "sapper"; then echo "sapper"; return; fi
|
||||
|
||||
# Saber
|
||||
if has_dep_exact "saber"; then echo "saber"; return; fi
|
||||
|
||||
# Sanity
|
||||
if has_dep_exact "sanity"; then echo "sanity-v3"; return; fi
|
||||
if has_dep_prefix "@sanity/"; then echo "sanity"; return; fi
|
||||
|
||||
# Storybook
|
||||
if has_dep_prefix "@storybook/"; then echo "storybook"; return; fi
|
||||
|
||||
# NestJS
|
||||
if has_dep_exact "@nestjs/core"; then echo "nestjs"; return; fi
|
||||
|
||||
# Elysia
|
||||
if has_dep_exact "elysia"; then echo "elysia"; return; fi
|
||||
|
||||
# Hono
|
||||
if has_dep_exact "hono"; then echo "hono"; return; fi
|
||||
|
||||
# Fastify
|
||||
if has_dep_exact "fastify"; then echo "fastify"; return; fi
|
||||
|
||||
# h3
|
||||
if has_dep_exact "h3"; then echo "h3"; return; fi
|
||||
|
||||
# Nitro
|
||||
if has_dep_exact "nitropack"; then echo "nitro"; return; fi
|
||||
|
||||
# Express
|
||||
if has_dep_exact "express"; then echo "express"; return; fi
|
||||
|
||||
# Vite (generic - check last among JS frameworks)
|
||||
if has_dep_exact "vite"; then echo "vite"; return; fi
|
||||
|
||||
# Parcel
|
||||
if has_dep_exact "parcel"; then echo "parcel"; return; fi
|
||||
|
||||
# No framework detected
|
||||
echo "null"
|
||||
}
|
||||
|
||||
# Parse arguments
|
||||
INPUT_PATH="${1:-.}"
|
||||
|
||||
# Create temp directory for packaging
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
TARBALL="$TEMP_DIR/project.tgz"
|
||||
STAGING_DIR="$TEMP_DIR/staging"
|
||||
CLEANUP_TEMP=true
|
||||
|
||||
cleanup() {
|
||||
if [ "$CLEANUP_TEMP" = true ]; then
|
||||
rm -rf "$TEMP_DIR"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
echo "Preparing deployment..." >&2
|
||||
|
||||
# Check if input is a .tgz file or a directory
|
||||
FRAMEWORK="null"
|
||||
|
||||
if [ -f "$INPUT_PATH" ] && [[ "$INPUT_PATH" == *.tgz ]]; then
|
||||
# Input is already a tarball, use it directly
|
||||
echo "Using provided tarball..." >&2
|
||||
TARBALL="$INPUT_PATH"
|
||||
CLEANUP_TEMP=false
|
||||
# Can't detect framework from tarball, leave as null
|
||||
elif [ -d "$INPUT_PATH" ]; then
|
||||
# Input is a directory, need to tar it
|
||||
PROJECT_PATH=$(cd "$INPUT_PATH" && pwd)
|
||||
|
||||
# Detect framework from package.json
|
||||
FRAMEWORK=$(detect_framework "$PROJECT_PATH/package.json")
|
||||
|
||||
# Stage files into a temporary directory to avoid mutating the source tree.
|
||||
mkdir -p "$STAGING_DIR"
|
||||
echo "Staging project files..." >&2
|
||||
tar -C "$PROJECT_PATH" \
|
||||
--exclude='node_modules' \
|
||||
--exclude='.git' \
|
||||
--exclude='.env' \
|
||||
--exclude='.env.*' \
|
||||
-cf - . | tar -C "$STAGING_DIR" -xf -
|
||||
|
||||
# Check if this is a static HTML project (no package.json)
|
||||
if [ ! -f "$PROJECT_PATH/package.json" ]; then
|
||||
# Find HTML files in root
|
||||
HTML_FILES=$(find "$STAGING_DIR" -maxdepth 1 -name "*.html" -type f)
|
||||
HTML_COUNT=$(printf '%s\n' "$HTML_FILES" | sed '/^$/d' | wc -l | tr -d '[:space:]')
|
||||
|
||||
# If there's exactly one HTML file and it's not index.html, rename it
|
||||
if [ "$HTML_COUNT" -eq 1 ]; then
|
||||
HTML_FILE=$(echo "$HTML_FILES" | head -1)
|
||||
BASENAME=$(basename "$HTML_FILE")
|
||||
if [ "$BASENAME" != "index.html" ]; then
|
||||
echo "Renaming $BASENAME to index.html..." >&2
|
||||
mv "$HTML_FILE" "$STAGING_DIR/index.html"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Create tarball from the staging directory
|
||||
echo "Creating deployment package..." >&2
|
||||
tar -czf "$TARBALL" -C "$STAGING_DIR" .
|
||||
else
|
||||
echo "Error: Input must be a directory or a .tgz file" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$FRAMEWORK" != "null" ]; then
|
||||
echo "Detected framework: $FRAMEWORK" >&2
|
||||
fi
|
||||
|
||||
# Deploy
|
||||
echo "Deploying..." >&2
|
||||
RESPONSE=$(curl -s -X POST "$DEPLOY_ENDPOINT" -F "file=@$TARBALL" -F "framework=$FRAMEWORK")
|
||||
|
||||
# Check for error in response
|
||||
if echo "$RESPONSE" | grep -q '"error"'; then
|
||||
ERROR_MSG=$(echo "$RESPONSE" | grep -o '"error":"[^"]*"' | cut -d'"' -f4)
|
||||
echo "Error: $ERROR_MSG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract URLs from response
|
||||
PREVIEW_URL=$(echo "$RESPONSE" | grep -o '"previewUrl":"[^"]*"' | cut -d'"' -f4)
|
||||
CLAIM_URL=$(echo "$RESPONSE" | grep -o '"claimUrl":"[^"]*"' | cut -d'"' -f4)
|
||||
|
||||
if [ -z "$PREVIEW_URL" ]; then
|
||||
echo "Error: Could not extract preview URL from response" >&2
|
||||
echo "$RESPONSE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Deployment started. Waiting for build to complete..." >&2
|
||||
echo "Preview URL: $PREVIEW_URL" >&2
|
||||
|
||||
# Poll the preview URL until it returns a non-5xx response (5xx = still building)
|
||||
MAX_ATTEMPTS=60 # 5 minutes max (60 * 5 seconds)
|
||||
ATTEMPT=0
|
||||
|
||||
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
|
||||
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$PREVIEW_URL")
|
||||
|
||||
if [ "$HTTP_STATUS" -eq 200 ]; then
|
||||
echo "" >&2
|
||||
echo "Deployment ready!" >&2
|
||||
break
|
||||
elif [ "$HTTP_STATUS" -ge 500 ]; then
|
||||
# 5xx means still building/deploying
|
||||
echo "Building... (attempt $((ATTEMPT + 1))/$MAX_ATTEMPTS)" >&2
|
||||
sleep 5
|
||||
ATTEMPT=$((ATTEMPT + 1))
|
||||
elif [ "$HTTP_STATUS" -ge 400 ] && [ "$HTTP_STATUS" -lt 500 ]; then
|
||||
# 4xx might be an error or the app itself returns 4xx - it's responding
|
||||
echo "" >&2
|
||||
echo "Deployment ready (returned $HTTP_STATUS)!" >&2
|
||||
break
|
||||
else
|
||||
# Any other status, assume it's ready
|
||||
echo "" >&2
|
||||
echo "Deployment ready!" >&2
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
|
||||
echo "" >&2
|
||||
echo "Warning: Timed out waiting for deployment, but it may still be building." >&2
|
||||
fi
|
||||
|
||||
echo "" >&2
|
||||
echo "Preview URL: $PREVIEW_URL" >&2
|
||||
echo "Claim URL: $CLAIM_URL" >&2
|
||||
echo "" >&2
|
||||
|
||||
# Output JSON for programmatic use
|
||||
echo "$RESPONSE"
|
||||
@@ -1,301 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Vercel Deployment Script (via claimable deploy endpoint)
|
||||
# Usage: ./deploy.sh [project-path]
|
||||
# Returns: JSON with previewUrl, claimUrl, deploymentId, projectId
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
DEPLOY_ENDPOINT="https://claude-skills-deploy.vercel.com/api/deploy"
|
||||
|
||||
# Detect framework from package.json
|
||||
detect_framework() {
|
||||
local pkg_json="$1"
|
||||
|
||||
if [ ! -f "$pkg_json" ]; then
|
||||
echo "null"
|
||||
return
|
||||
fi
|
||||
|
||||
local content=$(cat "$pkg_json")
|
||||
|
||||
# Helper to check if a package exists in dependencies or devDependencies.
|
||||
# Use exact matching by default, with a separate prefix matcher for scoped
|
||||
# package families like "@remix-run/".
|
||||
has_dep_exact() {
|
||||
echo "$content" | grep -q "\"$1\""
|
||||
}
|
||||
|
||||
has_dep_prefix() {
|
||||
echo "$content" | grep -q "\"$1"
|
||||
}
|
||||
|
||||
# Order matters - check more specific frameworks first
|
||||
|
||||
# Blitz
|
||||
if has_dep_exact "blitz"; then echo "blitzjs"; return; fi
|
||||
|
||||
# Next.js
|
||||
if has_dep_exact "next"; then echo "nextjs"; return; fi
|
||||
|
||||
# Gatsby
|
||||
if has_dep_exact "gatsby"; then echo "gatsby"; return; fi
|
||||
|
||||
# Remix
|
||||
if has_dep_prefix "@remix-run/"; then echo "remix"; return; fi
|
||||
|
||||
# React Router (v7 framework mode)
|
||||
if has_dep_prefix "@react-router/"; then echo "react-router"; return; fi
|
||||
|
||||
# TanStack Start
|
||||
if has_dep_exact "@tanstack/start"; then echo "tanstack-start"; return; fi
|
||||
|
||||
# Astro
|
||||
if has_dep_exact "astro"; then echo "astro"; return; fi
|
||||
|
||||
# Hydrogen (Shopify)
|
||||
if has_dep_exact "@shopify/hydrogen"; then echo "hydrogen"; return; fi
|
||||
|
||||
# SvelteKit
|
||||
if has_dep_exact "@sveltejs/kit"; then echo "sveltekit-1"; return; fi
|
||||
|
||||
# Svelte (standalone)
|
||||
if has_dep_exact "svelte"; then echo "svelte"; return; fi
|
||||
|
||||
# Nuxt
|
||||
if has_dep_exact "nuxt"; then echo "nuxtjs"; return; fi
|
||||
|
||||
# Vue with Vitepress
|
||||
if has_dep_exact "vitepress"; then echo "vitepress"; return; fi
|
||||
|
||||
# Vue with Vuepress
|
||||
if has_dep_exact "vuepress"; then echo "vuepress"; return; fi
|
||||
|
||||
# Gridsome
|
||||
if has_dep_exact "gridsome"; then echo "gridsome"; return; fi
|
||||
|
||||
# SolidStart
|
||||
if has_dep_exact "@solidjs/start"; then echo "solidstart-1"; return; fi
|
||||
|
||||
# Docusaurus
|
||||
if has_dep_exact "@docusaurus/core"; then echo "docusaurus-2"; return; fi
|
||||
|
||||
# RedwoodJS
|
||||
if has_dep_prefix "@redwoodjs/"; then echo "redwoodjs"; return; fi
|
||||
|
||||
# Hexo
|
||||
if has_dep_exact "hexo"; then echo "hexo"; return; fi
|
||||
|
||||
# Eleventy
|
||||
if has_dep_exact "@11ty/eleventy"; then echo "eleventy"; return; fi
|
||||
|
||||
# Angular / Ionic Angular
|
||||
if has_dep_exact "@ionic/angular"; then echo "ionic-angular"; return; fi
|
||||
if has_dep_exact "@angular/core"; then echo "angular"; return; fi
|
||||
|
||||
# Ionic React
|
||||
if has_dep_exact "@ionic/react"; then echo "ionic-react"; return; fi
|
||||
|
||||
# Create React App
|
||||
if has_dep_exact "react-scripts"; then echo "create-react-app"; return; fi
|
||||
|
||||
# Ember
|
||||
if has_dep_exact "ember-cli" || has_dep_exact "ember-source"; then echo "ember"; return; fi
|
||||
|
||||
# Dojo
|
||||
if has_dep_exact "@dojo/framework"; then echo "dojo"; return; fi
|
||||
|
||||
# Polymer
|
||||
if has_dep_prefix "@polymer/"; then echo "polymer"; return; fi
|
||||
|
||||
# Preact
|
||||
if has_dep_exact "preact"; then echo "preact"; return; fi
|
||||
|
||||
# Stencil
|
||||
if has_dep_exact "@stencil/core"; then echo "stencil"; return; fi
|
||||
|
||||
# UmiJS
|
||||
if has_dep_exact "umi"; then echo "umijs"; return; fi
|
||||
|
||||
# Sapper (legacy Svelte)
|
||||
if has_dep_exact "sapper"; then echo "sapper"; return; fi
|
||||
|
||||
# Saber
|
||||
if has_dep_exact "saber"; then echo "saber"; return; fi
|
||||
|
||||
# Sanity
|
||||
if has_dep_exact "sanity"; then echo "sanity-v3"; return; fi
|
||||
if has_dep_prefix "@sanity/"; then echo "sanity"; return; fi
|
||||
|
||||
# Storybook
|
||||
if has_dep_prefix "@storybook/"; then echo "storybook"; return; fi
|
||||
|
||||
# NestJS
|
||||
if has_dep_exact "@nestjs/core"; then echo "nestjs"; return; fi
|
||||
|
||||
# Elysia
|
||||
if has_dep_exact "elysia"; then echo "elysia"; return; fi
|
||||
|
||||
# Hono
|
||||
if has_dep_exact "hono"; then echo "hono"; return; fi
|
||||
|
||||
# Fastify
|
||||
if has_dep_exact "fastify"; then echo "fastify"; return; fi
|
||||
|
||||
# h3
|
||||
if has_dep_exact "h3"; then echo "h3"; return; fi
|
||||
|
||||
# Nitro
|
||||
if has_dep_exact "nitropack"; then echo "nitro"; return; fi
|
||||
|
||||
# Express
|
||||
if has_dep_exact "express"; then echo "express"; return; fi
|
||||
|
||||
# Vite (generic - check last among JS frameworks)
|
||||
if has_dep_exact "vite"; then echo "vite"; return; fi
|
||||
|
||||
# Parcel
|
||||
if has_dep_exact "parcel"; then echo "parcel"; return; fi
|
||||
|
||||
# No framework detected
|
||||
echo "null"
|
||||
}
|
||||
|
||||
# Parse arguments
|
||||
INPUT_PATH="${1:-.}"
|
||||
|
||||
# Create temp directory for packaging
|
||||
TEMP_DIR=$(mktemp -d)
|
||||
TARBALL="$TEMP_DIR/project.tgz"
|
||||
STAGING_DIR="$TEMP_DIR/staging"
|
||||
CLEANUP_TEMP=true
|
||||
|
||||
cleanup() {
|
||||
if [ "$CLEANUP_TEMP" = true ]; then
|
||||
rm -rf "$TEMP_DIR"
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
echo "Preparing deployment..." >&2
|
||||
|
||||
# Check if input is a .tgz file or a directory
|
||||
FRAMEWORK="null"
|
||||
|
||||
if [ -f "$INPUT_PATH" ] && [[ "$INPUT_PATH" == *.tgz ]]; then
|
||||
# Input is already a tarball, use it directly
|
||||
echo "Using provided tarball..." >&2
|
||||
TARBALL="$INPUT_PATH"
|
||||
CLEANUP_TEMP=false
|
||||
# Can't detect framework from tarball, leave as null
|
||||
elif [ -d "$INPUT_PATH" ]; then
|
||||
# Input is a directory, need to tar it
|
||||
PROJECT_PATH=$(cd "$INPUT_PATH" && pwd)
|
||||
|
||||
# Detect framework from package.json
|
||||
FRAMEWORK=$(detect_framework "$PROJECT_PATH/package.json")
|
||||
|
||||
# Stage files into a temporary directory to avoid mutating the source tree.
|
||||
mkdir -p "$STAGING_DIR"
|
||||
echo "Staging project files..." >&2
|
||||
tar -C "$PROJECT_PATH" \
|
||||
--exclude='node_modules' \
|
||||
--exclude='.git' \
|
||||
--exclude='.env' \
|
||||
--exclude='.env.*' \
|
||||
-cf - . | tar -C "$STAGING_DIR" -xf -
|
||||
|
||||
# Check if this is a static HTML project (no package.json)
|
||||
if [ ! -f "$PROJECT_PATH/package.json" ]; then
|
||||
# Find HTML files in root
|
||||
HTML_FILES=$(find "$STAGING_DIR" -maxdepth 1 -name "*.html" -type f)
|
||||
HTML_COUNT=$(printf '%s\n' "$HTML_FILES" | sed '/^$/d' | wc -l | tr -d '[:space:]')
|
||||
|
||||
# If there's exactly one HTML file and it's not index.html, rename it
|
||||
if [ "$HTML_COUNT" -eq 1 ]; then
|
||||
HTML_FILE=$(echo "$HTML_FILES" | head -1)
|
||||
BASENAME=$(basename "$HTML_FILE")
|
||||
if [ "$BASENAME" != "index.html" ]; then
|
||||
echo "Renaming $BASENAME to index.html..." >&2
|
||||
mv "$HTML_FILE" "$STAGING_DIR/index.html"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
# Create tarball from the staging directory
|
||||
echo "Creating deployment package..." >&2
|
||||
tar -czf "$TARBALL" -C "$STAGING_DIR" .
|
||||
else
|
||||
echo "Error: Input must be a directory or a .tgz file" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$FRAMEWORK" != "null" ]; then
|
||||
echo "Detected framework: $FRAMEWORK" >&2
|
||||
fi
|
||||
|
||||
# Deploy
|
||||
echo "Deploying..." >&2
|
||||
RESPONSE=$(curl -s -X POST "$DEPLOY_ENDPOINT" -F "file=@$TARBALL" -F "framework=$FRAMEWORK")
|
||||
|
||||
# Check for error in response
|
||||
if echo "$RESPONSE" | grep -q '"error"'; then
|
||||
ERROR_MSG=$(echo "$RESPONSE" | grep -o '"error":"[^"]*"' | cut -d'"' -f4)
|
||||
echo "Error: $ERROR_MSG" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Extract URLs from response
|
||||
PREVIEW_URL=$(echo "$RESPONSE" | grep -o '"previewUrl":"[^"]*"' | cut -d'"' -f4)
|
||||
CLAIM_URL=$(echo "$RESPONSE" | grep -o '"claimUrl":"[^"]*"' | cut -d'"' -f4)
|
||||
|
||||
if [ -z "$PREVIEW_URL" ]; then
|
||||
echo "Error: Could not extract preview URL from response" >&2
|
||||
echo "$RESPONSE" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Deployment started. Waiting for build to complete..." >&2
|
||||
echo "Preview URL: $PREVIEW_URL" >&2
|
||||
|
||||
# Poll the preview URL until it returns a non-5xx response (5xx = still building)
|
||||
MAX_ATTEMPTS=60 # 5 minutes max (60 * 5 seconds)
|
||||
ATTEMPT=0
|
||||
|
||||
while [ $ATTEMPT -lt $MAX_ATTEMPTS ]; do
|
||||
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$PREVIEW_URL")
|
||||
|
||||
if [ "$HTTP_STATUS" -eq 200 ]; then
|
||||
echo "" >&2
|
||||
echo "Deployment ready!" >&2
|
||||
break
|
||||
elif [ "$HTTP_STATUS" -ge 500 ]; then
|
||||
# 5xx means still building/deploying
|
||||
echo "Building... (attempt $((ATTEMPT + 1))/$MAX_ATTEMPTS)" >&2
|
||||
sleep 5
|
||||
ATTEMPT=$((ATTEMPT + 1))
|
||||
elif [ "$HTTP_STATUS" -ge 400 ] && [ "$HTTP_STATUS" -lt 500 ]; then
|
||||
# 4xx might be an error or the app itself returns 4xx - it's responding
|
||||
echo "" >&2
|
||||
echo "Deployment ready (returned $HTTP_STATUS)!" >&2
|
||||
break
|
||||
else
|
||||
# Any other status, assume it's ready
|
||||
echo "" >&2
|
||||
echo "Deployment ready!" >&2
|
||||
break
|
||||
fi
|
||||
done
|
||||
|
||||
if [ $ATTEMPT -eq $MAX_ATTEMPTS ]; then
|
||||
echo "" >&2
|
||||
echo "Warning: Timed out waiting for deployment, but it may still be building." >&2
|
||||
fi
|
||||
|
||||
echo "" >&2
|
||||
echo "Preview URL: $PREVIEW_URL" >&2
|
||||
echo "Claim URL: $CLAIM_URL" >&2
|
||||
echo "" >&2
|
||||
|
||||
# Output JSON for programmatic use
|
||||
echo "$RESPONSE"
|
||||
@@ -1,353 +0,0 @@
|
||||
---
|
||||
name: vercel-cli-with-tokens
|
||||
description: Deploy and manage projects on Vercel using token-based authentication. Use when working with Vercel CLI using access tokens rather than interactive login — e.g. "deploy to vercel", "set up vercel", "add environment variables to vercel".
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# Vercel CLI with Tokens
|
||||
|
||||
Deploy and manage projects on Vercel using the CLI with token-based authentication, without relying on `vercel login`.
|
||||
|
||||
## Step 1: Locate the Vercel Token
|
||||
|
||||
Before running any Vercel CLI commands, identify where the token is coming from. Work through these scenarios in order:
|
||||
|
||||
### A) `VERCEL_TOKEN` is already set in the environment
|
||||
|
||||
```bash
|
||||
printenv VERCEL_TOKEN
|
||||
```
|
||||
|
||||
If this returns a value, you're ready. Skip to Step 2.
|
||||
|
||||
### B) Token is in a `.env` file under `VERCEL_TOKEN`
|
||||
|
||||
```bash
|
||||
grep '^VERCEL_TOKEN=' .env 2>/dev/null
|
||||
```
|
||||
|
||||
If found, export it:
|
||||
|
||||
```bash
|
||||
export VERCEL_TOKEN=$(grep '^VERCEL_TOKEN=' .env | cut -d= -f2-)
|
||||
```
|
||||
|
||||
### C) Token is in a `.env` file under a different name
|
||||
|
||||
Look for any variable that looks like a Vercel token (Vercel tokens typically start with `vca_`):
|
||||
|
||||
```bash
|
||||
grep -i 'vercel' .env 2>/dev/null
|
||||
```
|
||||
|
||||
Inspect the output to identify which variable holds the token, then export it as `VERCEL_TOKEN`:
|
||||
|
||||
```bash
|
||||
export VERCEL_TOKEN=$(grep '^<VARIABLE_NAME>=' .env | cut -d= -f2-)
|
||||
```
|
||||
|
||||
### D) No token found — ask the user
|
||||
|
||||
If none of the above yield a token, ask the user to provide one. They can create a Vercel access token at vercel.com/account/tokens.
|
||||
|
||||
---
|
||||
|
||||
**Important:** Once `VERCEL_TOKEN` is exported as an environment variable, the Vercel CLI reads it natively — **do not pass it as a `--token` flag**. Putting secrets in command-line arguments exposes them in shell history and process listings.
|
||||
|
||||
```bash
|
||||
# Bad — token visible in shell history and process listings
|
||||
vercel deploy --token "vca_abc123"
|
||||
|
||||
# Good — CLI reads VERCEL_TOKEN from the environment
|
||||
export VERCEL_TOKEN="vca_abc123"
|
||||
vercel deploy
|
||||
```
|
||||
|
||||
## Step 2: Locate the Project and Team
|
||||
|
||||
Similarly, check for the project ID and team scope. These let the CLI target the right project without needing `vercel link`.
|
||||
|
||||
```bash
|
||||
# Check environment
|
||||
printenv VERCEL_PROJECT_ID
|
||||
printenv VERCEL_ORG_ID
|
||||
|
||||
# Or check .env
|
||||
grep -i 'vercel' .env 2>/dev/null
|
||||
```
|
||||
|
||||
**If you have a project URL** (e.g. `https://vercel.com/my-team/my-project`), extract the team slug:
|
||||
|
||||
```bash
|
||||
# e.g. "my-team" from "https://vercel.com/my-team/my-project"
|
||||
echo "$PROJECT_URL" | sed 's|https://vercel.com/||' | cut -d/ -f1
|
||||
```
|
||||
|
||||
**If you have both `VERCEL_ORG_ID` and `VERCEL_PROJECT_ID` in your environment**, export them — the CLI will use these automatically and skip any `.vercel/` directory:
|
||||
|
||||
```bash
|
||||
export VERCEL_ORG_ID="<org-id>"
|
||||
export VERCEL_PROJECT_ID="<project-id>"
|
||||
```
|
||||
|
||||
Note: `VERCEL_ORG_ID` and `VERCEL_PROJECT_ID` must be set together — setting only one causes an error.
|
||||
|
||||
## CLI Setup
|
||||
|
||||
Ensure the Vercel CLI is installed and up to date:
|
||||
|
||||
```bash
|
||||
npm install -g vercel
|
||||
vercel --version
|
||||
```
|
||||
|
||||
## Deploying a Project
|
||||
|
||||
Always deploy as **preview** unless the user explicitly requests production. Choose a method based on what you have available.
|
||||
|
||||
### Quick Deploy (have project ID — no linking needed)
|
||||
|
||||
When `VERCEL_TOKEN` and `VERCEL_PROJECT_ID` are set in the environment, deploy directly:
|
||||
|
||||
```bash
|
||||
vercel deploy -y --no-wait
|
||||
```
|
||||
|
||||
With a team scope (either via `VERCEL_ORG_ID` or `--scope`):
|
||||
|
||||
```bash
|
||||
vercel deploy --scope <team-slug> -y --no-wait
|
||||
```
|
||||
|
||||
Production (only when explicitly requested):
|
||||
|
||||
```bash
|
||||
vercel deploy --prod --scope <team-slug> -y --no-wait
|
||||
```
|
||||
|
||||
Check status:
|
||||
|
||||
```bash
|
||||
vercel inspect <deployment-url>
|
||||
```
|
||||
|
||||
### Full Deploy Flow (no project ID — need to link)
|
||||
|
||||
Use this when you have a token and team but no pre-existing project ID.
|
||||
|
||||
#### Check project state first
|
||||
|
||||
```bash
|
||||
# Does the project have a git remote?
|
||||
git remote get-url origin 2>/dev/null
|
||||
|
||||
# Is it already linked to a Vercel project?
|
||||
cat .vercel/project.json 2>/dev/null || cat .vercel/repo.json 2>/dev/null
|
||||
```
|
||||
|
||||
#### Link the project
|
||||
|
||||
**With git remote (preferred):**
|
||||
|
||||
```bash
|
||||
vercel link --repo --scope <team-slug> -y
|
||||
```
|
||||
|
||||
Reads the git remote and connects to the matching Vercel project. Creates `.vercel/repo.json`. More reliable than plain `vercel link`, which matches by directory name.
|
||||
|
||||
**Without git remote:**
|
||||
|
||||
```bash
|
||||
vercel link --scope <team-slug> -y
|
||||
```
|
||||
|
||||
Creates `.vercel/project.json`.
|
||||
|
||||
**Link to a specific project by name:**
|
||||
|
||||
```bash
|
||||
vercel link --project <project-name> --scope <team-slug> -y
|
||||
```
|
||||
|
||||
If the project is already linked, check `orgId` in `.vercel/project.json` or `.vercel/repo.json` to verify it matches the intended team.
|
||||
|
||||
#### Deploy after linking
|
||||
|
||||
**A) Git Push Deploy — has git remote (preferred)**
|
||||
|
||||
Git pushes trigger automatic Vercel deployments.
|
||||
|
||||
1. **Ask the user before pushing.** Never push without explicit approval.
|
||||
2. Commit and push:
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "deploy: <description of changes>"
|
||||
git push
|
||||
```
|
||||
3. Vercel builds automatically. Non-production branches get preview deployments.
|
||||
4. Retrieve the deployment URL:
|
||||
```bash
|
||||
sleep 5
|
||||
vercel ls --format json --scope <team-slug>
|
||||
```
|
||||
Find the latest entry in the `deployments` array.
|
||||
|
||||
**B) CLI Deploy — no git remote**
|
||||
|
||||
```bash
|
||||
vercel deploy --scope <team-slug> -y --no-wait
|
||||
```
|
||||
|
||||
Check status:
|
||||
|
||||
```bash
|
||||
vercel inspect <deployment-url>
|
||||
```
|
||||
|
||||
### Deploying from a Remote Repository (code not cloned locally)
|
||||
|
||||
1. Clone the repository:
|
||||
```bash
|
||||
git clone <repo-url>
|
||||
cd <repo-name>
|
||||
```
|
||||
2. Link to Vercel:
|
||||
```bash
|
||||
vercel link --repo --scope <team-slug> -y
|
||||
```
|
||||
3. Deploy via git push (if you have push access) or CLI deploy.
|
||||
|
||||
### About `.vercel/` Directory
|
||||
|
||||
A linked project has either:
|
||||
- `.vercel/project.json` — from `vercel link`. Contains `projectId` and `orgId`.
|
||||
- `.vercel/repo.json` — from `vercel link --repo`. Contains `orgId`, `remoteName`, and a `projects` map.
|
||||
|
||||
Not needed when `VERCEL_ORG_ID` + `VERCEL_PROJECT_ID` are both set in the environment.
|
||||
|
||||
**Do NOT** run `vercel project inspect` or `vercel link` in an unlinked directory to detect state — they will interactively prompt or silently link as a side-effect. `vercel ls` is safe (in an unlinked directory it defaults to showing all deployments for the scope). `vercel whoami` is safe anywhere.
|
||||
|
||||
## Managing Environment Variables
|
||||
|
||||
```bash
|
||||
# Set for all environments
|
||||
echo "value" | vercel env add VAR_NAME --scope <team-slug>
|
||||
|
||||
# Set for a specific environment (production, preview, development)
|
||||
echo "value" | vercel env add VAR_NAME production --scope <team-slug>
|
||||
|
||||
# List environment variables
|
||||
vercel env ls --scope <team-slug>
|
||||
|
||||
# Pull env vars to local .env.local file
|
||||
vercel env pull --scope <team-slug>
|
||||
|
||||
# Remove a variable
|
||||
vercel env rm VAR_NAME --scope <team-slug> -y
|
||||
```
|
||||
|
||||
## Inspecting Deployments
|
||||
|
||||
```bash
|
||||
# List recent deployments
|
||||
vercel ls --format json --scope <team-slug>
|
||||
|
||||
# Inspect a specific deployment
|
||||
vercel inspect <deployment-url>
|
||||
|
||||
# View build logs (requires Vercel CLI v35+)
|
||||
vercel inspect <deployment-url> --logs
|
||||
|
||||
# View runtime request logs (follows live by default; add --no-follow for a one-shot snapshot)
|
||||
vercel logs <deployment-url>
|
||||
```
|
||||
|
||||
## Managing Domains
|
||||
|
||||
```bash
|
||||
# List domains
|
||||
vercel domains ls --scope <team-slug>
|
||||
|
||||
# Add a domain to the project — linked or env-linked directory (1 arg)
|
||||
vercel domains add <domain> --scope <team-slug>
|
||||
|
||||
# Add a domain — unlinked directory (requires <project> positional)
|
||||
vercel domains add <domain> <project> --scope <team-slug>
|
||||
```
|
||||
|
||||
## Stripe Projects Plan Changes
|
||||
|
||||
If this project is managed by Stripe Projects. **Ask the user before running any paid or destructive plan change** — upgrades bill a real card, downgrades remove seats.
|
||||
|
||||
First run `stripe projects status --json` to confirm the Vercel resource's local name. The examples below assume the default (`vercel-plan`); substitute the actual name if it was renamed at `stripe projects add` time.
|
||||
|
||||
- **Upgrade to Pro:** `stripe projects add vercel/pro` (or `stripe projects upgrade vercel-plan pro`)
|
||||
- **Downgrade to Hobby:** `stripe projects downgrade vercel-plan hobby`
|
||||
|
||||
### What Pro gives you
|
||||
|
||||
- $20/month platform fee, includes $20/month of usage credit.
|
||||
- Turbo build machines (30 vCPUs, 60 GB memory) by default for new projects — significantly faster builds than Hobby.
|
||||
- 1 deploying seat + unlimited free Viewer seats (read-only collaborators, preview comments).
|
||||
- Higher included allocations (1 TB Fast Data Transfer, 10M Edge Requests per month).
|
||||
- Paid add-ons available: SAML SSO, HIPAA BAA, Flags Explorer, Observability Plus, Speed Insights, Web Analytics Plus.
|
||||
|
||||
Full details: https://vercel.com/docs/plans/pro-plan
|
||||
|
||||
## Working Agreement
|
||||
|
||||
- **Never pass `VERCEL_TOKEN` as a `--token` flag.** Export it as an environment variable and let the CLI read it natively.
|
||||
- **Check the environment for tokens before asking the user.** Look in the current env and `.env` files first.
|
||||
- **Default to preview deployments.** Only deploy to production when explicitly asked.
|
||||
- **Ask before pushing to git.** Never push commits without the user's approval.
|
||||
- **Do not modify `.vercel/` files directly.** The CLI manages this directory. Reading them (e.g. to verify `orgId`) is fine.
|
||||
- **Do not curl/fetch deployed URLs to verify.** Just return the link to the user.
|
||||
- **Use `--format json`** when structured output will help with follow-up steps.
|
||||
- **Use `-y`** on commands that prompt for confirmation to avoid interactive blocking.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Token not found
|
||||
|
||||
Check the environment and any `.env` files present:
|
||||
|
||||
```bash
|
||||
printenv | grep -i vercel
|
||||
grep -i vercel .env 2>/dev/null
|
||||
```
|
||||
|
||||
### Authentication error
|
||||
|
||||
If the CLI fails with `Authentication required`:
|
||||
- The token may be expired or invalid.
|
||||
- Verify: `vercel whoami` (uses `VERCEL_TOKEN` from environment).
|
||||
- Ask the user for a fresh token.
|
||||
|
||||
### Wrong team
|
||||
|
||||
Verify the scope is correct:
|
||||
|
||||
```bash
|
||||
vercel whoami --scope <team-slug>
|
||||
```
|
||||
|
||||
### Build failure
|
||||
|
||||
Check the build logs:
|
||||
|
||||
```bash
|
||||
vercel inspect <deployment-url> --logs
|
||||
```
|
||||
|
||||
Common causes:
|
||||
- Missing dependencies — ensure `package.json` is complete and committed.
|
||||
- Missing environment variables — add with `vercel env add`.
|
||||
- Framework misconfiguration — check `vercel.json`. Vercel auto-detects frameworks (Next.js, Remix, Vite, etc.) from `package.json`; override with `vercel.json` if detection is wrong.
|
||||
|
||||
### CLI not installed
|
||||
|
||||
```bash
|
||||
npm install -g vercel
|
||||
```
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,60 +0,0 @@
|
||||
# React Composition Patterns
|
||||
|
||||
A structured repository for React composition patterns that scale. These
|
||||
patterns help avoid boolean prop proliferation by using compound components,
|
||||
lifting state, and composing internals.
|
||||
|
||||
## Structure
|
||||
|
||||
- `rules/` - Individual rule files (one per rule)
|
||||
- `_sections.md` - Section metadata (titles, impacts, descriptions)
|
||||
- `_template.md` - Template for creating new rules
|
||||
- `area-description.md` - Individual rule files
|
||||
- `metadata.json` - Document metadata (version, organization, abstract)
|
||||
- **`AGENTS.md`** - Compiled output (generated)
|
||||
|
||||
## Rules
|
||||
|
||||
### Component Architecture (CRITICAL)
|
||||
|
||||
- `architecture-avoid-boolean-props.md` - Don't add boolean props to customize
|
||||
behavior
|
||||
- `architecture-compound-components.md` - Structure as compound components with
|
||||
shared context
|
||||
|
||||
### State Management (HIGH)
|
||||
|
||||
- `state-lift-state.md` - Lift state into provider components
|
||||
- `state-context-interface.md` - Define clear context interfaces
|
||||
(state/actions/meta)
|
||||
- `state-decouple-implementation.md` - Decouple state management from UI
|
||||
|
||||
### Implementation Patterns (MEDIUM)
|
||||
|
||||
- `patterns-children-over-render-props.md` - Prefer children over renderX props
|
||||
- `patterns-explicit-variants.md` - Create explicit component variants
|
||||
|
||||
## Core Principles
|
||||
|
||||
1. **Composition over configuration** — Instead of adding props, let consumers
|
||||
compose
|
||||
2. **Lift your state** — State in providers, not trapped in components
|
||||
3. **Compose your internals** — Subcomponents access context, not props
|
||||
4. **Explicit variants** — Create ThreadComposer, EditComposer, not Composer
|
||||
with isThread
|
||||
|
||||
## Creating a New Rule
|
||||
|
||||
1. Copy `rules/_template.md` to `rules/area-description.md`
|
||||
2. Choose the appropriate area prefix:
|
||||
- `architecture-` for Component Architecture
|
||||
- `state-` for State Management
|
||||
- `patterns-` for Implementation Patterns
|
||||
3. Fill in the frontmatter and content
|
||||
4. Ensure you have clear examples with explanations
|
||||
|
||||
## Impact Levels
|
||||
|
||||
- `CRITICAL` - Foundational patterns, prevents unmaintainable code
|
||||
- `HIGH` - Significant maintainability improvements
|
||||
- `MEDIUM` - Good practices for cleaner code
|
||||
@@ -1,89 +0,0 @@
|
||||
---
|
||||
name: vercel-composition-patterns
|
||||
description:
|
||||
React composition patterns that scale. Use when refactoring components with
|
||||
boolean prop proliferation, building flexible component libraries, or
|
||||
designing reusable APIs. Triggers on tasks involving compound components,
|
||||
render props, context providers, or component architecture. Includes React 19
|
||||
API changes.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: '1.0.0'
|
||||
---
|
||||
|
||||
# React Composition Patterns
|
||||
|
||||
Composition patterns for building flexible, maintainable React components. Avoid
|
||||
boolean prop proliferation by using compound components, lifting state, and
|
||||
composing internals. These patterns make codebases easier for both humans and AI
|
||||
agents to work with as they scale.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
|
||||
- Refactoring components with many boolean props
|
||||
- Building reusable component libraries
|
||||
- Designing flexible component APIs
|
||||
- Reviewing component architecture
|
||||
- Working with compound components or context providers
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
| -------- | ----------------------- | ------ | --------------- |
|
||||
| 1 | Component Architecture | HIGH | `architecture-` |
|
||||
| 2 | State Management | MEDIUM | `state-` |
|
||||
| 3 | Implementation Patterns | MEDIUM | `patterns-` |
|
||||
| 4 | React 19 APIs | MEDIUM | `react19-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Component Architecture (HIGH)
|
||||
|
||||
- `architecture-avoid-boolean-props` - Don't add boolean props to customize
|
||||
behavior; use composition
|
||||
- `architecture-compound-components` - Structure complex components with shared
|
||||
context
|
||||
|
||||
### 2. State Management (MEDIUM)
|
||||
|
||||
- `state-decouple-implementation` - Provider is the only place that knows how
|
||||
state is managed
|
||||
- `state-context-interface` - Define generic interface with state, actions, meta
|
||||
for dependency injection
|
||||
- `state-lift-state` - Move state into provider components for sibling access
|
||||
|
||||
### 3. Implementation Patterns (MEDIUM)
|
||||
|
||||
- `patterns-explicit-variants` - Create explicit variant components instead of
|
||||
boolean modes
|
||||
- `patterns-children-over-render-props` - Use children for composition instead
|
||||
of renderX props
|
||||
|
||||
### 4. React 19 APIs (MEDIUM)
|
||||
|
||||
> **⚠️ React 19+ only.** Skip this section if using React 18 or earlier.
|
||||
|
||||
- `react19-no-forwardref` - Don't use `forwardRef`; use `use()` instead of `useContext()`
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/architecture-avoid-boolean-props.md
|
||||
rules/state-context-interface.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -1,11 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"organization": "Engineering",
|
||||
"date": "January 2026",
|
||||
"abstract": "Composition patterns for building flexible, maintainable React components. Avoid boolean prop proliferation by using compound components, lifting state, and composing internals. These patterns make codebases easier for both humans and AI agents to work with as they scale.",
|
||||
"references": [
|
||||
"https://react.dev",
|
||||
"https://react.dev/learn/passing-data-deeply-with-context",
|
||||
"https://react.dev/reference/react/use"
|
||||
]
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
# Sections
|
||||
|
||||
This file defines all sections, their ordering, impact levels, and descriptions.
|
||||
The section ID (in parentheses) is the filename prefix used to group rules.
|
||||
|
||||
---
|
||||
|
||||
## 1. Component Architecture (architecture)
|
||||
|
||||
**Impact:** HIGH
|
||||
**Description:** Fundamental patterns for structuring components to avoid prop
|
||||
proliferation and enable flexible composition.
|
||||
|
||||
## 2. State Management (state)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Patterns for lifting state and managing shared context across
|
||||
composed components.
|
||||
|
||||
## 3. Implementation Patterns (patterns)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Specific techniques for implementing compound components and
|
||||
context providers.
|
||||
|
||||
## 4. React 19 APIs (react19)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
|
||||
@@ -1,24 +0,0 @@
|
||||
---
|
||||
title: Rule Title Here
|
||||
impact: MEDIUM
|
||||
impactDescription: brief description of impact
|
||||
tags: composition, components
|
||||
---
|
||||
|
||||
## Rule Title Here
|
||||
|
||||
Brief explanation of the rule and why it matters.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```tsx
|
||||
// Bad code example
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```tsx
|
||||
// Good code example
|
||||
```
|
||||
|
||||
Reference: [Link](https://example.com)
|
||||
@@ -1,100 +0,0 @@
|
||||
---
|
||||
title: Avoid Boolean Prop Proliferation
|
||||
impact: CRITICAL
|
||||
impactDescription: prevents unmaintainable component variants
|
||||
tags: composition, props, architecture
|
||||
---
|
||||
|
||||
## Avoid Boolean Prop Proliferation
|
||||
|
||||
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customize
|
||||
component behavior. Each boolean doubles possible states and creates
|
||||
unmaintainable conditional logic. Use composition instead.
|
||||
|
||||
**Incorrect (boolean props create exponential complexity):**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
onSubmit,
|
||||
isThread,
|
||||
channelId,
|
||||
isDMThread,
|
||||
dmId,
|
||||
isEditing,
|
||||
isForwarding,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
<Header />
|
||||
<Input />
|
||||
{isDMThread ? (
|
||||
<AlsoSendToDMField id={dmId} />
|
||||
) : isThread ? (
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
) : null}
|
||||
{isEditing ? (
|
||||
<EditActions />
|
||||
) : isForwarding ? (
|
||||
<ForwardActions />
|
||||
) : (
|
||||
<DefaultActions />
|
||||
)}
|
||||
<Footer onSubmit={onSubmit} />
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (composition eliminates conditionals):**
|
||||
|
||||
```tsx
|
||||
// Channel composer
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Attachments />
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Thread composer - adds "also send to channel" field
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField id={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Edit composer - different footer actions
|
||||
function EditComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about what it renders. We can share internals without
|
||||
sharing a single monolithic parent.
|
||||
@@ -1,112 +0,0 @@
|
||||
---
|
||||
title: Use Compound Components
|
||||
impact: HIGH
|
||||
impactDescription: enables flexible composition without prop drilling
|
||||
tags: composition, compound-components, architecture
|
||||
---
|
||||
|
||||
## Use Compound Components
|
||||
|
||||
Structure complex components as compound components with a shared context. Each
|
||||
subcomponent accesses shared state via context, not props. Consumers compose the
|
||||
pieces they need.
|
||||
|
||||
**Incorrect (monolithic component with render props):**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
showAttachments,
|
||||
showFormatting,
|
||||
showEmojis,
|
||||
}: Props) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{showAttachments && <Attachments />}
|
||||
{renderFooter ? (
|
||||
renderFooter()
|
||||
) : (
|
||||
<Footer>
|
||||
{showFormatting && <Formatting />}
|
||||
{showEmojis && <Emojis />}
|
||||
{renderActions?.()}
|
||||
</Footer>
|
||||
)}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (compound components with shared context):**
|
||||
|
||||
```tsx
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
|
||||
function ComposerProvider({ children, state, actions, meta }: ProviderProps) {
|
||||
return (
|
||||
<ComposerContext value={{ state, actions, meta }}>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta: { inputRef },
|
||||
} = use(ComposerContext)
|
||||
return (
|
||||
<TextInput
|
||||
ref={inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ComposerSubmit() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Send</Button>
|
||||
}
|
||||
|
||||
// Export as compound component
|
||||
const Composer = {
|
||||
Provider: ComposerProvider,
|
||||
Frame: ComposerFrame,
|
||||
Input: ComposerInput,
|
||||
Submit: ComposerSubmit,
|
||||
Header: ComposerHeader,
|
||||
Footer: ComposerFooter,
|
||||
Attachments: ComposerAttachments,
|
||||
Formatting: ComposerFormatting,
|
||||
Emojis: ComposerEmojis,
|
||||
}
|
||||
```
|
||||
|
||||
**Usage:**
|
||||
|
||||
```tsx
|
||||
<Composer.Provider state={state} actions={actions} meta={meta}>
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</Composer.Provider>
|
||||
```
|
||||
|
||||
Consumers explicitly compose exactly what they need. No hidden conditionals. And the state, actions and meta are dependency-injected by a parent provider, allowing multiple usages of the same component structure.
|
||||
-87
@@ -1,87 +0,0 @@
|
||||
---
|
||||
title: Prefer Composing Children Over Render Props
|
||||
impact: MEDIUM
|
||||
impactDescription: cleaner composition, better readability
|
||||
tags: composition, children, render-props
|
||||
---
|
||||
|
||||
## Prefer Children Over Render Props
|
||||
|
||||
Use `children` for composition instead of `renderX` props. Children are more
|
||||
readable, compose naturally, and don't require understanding callback
|
||||
signatures.
|
||||
|
||||
**Incorrect (render props):**
|
||||
|
||||
```tsx
|
||||
function Composer({
|
||||
renderHeader,
|
||||
renderFooter,
|
||||
renderActions,
|
||||
}: {
|
||||
renderHeader?: () => React.ReactNode
|
||||
renderFooter?: () => React.ReactNode
|
||||
renderActions?: () => React.ReactNode
|
||||
}) {
|
||||
return (
|
||||
<form>
|
||||
{renderHeader?.()}
|
||||
<Input />
|
||||
{renderFooter ? renderFooter() : <DefaultFooter />}
|
||||
{renderActions?.()}
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage is awkward and inflexible
|
||||
return (
|
||||
<Composer
|
||||
renderHeader={() => <CustomHeader />}
|
||||
renderFooter={() => (
|
||||
<>
|
||||
<Formatting />
|
||||
<Emojis />
|
||||
</>
|
||||
)}
|
||||
renderActions={() => <SubmitButton />}
|
||||
/>
|
||||
)
|
||||
```
|
||||
|
||||
**Correct (compound components with children):**
|
||||
|
||||
```tsx
|
||||
function ComposerFrame({ children }: { children: React.ReactNode }) {
|
||||
return <form>{children}</form>
|
||||
}
|
||||
|
||||
function ComposerFooter({ children }: { children: React.ReactNode }) {
|
||||
return <footer className='flex'>{children}</footer>
|
||||
}
|
||||
|
||||
// Usage is flexible
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<CustomHeader />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<SubmitButton />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
```
|
||||
|
||||
**When render props are appropriate:**
|
||||
|
||||
```tsx
|
||||
// Render props work well when you need to pass data back
|
||||
<List
|
||||
data={items}
|
||||
renderItem={({ item, index }) => <Item item={item} index={index} />}
|
||||
/>
|
||||
```
|
||||
|
||||
Use render props when the parent needs to provide data or state to the child.
|
||||
Use children when composing static structure.
|
||||
@@ -1,100 +0,0 @@
|
||||
---
|
||||
title: Create Explicit Component Variants
|
||||
impact: MEDIUM
|
||||
impactDescription: self-documenting code, no hidden conditionals
|
||||
tags: composition, variants, architecture
|
||||
---
|
||||
|
||||
## Create Explicit Component Variants
|
||||
|
||||
Instead of one component with many boolean props, create explicit variant
|
||||
components. Each variant composes the pieces it needs. The code documents
|
||||
itself.
|
||||
|
||||
**Incorrect (one component, many modes):**
|
||||
|
||||
```tsx
|
||||
// What does this component actually render?
|
||||
<Composer
|
||||
isThread
|
||||
isEditing={false}
|
||||
channelId='abc'
|
||||
showAttachments
|
||||
showFormatting={false}
|
||||
/>
|
||||
```
|
||||
|
||||
**Correct (explicit variants):**
|
||||
|
||||
```tsx
|
||||
// Immediately clear what this renders
|
||||
<ThreadComposer channelId="abc" />
|
||||
|
||||
// Or
|
||||
<EditMessageComposer messageId="xyz" />
|
||||
|
||||
// Or
|
||||
<ForwardMessageComposer messageId="123" />
|
||||
```
|
||||
|
||||
Each implementation is unique, explicit and self-contained. Yet they can each
|
||||
use shared parts.
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```tsx
|
||||
function ThreadComposer({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ThreadProvider channelId={channelId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<AlsoSendToChannelField channelId={channelId} />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ThreadProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function EditMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<EditMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.CancelEdit />
|
||||
<Composer.SaveEdit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</EditMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ messageId }: { messageId: string }) {
|
||||
return (
|
||||
<ForwardMessageProvider messageId={messageId}>
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
<Composer.Mentions />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
Each variant is explicit about:
|
||||
|
||||
- What provider/state it uses
|
||||
- What UI elements it includes
|
||||
- What actions are available
|
||||
|
||||
No boolean prop combinations to reason about. No impossible states.
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
title: React 19 API Changes
|
||||
impact: MEDIUM
|
||||
impactDescription: cleaner component definitions and context usage
|
||||
tags: react19, refs, context, hooks
|
||||
---
|
||||
|
||||
## React 19 API Changes
|
||||
|
||||
> **⚠️ React 19+ only.** Skip this if you're on React 18 or earlier.
|
||||
|
||||
In React 19, `ref` is now a regular prop (no `forwardRef` wrapper needed), and `use()` replaces `useContext()`.
|
||||
|
||||
**Incorrect (forwardRef in React 19):**
|
||||
|
||||
```tsx
|
||||
const ComposerInput = forwardRef<TextInput, Props>((props, ref) => {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
})
|
||||
```
|
||||
|
||||
**Correct (ref as a regular prop):**
|
||||
|
||||
```tsx
|
||||
function ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) {
|
||||
return <TextInput ref={ref} {...props} />
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (useContext in React 19):**
|
||||
|
||||
```tsx
|
||||
const value = useContext(MyContext)
|
||||
```
|
||||
|
||||
**Correct (use instead of useContext):**
|
||||
|
||||
```tsx
|
||||
const value = use(MyContext)
|
||||
```
|
||||
|
||||
`use()` can also be called conditionally, unlike `useContext()`.
|
||||
@@ -1,191 +0,0 @@
|
||||
---
|
||||
title: Define Generic Context Interfaces for Dependency Injection
|
||||
impact: HIGH
|
||||
impactDescription: enables dependency-injectable state across use-cases
|
||||
tags: composition, context, state, typescript, dependency-injection
|
||||
---
|
||||
|
||||
## Define Generic Context Interfaces for Dependency Injection
|
||||
|
||||
Define a **generic interface** for your component context with three parts:
|
||||
`state`, `actions`, and `meta`. This interface is a contract that any provider
|
||||
can implement—enabling the same UI components to work with completely different
|
||||
state implementations.
|
||||
|
||||
**Core principle:** Lift state, compose internals, make state
|
||||
dependency-injectable.
|
||||
|
||||
**Incorrect (UI coupled to specific state implementation):**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
// Tightly coupled to a specific hook
|
||||
const { input, setInput } = useChannelComposerState()
|
||||
return <TextInput value={input} onChangeText={setInput} />
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (generic interface enables dependency injection):**
|
||||
|
||||
```tsx
|
||||
// Define a GENERIC interface that any provider can implement
|
||||
interface ComposerState {
|
||||
input: string
|
||||
attachments: Attachment[]
|
||||
isSubmitting: boolean
|
||||
}
|
||||
|
||||
interface ComposerActions {
|
||||
update: (updater: (state: ComposerState) => ComposerState) => void
|
||||
submit: () => void
|
||||
}
|
||||
|
||||
interface ComposerMeta {
|
||||
inputRef: React.RefObject<TextInput>
|
||||
}
|
||||
|
||||
interface ComposerContextValue {
|
||||
state: ComposerState
|
||||
actions: ComposerActions
|
||||
meta: ComposerMeta
|
||||
}
|
||||
|
||||
const ComposerContext = createContext<ComposerContextValue | null>(null)
|
||||
```
|
||||
|
||||
**UI components consume the interface, not the implementation:**
|
||||
|
||||
```tsx
|
||||
function ComposerInput() {
|
||||
const {
|
||||
state,
|
||||
actions: { update },
|
||||
meta,
|
||||
} = use(ComposerContext)
|
||||
|
||||
// This component works with ANY provider that implements the interface
|
||||
return (
|
||||
<TextInput
|
||||
ref={meta.inputRef}
|
||||
value={state.input}
|
||||
onChangeText={(text) => update((s) => ({ ...s, input: text }))}
|
||||
/>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers implement the same interface:**
|
||||
|
||||
```tsx
|
||||
// Provider A: Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const inputRef = useRef(null)
|
||||
const submit = useForwardMessage()
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update: setState, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
|
||||
// Provider B: Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }: Props) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<ComposerContext
|
||||
value={{
|
||||
state,
|
||||
actions: { update, submit },
|
||||
meta: { inputRef },
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</ComposerContext>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**The same composed UI works with both:**
|
||||
|
||||
```tsx
|
||||
// Works with ForwardMessageProvider (local state)
|
||||
<ForwardMessageProvider>
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ForwardMessageProvider>
|
||||
|
||||
// Works with ChannelProvider (global synced state)
|
||||
<ChannelProvider channelId="abc">
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Submit />
|
||||
</Composer.Frame>
|
||||
</ChannelProvider>
|
||||
```
|
||||
|
||||
**Custom UI outside the component can access state and actions:**
|
||||
|
||||
The provider boundary is what matters—not the visual nesting. Components that
|
||||
need shared state don't have to be inside the `Composer.Frame`. They just need
|
||||
to be within the provider.
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
{/* The composer UI */}
|
||||
<Composer.Frame>
|
||||
<Composer.Input placeholder="Add a message, if you'd like." />
|
||||
<Composer.Footer>
|
||||
<Composer.Formatting />
|
||||
<Composer.Emojis />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
|
||||
{/* Custom UI OUTSIDE the composer, but INSIDE the provider */}
|
||||
<MessagePreview />
|
||||
|
||||
{/* Actions at the bottom of the dialog */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton />
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
// This button lives OUTSIDE Composer.Frame but can still submit based on its context!
|
||||
function ForwardButton() {
|
||||
const {
|
||||
actions: { submit },
|
||||
} = use(ComposerContext)
|
||||
return <Button onPress={submit}>Forward</Button>
|
||||
}
|
||||
|
||||
// This preview lives OUTSIDE Composer.Frame but can read composer's state!
|
||||
function MessagePreview() {
|
||||
const { state } = use(ComposerContext)
|
||||
return <Preview message={state.input} attachments={state.attachments} />
|
||||
}
|
||||
```
|
||||
|
||||
The `ForwardButton` and `MessagePreview` are not visually inside the composer
|
||||
box, but they can still access its state and actions. This is the power of
|
||||
lifting state into providers.
|
||||
|
||||
The UI is reusable bits you compose together. The state is dependency-injected
|
||||
by the provider. Swap the provider, keep the UI.
|
||||
@@ -1,113 +0,0 @@
|
||||
---
|
||||
title: Decouple State Management from UI
|
||||
impact: MEDIUM
|
||||
impactDescription: enables swapping state implementations without changing UI
|
||||
tags: composition, state, architecture
|
||||
---
|
||||
|
||||
## Decouple State Management from UI
|
||||
|
||||
The provider component should be the only place that knows how state is managed.
|
||||
UI components consume the context interface—they don't know if state comes from
|
||||
useState, Zustand, or a server sync.
|
||||
|
||||
**Incorrect (UI coupled to state implementation):**
|
||||
|
||||
```tsx
|
||||
function ChannelComposer({ channelId }: { channelId: string }) {
|
||||
// UI component knows about global state implementation
|
||||
const state = useGlobalChannelState(channelId)
|
||||
const { submit, updateInput } = useChannelSync(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input
|
||||
value={state.input}
|
||||
onChange={(text) => sync.updateInput(text)}
|
||||
/>
|
||||
<Composer.Submit onPress={() => sync.submit()} />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (state management isolated in provider):**
|
||||
|
||||
```tsx
|
||||
// Provider handles all state management details
|
||||
function ChannelProvider({
|
||||
channelId,
|
||||
children,
|
||||
}: {
|
||||
channelId: string
|
||||
children: React.ReactNode
|
||||
}) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update, submit }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// UI component only knows about the context interface
|
||||
function ChannelComposer() {
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Header />
|
||||
<Composer.Input />
|
||||
<Composer.Footer>
|
||||
<Composer.Submit />
|
||||
</Composer.Footer>
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Usage
|
||||
function Channel({ channelId }: { channelId: string }) {
|
||||
return (
|
||||
<ChannelProvider channelId={channelId}>
|
||||
<ChannelComposer />
|
||||
</ChannelProvider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Different providers, same UI:**
|
||||
|
||||
```tsx
|
||||
// Local state for ephemeral forms
|
||||
function ForwardMessageProvider({ children }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// Global synced state for channels
|
||||
function ChannelProvider({ channelId, children }) {
|
||||
const { state, update, submit } = useGlobalChannel(channelId)
|
||||
|
||||
return (
|
||||
<Composer.Provider state={state} actions={{ update, submit }}>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
The same `Composer.Input` component works with both providers because it only
|
||||
depends on the context interface, not the implementation.
|
||||
@@ -1,125 +0,0 @@
|
||||
---
|
||||
title: Lift State into Provider Components
|
||||
impact: HIGH
|
||||
impactDescription: enables state sharing outside component boundaries
|
||||
tags: composition, state, context, providers
|
||||
---
|
||||
|
||||
## Lift State into Provider Components
|
||||
|
||||
Move state management into dedicated provider components. This allows sibling
|
||||
components outside the main UI to access and modify state without prop drilling
|
||||
or awkward refs.
|
||||
|
||||
**Incorrect (state trapped inside component):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageComposer() {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
|
||||
return (
|
||||
<Composer.Frame>
|
||||
<Composer.Input />
|
||||
<Composer.Footer />
|
||||
</Composer.Frame>
|
||||
)
|
||||
}
|
||||
|
||||
// Problem: How does this button access composer state?
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Needs composer state */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Needs to call submit */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (useEffect to sync state up):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const [input, setInput] = useState('')
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer onInputChange={setInput} />
|
||||
<MessagePreview input={input} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageComposer({ onInputChange }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
useEffect(() => {
|
||||
onInputChange(state.input) // Sync on every change 😬
|
||||
}, [state.input])
|
||||
}
|
||||
```
|
||||
|
||||
**Incorrect (reading state from ref on submit):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageDialog() {
|
||||
const stateRef = useRef(null)
|
||||
return (
|
||||
<Dialog>
|
||||
<ForwardMessageComposer stateRef={stateRef} />
|
||||
<ForwardButton onPress={() => submit(stateRef.current)} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (state lifted to provider):**
|
||||
|
||||
```tsx
|
||||
function ForwardMessageProvider({ children }: { children: React.ReactNode }) {
|
||||
const [state, setState] = useState(initialState)
|
||||
const forwardMessage = useForwardMessage()
|
||||
const inputRef = useRef(null)
|
||||
|
||||
return (
|
||||
<Composer.Provider
|
||||
state={state}
|
||||
actions={{ update: setState, submit: forwardMessage }}
|
||||
meta={{ inputRef }}
|
||||
>
|
||||
{children}
|
||||
</Composer.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardMessageDialog() {
|
||||
return (
|
||||
<ForwardMessageProvider>
|
||||
<Dialog>
|
||||
<ForwardMessageComposer />
|
||||
<MessagePreview /> {/* Custom components can access state and actions */}
|
||||
<DialogActions>
|
||||
<CancelButton />
|
||||
<ForwardButton /> {/* Custom components can access state and actions */}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</ForwardMessageProvider>
|
||||
)
|
||||
}
|
||||
|
||||
function ForwardButton() {
|
||||
const { actions } = use(Composer.Context)
|
||||
return <Button onPress={actions.submit}>Forward</Button>
|
||||
}
|
||||
```
|
||||
|
||||
The ForwardButton lives outside the Composer.Frame but still has access to the
|
||||
submit action because it's within the provider. Even though it's a one-off
|
||||
component, it can still access the composer's state and actions from outside the
|
||||
UI itself.
|
||||
|
||||
**Key insight:** Components that need shared state don't have to be visually
|
||||
nested inside each other—they just need to be within the same provider.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,123 +0,0 @@
|
||||
# React Best Practices
|
||||
|
||||
A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
|
||||
|
||||
## Structure
|
||||
|
||||
- `rules/` - Individual rule files (one per rule)
|
||||
- `_sections.md` - Section metadata (titles, impacts, descriptions)
|
||||
- `_template.md` - Template for creating new rules
|
||||
- `area-description.md` - Individual rule files
|
||||
- `src/` - Build scripts and utilities
|
||||
- `metadata.json` - Document metadata (version, organization, abstract)
|
||||
- __`AGENTS.md`__ - Compiled output (generated)
|
||||
- __`test-cases.json`__ - Test cases for LLM evaluation (generated)
|
||||
|
||||
## Getting Started
|
||||
|
||||
1. Install dependencies:
|
||||
```bash
|
||||
pnpm install
|
||||
```
|
||||
|
||||
2. Build AGENTS.md from rules:
|
||||
```bash
|
||||
pnpm build
|
||||
```
|
||||
|
||||
3. Validate rule files:
|
||||
```bash
|
||||
pnpm validate
|
||||
```
|
||||
|
||||
4. Extract test cases:
|
||||
```bash
|
||||
pnpm extract-tests
|
||||
```
|
||||
|
||||
## Creating a New Rule
|
||||
|
||||
1. Copy `rules/_template.md` to `rules/area-description.md`
|
||||
2. Choose the appropriate area prefix:
|
||||
- `async-` for Eliminating Waterfalls (Section 1)
|
||||
- `bundle-` for Bundle Size Optimization (Section 2)
|
||||
- `server-` for Server-Side Performance (Section 3)
|
||||
- `client-` for Client-Side Data Fetching (Section 4)
|
||||
- `rerender-` for Re-render Optimization (Section 5)
|
||||
- `rendering-` for Rendering Performance (Section 6)
|
||||
- `js-` for JavaScript Performance (Section 7)
|
||||
- `advanced-` for Advanced Patterns (Section 8)
|
||||
3. Fill in the frontmatter and content
|
||||
4. Ensure you have clear examples with explanations
|
||||
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
|
||||
|
||||
## Rule File Structure
|
||||
|
||||
Each rule file should follow this structure:
|
||||
|
||||
```markdown
|
||||
---
|
||||
title: Rule Title Here
|
||||
impact: MEDIUM
|
||||
impactDescription: Optional description
|
||||
tags: tag1, tag2, tag3
|
||||
---
|
||||
|
||||
## Rule Title Here
|
||||
|
||||
Brief explanation of the rule and why it matters.
|
||||
|
||||
**Incorrect (description of what's wrong):**
|
||||
|
||||
```typescript
|
||||
// Bad code example
|
||||
```
|
||||
|
||||
**Correct (description of what's right):**
|
||||
|
||||
```typescript
|
||||
// Good code example
|
||||
```
|
||||
|
||||
Optional explanatory text after examples.
|
||||
|
||||
Reference: [Link](https://example.com)
|
||||
|
||||
## File Naming Convention
|
||||
|
||||
- Files starting with `_` are special (excluded from build)
|
||||
- Rule files: `area-description.md` (e.g., `async-parallel.md`)
|
||||
- Section is automatically inferred from filename prefix
|
||||
- Rules are sorted alphabetically by title within each section
|
||||
- IDs (e.g., 1.1, 1.2) are auto-generated during build
|
||||
|
||||
## Impact Levels
|
||||
|
||||
- `CRITICAL` - Highest priority, major performance gains
|
||||
- `HIGH` - Significant performance improvements
|
||||
- `MEDIUM-HIGH` - Moderate-high gains
|
||||
- `MEDIUM` - Moderate performance improvements
|
||||
- `LOW-MEDIUM` - Low-medium gains
|
||||
- `LOW` - Incremental improvements
|
||||
|
||||
## Scripts
|
||||
|
||||
- `pnpm build` - Compile rules into AGENTS.md
|
||||
- `pnpm validate` - Validate all rule files
|
||||
- `pnpm extract-tests` - Extract test cases for LLM evaluation
|
||||
- `pnpm dev` - Build and validate
|
||||
|
||||
## Contributing
|
||||
|
||||
When adding or modifying rules:
|
||||
|
||||
1. Use the correct filename prefix for your section
|
||||
2. Follow the `_template.md` structure
|
||||
3. Include clear bad/good examples with explanations
|
||||
4. Add appropriate tags
|
||||
5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
|
||||
6. Rules are automatically sorted by title - no need to manage numbers!
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
|
||||
@@ -1,149 +0,0 @@
|
||||
---
|
||||
name: vercel-react-best-practices
|
||||
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
|
||||
license: MIT
|
||||
metadata:
|
||||
author: vercel
|
||||
version: "1.0.0"
|
||||
---
|
||||
|
||||
# Vercel React Best Practices
|
||||
|
||||
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
||||
|
||||
## When to Apply
|
||||
|
||||
Reference these guidelines when:
|
||||
- Writing new React components or Next.js pages
|
||||
- Implementing data fetching (client or server-side)
|
||||
- Reviewing code for performance issues
|
||||
- Refactoring existing React/Next.js code
|
||||
- Optimizing bundle size or load times
|
||||
|
||||
## Rule Categories by Priority
|
||||
|
||||
| Priority | Category | Impact | Prefix |
|
||||
|----------|----------|--------|--------|
|
||||
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
|
||||
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
|
||||
| 3 | Server-Side Performance | HIGH | `server-` |
|
||||
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
||||
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
||||
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
||||
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
||||
| 8 | Advanced Patterns | LOW | `advanced-` |
|
||||
|
||||
## Quick Reference
|
||||
|
||||
### 1. Eliminating Waterfalls (CRITICAL)
|
||||
|
||||
- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
|
||||
- `async-defer-await` - Move await into branches where actually used
|
||||
- `async-parallel` - Use Promise.all() for independent operations
|
||||
- `async-dependencies` - Use better-all for partial dependencies
|
||||
- `async-api-routes` - Start promises early, await late in API routes
|
||||
- `async-suspense-boundaries` - Use Suspense to stream content
|
||||
|
||||
### 2. Bundle Size Optimization (CRITICAL)
|
||||
|
||||
- `bundle-barrel-imports` - Import directly, avoid barrel files
|
||||
- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces
|
||||
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
|
||||
- `bundle-defer-third-party` - Load analytics/logging after hydration
|
||||
- `bundle-conditional` - Load modules only when feature is activated
|
||||
- `bundle-preload` - Preload on hover/focus for perceived speed
|
||||
|
||||
### 3. Server-Side Performance (HIGH)
|
||||
|
||||
- `server-auth-actions` - Authenticate server actions like API routes
|
||||
- `server-cache-react` - Use React.cache() for per-request deduplication
|
||||
- `server-cache-lru` - Use LRU cache for cross-request caching
|
||||
- `server-dedup-props` - Avoid duplicate serialization in RSC props
|
||||
- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
|
||||
- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR
|
||||
- `server-serialization` - Minimize data passed to client components
|
||||
- `server-parallel-fetching` - Restructure components to parallelize fetches
|
||||
- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
|
||||
- `server-after-nonblocking` - Use after() for non-blocking operations
|
||||
|
||||
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
||||
|
||||
- `client-swr-dedup` - Use SWR for automatic request deduplication
|
||||
- `client-event-listeners` - Deduplicate global event listeners
|
||||
- `client-passive-event-listeners` - Use passive listeners for scroll
|
||||
- `client-localstorage-schema` - Version and minimize localStorage data
|
||||
|
||||
### 5. Re-render Optimization (MEDIUM)
|
||||
|
||||
- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
|
||||
- `rerender-memo` - Extract expensive work into memoized components
|
||||
- `rerender-memo-with-default-value` - Hoist default non-primitive props
|
||||
- `rerender-dependencies` - Use primitive dependencies in effects
|
||||
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
|
||||
- `rerender-derived-state-no-effect` - Derive state during render, not effects
|
||||
- `rerender-functional-setstate` - Use functional setState for stable callbacks
|
||||
- `rerender-lazy-state-init` - Pass function to useState for expensive values
|
||||
- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
|
||||
- `rerender-split-combined-hooks` - Split hooks with independent dependencies
|
||||
- `rerender-move-effect-to-event` - Put interaction logic in event handlers
|
||||
- `rerender-transitions` - Use startTransition for non-urgent updates
|
||||
- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
|
||||
- `rerender-use-ref-transient-values` - Use refs for transient frequent values
|
||||
- `rerender-no-inline-components` - Don't define components inside components
|
||||
|
||||
### 6. Rendering Performance (MEDIUM)
|
||||
|
||||
- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
|
||||
- `rendering-content-visibility` - Use content-visibility for long lists
|
||||
- `rendering-hoist-jsx` - Extract static JSX outside components
|
||||
- `rendering-svg-precision` - Reduce SVG coordinate precision
|
||||
- `rendering-hydration-no-flicker` - Use inline script for client-only data
|
||||
- `rendering-hydration-suppress-warning` - Suppress expected mismatches
|
||||
- `rendering-activity` - Use Activity component for show/hide
|
||||
- `rendering-conditional-render` - Use ternary, not && for conditionals
|
||||
- `rendering-usetransition-loading` - Prefer useTransition for loading state
|
||||
- `rendering-resource-hints` - Use React DOM resource hints for preloading
|
||||
- `rendering-script-defer-async` - Use defer or async on script tags
|
||||
|
||||
### 7. JavaScript Performance (LOW-MEDIUM)
|
||||
|
||||
- `js-batch-dom-css` - Group CSS changes via classes or cssText
|
||||
- `js-index-maps` - Build Map for repeated lookups
|
||||
- `js-cache-property-access` - Cache object properties in loops
|
||||
- `js-cache-function-results` - Cache function results in module-level Map
|
||||
- `js-cache-storage` - Cache localStorage/sessionStorage reads
|
||||
- `js-combine-iterations` - Combine multiple filter/map into one loop
|
||||
- `js-length-check-first` - Check array length before expensive comparison
|
||||
- `js-early-exit` - Return early from functions
|
||||
- `js-hoist-regexp` - Hoist RegExp creation outside loops
|
||||
- `js-min-max-loop` - Use loop for min/max instead of sort
|
||||
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
|
||||
- `js-tosorted-immutable` - Use toSorted() for immutability
|
||||
- `js-flatmap-filter` - Use flatMap to map and filter in one pass
|
||||
- `js-request-idle-callback` - Defer non-critical work to browser idle time
|
||||
|
||||
### 8. Advanced Patterns (LOW)
|
||||
|
||||
- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
|
||||
- `advanced-event-handler-refs` - Store event handlers in refs
|
||||
- `advanced-init-once` - Initialize app once per app load
|
||||
- `advanced-use-latest` - useLatest for stable callback refs
|
||||
|
||||
## How to Use
|
||||
|
||||
Read individual rule files for detailed explanations and code examples:
|
||||
|
||||
```
|
||||
rules/async-parallel.md
|
||||
rules/bundle-barrel-imports.md
|
||||
```
|
||||
|
||||
Each rule file contains:
|
||||
- Brief explanation of why it matters
|
||||
- Incorrect code example with explanation
|
||||
- Correct code example with explanation
|
||||
- Additional context and references
|
||||
|
||||
## Full Compiled Document
|
||||
|
||||
For the complete guide with all rules expanded: `AGENTS.md`
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"organization": "Vercel Engineering",
|
||||
"date": "January 2026",
|
||||
"abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",
|
||||
"references": [
|
||||
"https://react.dev",
|
||||
"https://nextjs.org",
|
||||
"https://swr.vercel.app",
|
||||
"https://github.com/shuding/better-all",
|
||||
"https://github.com/isaacs/node-lru-cache",
|
||||
"https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",
|
||||
"https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"
|
||||
]
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
# Sections
|
||||
|
||||
This file defines all sections, their ordering, impact levels, and descriptions.
|
||||
The section ID (in parentheses) is the filename prefix used to group rules.
|
||||
|
||||
---
|
||||
|
||||
## 1. Eliminating Waterfalls (async)
|
||||
|
||||
**Impact:** CRITICAL
|
||||
**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
|
||||
|
||||
## 2. Bundle Size Optimization (bundle)
|
||||
|
||||
**Impact:** CRITICAL
|
||||
**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
|
||||
|
||||
## 3. Server-Side Performance (server)
|
||||
|
||||
**Impact:** HIGH
|
||||
**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
|
||||
|
||||
## 4. Client-Side Data Fetching (client)
|
||||
|
||||
**Impact:** MEDIUM-HIGH
|
||||
**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
|
||||
|
||||
## 5. Re-render Optimization (rerender)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
|
||||
|
||||
## 6. Rendering Performance (rendering)
|
||||
|
||||
**Impact:** MEDIUM
|
||||
**Description:** Optimizing the rendering process reduces the work the browser needs to do.
|
||||
|
||||
## 7. JavaScript Performance (js)
|
||||
|
||||
**Impact:** LOW-MEDIUM
|
||||
**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
|
||||
|
||||
## 8. Advanced Patterns (advanced)
|
||||
|
||||
**Impact:** LOW
|
||||
**Description:** Advanced patterns for specific cases that require careful implementation.
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
title: Rule Title Here
|
||||
impact: MEDIUM
|
||||
impactDescription: Optional description of impact (e.g., "20-50% improvement")
|
||||
tags: tag1, tag2
|
||||
---
|
||||
|
||||
## Rule Title Here
|
||||
|
||||
**Impact: MEDIUM (optional impact description)**
|
||||
|
||||
Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
|
||||
|
||||
**Incorrect (description of what's wrong):**
|
||||
|
||||
```typescript
|
||||
// Bad code example here
|
||||
const bad = example()
|
||||
```
|
||||
|
||||
**Correct (description of what's right):**
|
||||
|
||||
```typescript
|
||||
// Good code example here
|
||||
const good = example()
|
||||
```
|
||||
|
||||
Reference: [Link to documentation or resource](https://example.com)
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
title: Do Not Put Effect Events in Dependency Arrays
|
||||
impact: LOW
|
||||
impactDescription: avoids unnecessary effect re-runs and lint errors
|
||||
tags: advanced, hooks, useEffectEvent, dependencies, effects
|
||||
---
|
||||
|
||||
## Do Not Put Effect Events in Dependency Arrays
|
||||
|
||||
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
|
||||
|
||||
**Incorrect (Effect Event added as a dependency):**
|
||||
|
||||
```tsx
|
||||
import { useEffect, useEffectEvent } from 'react'
|
||||
|
||||
function ChatRoom({ roomId, onConnected }: {
|
||||
roomId: string
|
||||
onConnected: () => void
|
||||
}) {
|
||||
const handleConnected = useEffectEvent(onConnected)
|
||||
|
||||
useEffect(() => {
|
||||
const connection = createConnection(roomId)
|
||||
connection.on('connected', handleConnected)
|
||||
connection.connect()
|
||||
|
||||
return () => connection.disconnect()
|
||||
}, [roomId, handleConnected])
|
||||
}
|
||||
```
|
||||
|
||||
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
|
||||
|
||||
**Correct (depend on reactive values, not the Effect Event):**
|
||||
|
||||
```tsx
|
||||
import { useEffect, useEffectEvent } from 'react'
|
||||
|
||||
function ChatRoom({ roomId, onConnected }: {
|
||||
roomId: string
|
||||
onConnected: () => void
|
||||
}) {
|
||||
const handleConnected = useEffectEvent(onConnected)
|
||||
|
||||
useEffect(() => {
|
||||
const connection = createConnection(roomId)
|
||||
connection.on('connected', handleConnected)
|
||||
connection.connect()
|
||||
|
||||
return () => connection.disconnect()
|
||||
}, [roomId])
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
|
||||
@@ -1,55 +0,0 @@
|
||||
---
|
||||
title: Store Event Handlers in Refs
|
||||
impact: LOW
|
||||
impactDescription: stable subscriptions
|
||||
tags: advanced, hooks, refs, event-handlers, optimization
|
||||
---
|
||||
|
||||
## Store Event Handlers in Refs
|
||||
|
||||
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
||||
|
||||
**Incorrect (re-subscribes on every render):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, handler)
|
||||
return () => window.removeEventListener(event, handler)
|
||||
}, [event, handler])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (stable subscription):**
|
||||
|
||||
```tsx
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const handlerRef = useRef(handler)
|
||||
useEffect(() => {
|
||||
handlerRef.current = handler
|
||||
}, [handler])
|
||||
|
||||
useEffect(() => {
|
||||
const listener = (e) => handlerRef.current(e)
|
||||
window.addEventListener(event, listener)
|
||||
return () => window.removeEventListener(event, listener)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
**Alternative: use `useEffectEvent` if you're on latest React:**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react'
|
||||
|
||||
function useWindowEvent(event: string, handler: (e) => void) {
|
||||
const onEvent = useEffectEvent(handler)
|
||||
|
||||
useEffect(() => {
|
||||
window.addEventListener(event, onEvent)
|
||||
return () => window.removeEventListener(event, onEvent)
|
||||
}, [event])
|
||||
}
|
||||
```
|
||||
|
||||
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
||||
@@ -1,42 +0,0 @@
|
||||
---
|
||||
title: Initialize App Once, Not Per Mount
|
||||
impact: LOW-MEDIUM
|
||||
impactDescription: avoids duplicate init in development
|
||||
tags: initialization, useEffect, app-startup, side-effects
|
||||
---
|
||||
|
||||
## Initialize App Once, Not Per Mount
|
||||
|
||||
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
|
||||
|
||||
**Incorrect (runs twice in dev, re-runs on remount):**
|
||||
|
||||
```tsx
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (once per app load):**
|
||||
|
||||
```tsx
|
||||
let didInit = false
|
||||
|
||||
function Comp() {
|
||||
useEffect(() => {
|
||||
if (didInit) return
|
||||
didInit = true
|
||||
loadFromStorage()
|
||||
checkAuthToken()
|
||||
}, [])
|
||||
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
|
||||
@@ -1,39 +0,0 @@
|
||||
---
|
||||
title: useEffectEvent for Stable Callback Refs
|
||||
impact: LOW
|
||||
impactDescription: prevents effect re-runs
|
||||
tags: advanced, hooks, useEffectEvent, refs, optimization
|
||||
---
|
||||
|
||||
## useEffectEvent for Stable Callback Refs
|
||||
|
||||
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
||||
|
||||
**Incorrect (effect re-runs on every callback change):**
|
||||
|
||||
```tsx
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearch(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query, onSearch])
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (using React's useEffectEvent):**
|
||||
|
||||
```tsx
|
||||
import { useEffectEvent } from 'react';
|
||||
|
||||
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
||||
const [query, setQuery] = useState('')
|
||||
const onSearchEvent = useEffectEvent(onSearch)
|
||||
|
||||
useEffect(() => {
|
||||
const timeout = setTimeout(() => onSearchEvent(query), 300)
|
||||
return () => clearTimeout(timeout)
|
||||
}, [query])
|
||||
}
|
||||
```
|
||||
@@ -1,38 +0,0 @@
|
||||
---
|
||||
title: Prevent Waterfall Chains in API Routes
|
||||
impact: CRITICAL
|
||||
impactDescription: 2-10× improvement
|
||||
tags: api-routes, server-actions, waterfalls, parallelization
|
||||
---
|
||||
|
||||
## Prevent Waterfall Chains in API Routes
|
||||
|
||||
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||||
|
||||
**Incorrect (config waits for auth, data waits for both):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const session = await auth()
|
||||
const config = await fetchConfig()
|
||||
const data = await fetchData(session.user.id)
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
**Correct (auth and config start immediately):**
|
||||
|
||||
```typescript
|
||||
export async function GET(request: Request) {
|
||||
const sessionPromise = auth()
|
||||
const configPromise = fetchConfig()
|
||||
const session = await sessionPromise
|
||||
const [config, data] = await Promise.all([
|
||||
configPromise,
|
||||
fetchData(session.user.id)
|
||||
])
|
||||
return Response.json({ data, config })
|
||||
}
|
||||
```
|
||||
|
||||
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
||||
-37
@@ -1,37 +0,0 @@
|
||||
---
|
||||
title: Check Cheap Conditions Before Async Flags
|
||||
impact: HIGH
|
||||
impactDescription: avoids unnecessary async work when a synchronous guard already fails
|
||||
tags: async, await, feature-flags, short-circuit, conditional
|
||||
---
|
||||
|
||||
## Check Cheap Conditions Before Async Flags
|
||||
|
||||
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
|
||||
|
||||
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
|
||||
|
||||
**Incorrect:**
|
||||
|
||||
```typescript
|
||||
const someFlag = await getFlag()
|
||||
|
||||
if (someFlag && someCondition) {
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
**Correct:**
|
||||
|
||||
```typescript
|
||||
if (someCondition) {
|
||||
const someFlag = await getFlag()
|
||||
if (someFlag) {
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
|
||||
|
||||
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user