Commit ·
cfc59e4
0
Parent(s):
initial commit
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .agents/skills/better-auth-best-practices/SKILL.mdAdded+183
- .agents/skills/hono/SKILL.mdAdded+579
- .agents/skills/shadcn/SKILL.mdAdded+250
- .agents/skills/shadcn/agents/openai.ymlAdded+5
- .agents/skills/shadcn/assets/shadcn-small.pngAdded
- .agents/skills/shadcn/assets/shadcn.pngAdded
- .agents/skills/shadcn/cli.mdAdded+276
- .agents/skills/shadcn/customization.mdAdded+208
- .agents/skills/shadcn/evals/evals.jsonAdded+47
- .agents/skills/shadcn/mcp.mdAdded+94
- .agents/skills/shadcn/rules/base-vs-radix.mdAdded+308
- .agents/skills/shadcn/rules/composition.mdAdded+197
- .agents/skills/shadcn/rules/forms.mdAdded+194
- .agents/skills/shadcn/rules/icons.mdAdded+101
- .agents/skills/shadcn/rules/styling.mdAdded+161
- .agents/skills/turborepo/SKILL.mdAdded+951
- .agents/skills/turborepo/command/turborepo.mdAdded+70
- .agents/skills/turborepo/references/best-practices/RULE.mdAdded+241
- .agents/skills/turborepo/references/best-practices/dependencies.mdAdded+246
- .agents/skills/turborepo/references/best-practices/packages.mdAdded+335
- .agents/skills/turborepo/references/best-practices/structure.mdAdded+297
- .agents/skills/turborepo/references/boundaries/RULE.mdAdded+126
- .agents/skills/turborepo/references/caching/RULE.mdAdded+153
- .agents/skills/turborepo/references/caching/gotchas.mdAdded+190
- .agents/skills/turborepo/references/caching/remote-cache.mdAdded+127
- .agents/skills/turborepo/references/ci/RULE.mdAdded+79
- .agents/skills/turborepo/references/ci/github-actions.mdAdded+162
- .agents/skills/turborepo/references/ci/patterns.mdAdded+145
- .agents/skills/turborepo/references/ci/vercel.mdAdded+103
- .agents/skills/turborepo/references/cli/RULE.mdAdded+100
- .agents/skills/turborepo/references/cli/commands.mdAdded+297
- .agents/skills/turborepo/references/configuration/RULE.mdAdded+235
- .agents/skills/turborepo/references/configuration/global-options.mdAdded+239
- .agents/skills/turborepo/references/configuration/gotchas.mdAdded+368
- .agents/skills/turborepo/references/configuration/tasks.mdAdded+321
- .agents/skills/turborepo/references/environment/RULE.mdAdded+123
- .agents/skills/turborepo/references/environment/gotchas.mdAdded+175
- .agents/skills/turborepo/references/environment/modes.mdAdded+101
- .agents/skills/turborepo/references/filtering/RULE.mdAdded+148
- .agents/skills/turborepo/references/filtering/patterns.mdAdded+152
- .agents/skills/turborepo/references/watch/RULE.mdAdded+99
- .agents/skills/vercel-composition-patterns/AGENTS.mdAdded+917
- .agents/skills/vercel-composition-patterns/README.mdAdded+60
- .agents/skills/vercel-composition-patterns/SKILL.mdAdded+88
- .agents/skills/vercel-composition-patterns/metadata.jsonAdded+11
- .agents/skills/vercel-composition-patterns/rules/_sections.mdAdded+29
- .agents/skills/vercel-composition-patterns/rules/_template.mdAdded+24
- .agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.mdAdded+94
- .agents/skills/vercel-composition-patterns/rules/architecture-compound-components.mdAdded+108
- .agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.mdAdded+84
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183---name: better-auth-best-practicesdescription: Configure Better Auth server and client, set up database adapters, manage sessions, add plugins, and handle environment variables. Use when users mention Better Auth, betterauth, auth.ts, or need to set up TypeScript authentication with email/password, OAuth, or plugin configuration.---
# Better Auth Integration Guide
**Always consult [better-auth.com/docs](https://better-auth.com/docs) for code examples and latest API.**
---
## Setup Workflow
1. Install: `npm install better-auth`2. Set env vars: `BETTER_AUTH_SECRET` and `BETTER_AUTH_URL`3. Create `auth.ts` with database + config4. Create route handler for your framework5. Run `npx @better-auth/cli@latest migrate`6. Verify: call `GET /api/auth/ok` — should return `{ status: "ok" }`
---
## Quick Reference
### Environment Variables
- `BETTER_AUTH_SECRET` - Encryption secret (min 32 chars). Generate: `openssl rand -base64 32`- `BETTER_AUTH_URL` - Base URL (e.g., `https://example.com`)
Only define `baseURL`/`secret` in config if env vars are NOT set.
### File Location
CLI looks for `auth.ts` in: `./`, `./lib`, `./utils`, or under `./src`. Use `--config` for custom path.
### CLI Commands
- `npx @better-auth/cli@latest migrate` - Apply schema (built-in adapter)- `npx @better-auth/cli@latest generate` - Generate schema for Prisma/Drizzle- `npx @better-auth/cli mcp --cursor` - Add MCP to AI tools
**Re-run after adding/changing plugins.**
---
## Core Config Options
| Option | Notes || ------------------ | ---------------------------------------------- || `appName` | Optional display name || `baseURL` | Only if `BETTER_AUTH_URL` not set || `basePath` | Default `/api/auth`. Set `/` for root. || `secret` | Only if `BETTER_AUTH_SECRET` not set || `database` | Required for most features. See adapters docs. || `secondaryStorage` | Redis/KV for sessions & rate limits || `emailAndPassword` | `{ enabled: true }` to activate || `socialProviders` | `{ google: { clientId, clientSecret }, ... }` || `plugins` | Array of plugins || `trustedOrigins` | CSRF whitelist |
---
## Database
**Direct connections:** Pass `pg.Pool`, `mysql2` pool, `better-sqlite3`, or `bun:sqlite` instance.
**ORM adapters:** Import from `better-auth/adapters/drizzle`, `better-auth/adapters/prisma`, `better-auth/adapters/mongodb`.
**Critical:** Better Auth uses adapter model names, NOT underlying table names. If Prisma model is `User` mapping to table `users`, use `modelName: "user"` (Prisma reference), not `"users"`.
---
## Session Management
**Storage priority:**
1. If `secondaryStorage` defined → sessions go there (not DB)2. Set `session.storeSessionInDatabase: true` to also persist to DB3. No database + `cookieCache` → fully stateless mode
**Cookie cache strategies:**
- `compact` (default) - Base64url + HMAC. Smallest.- `jwt` - Standard JWT. Readable but signed.- `jwe` - Encrypted. Maximum security.
**Key options:** `session.expiresIn` (default 7 days), `session.updateAge` (refresh interval), `session.cookieCache.maxAge`, `session.cookieCache.version` (change to invalidate all sessions).
---
## User & Account Config
**User:** `user.modelName`, `user.fields` (column mapping), `user.additionalFields`, `user.changeEmail.enabled` (disabled by default), `user.deleteUser.enabled` (disabled by default).
**Account:** `account.modelName`, `account.accountLinking.enabled`, `account.storeAccountCookie` (for stateless OAuth).
**Required for registration:** `email` and `name` fields.
---
## Email Flows
- `emailVerification.sendVerificationEmail` - Must be defined for verification to work- `emailVerification.sendOnSignUp` / `sendOnSignIn` - Auto-send triggers- `emailAndPassword.sendResetPassword` - Password reset email handler
---
## Security
**In `advanced`:**
- `useSecureCookies` - Force HTTPS cookies- `disableCSRFCheck` - ⚠️ Security risk- `disableOriginCheck` - ⚠️ Security risk- `crossSubDomainCookies.enabled` - Share cookies across subdomains- `ipAddress.ipAddressHeaders` - Custom IP headers for proxies- `database.generateId` - Custom ID generation or `"serial"`/`"uuid"`/`false`
**Rate limiting:** `rateLimit.enabled`, `rateLimit.window`, `rateLimit.max`, `rateLimit.storage` ("memory" | "database" | "secondary-storage").
---
## Hooks
**Endpoint hooks:** `hooks.before` / `hooks.after` - Array of `{ matcher, handler }`. Use `createAuthMiddleware`. Access `ctx.path`, `ctx.context.returned` (after), `ctx.context.session`.
**Database hooks:** `databaseHooks.user.create.before/after`, same for `session`, `account`. Useful for adding default values or post-creation actions.
**Hook context (`ctx.context`):** `session`, `secret`, `authCookies`, `password.hash()`/`verify()`, `adapter`, `internalAdapter`, `generateId()`, `tables`, `baseURL`.
---
## Plugins
**Import from dedicated paths for tree-shaking:**
```import { twoFactor } from "better-auth/plugins/two-factor"```
NOT `from "better-auth/plugins"`.
**Popular plugins:** `twoFactor`, `organization`, `passkey`, `magicLink`, `emailOtp`, `username`, `phoneNumber`, `admin`, `apiKey`, `bearer`, `jwt`, `multiSession`, `sso`, `oauthProvider`, `oidcProvider`, `openAPI`, `genericOAuth`.
Client plugins go in `createAuthClient({ plugins: [...] })`.
---
## Client
Import from: `better-auth/client` (vanilla), `better-auth/react`, `better-auth/vue`, `better-auth/svelte`, `better-auth/solid`.
Key methods: `signUp.email()`, `signIn.email()`, `signIn.social()`, `signOut()`, `useSession()`, `getSession()`, `revokeSession()`, `revokeSessions()`.
---
## Type Safety
Infer types: `typeof auth.$Infer.Session`, `typeof auth.$Infer.Session.user`.
For separate client/server projects: `createAuthClient<typeof auth>()`.
---
## Common Gotchas
1. **Model vs table name** - Config uses ORM model name, not DB table name2. **Plugin schema** - Re-run CLI after adding plugins3. **Secondary storage** - Sessions go there by default, not DB4. **Cookie cache** - Custom session fields NOT cached, always re-fetched5. **Stateless mode** - No DB = session in cookie only, logout on cache expiry6. **Change email flow** - Sends to current email first, then new email
---
## Resources
- [Docs](https://better-auth.com/docs)- [Options Reference](https://better-auth.com/docs/reference/options)- [LLMs.txt](https://better-auth.com/llms.txt)- [GitHub](https://github.com/better-auth/better-auth)- [Init Options Source](https://github.com/better-auth/better-auth/blob/main/packages/core/src/types/init-options.ts)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579---name: honodescription: Use when building Hono web applications or when the user asks about Hono APIs, routing, middleware, JSX, validation, testing, or streaming. TRIGGER when code imports from 'hono' or 'hono/*', or user mentions Hono. Use `npx hono request` to test endpoints.---
# Hono Skill
Build Hono web applications. This skill provides inline API knowledge for AI. Use `npx hono request` to test endpoints. If the `hono-docs` MCP server is configured, prefer its tools for the latest documentation over the inline reference.
## Hono CLI Usage
### Request Testing
Test endpoints without starting an HTTP server. Uses `app.request()` internally.
```bash# GET requestnpx hono request [file] -P /path
# POST request with JSON bodynpx hono request [file] -X POST -P /api/users -d '{"name": "test"}'```
**Note:** Do not pass credentials directly in CLI arguments. Use environment variables for sensitive values. `hono request` does not support Cloudflare Workers bindings (KV, D1, R2, etc.). When bindings are required, use `workers-fetch` instead:
```bashnpx workers-fetch /pathnpx workers-fetch -X POST -H "Content-Type:application/json" -d '{"name":"test"}' /api/users```
---
## Hono API Reference
### App Constructor
```tsimport { Hono } from "hono";
const app = new Hono();
// With TypeScript genericstype Env = { Bindings: { DATABASE: D1Database; KV: KVNamespace }; Variables: { user: User };};const app = new Hono<Env>();```
### Routing Methods
```tsapp.get("/path", handler);app.post("/path", handler);app.put("/path", handler);app.delete("/path", handler);app.patch("/path", handler);app.options("/path", handler);app.all("/path", handler); // all HTTP methodsapp.on("PURGE", "/path", handler); // custom methodapp.on(["PUT", "DELETE"], "/path", handler); // multiple methods```
### Routing Patterns
```ts// Path parametersapp.get("/user/:name", (c) => { const name = c.req.param("name"); return c.json({ name });});
// Multiple paramsapp.get("/posts/:id/comments/:commentId", (c) => { const { id, commentId } = c.req.param();});
// Optional parametersapp.get("/api/animal/:type?", (c) => c.text("Animal!"));
// Wildcardsapp.get("/wild/*/card", (c) => c.text("Wildcard"));
// Regexp constraintsapp.get("/post/:date{[0-9]+}/:title{[a-z]+}", (c) => { const { date, title } = c.req.param();});
// Chained routesapp .get("/endpoint", (c) => c.text("GET")) .post((c) => c.text("POST")) .delete((c) => c.text("DELETE"));```
### Route Grouping
```ts// Using route()const api = new Hono();api.get("/users", (c) => c.json([]));
const app = new Hono();app.route("/api", api); // mounts at /api/users
// Using basePath()const app = new Hono().basePath("/api");app.get("/users", (c) => c.json([])); // GET /api/users```
### Error Handling
```tsapp.notFound((c) => c.json({ message: "Not Found" }, 404));
app.onError((err, c) => { console.error(err); return c.json({ message: "Internal Server Error" }, 500);});```
---
## Context (c)
### Response Methods
```tsc.text("Hello"); // text/plainc.json({ message: "Hello" }); // application/jsonc.html("<h1>Hello</h1>"); // text/htmlc.redirect("/new-path"); // 302 redirectc.redirect("/new-path", 301); // 301 redirectc.body("raw body", 200, headers); // raw responsec.notFound(); // 404 response```
### Headers & Status
```tsc.status(201);c.header("X-Custom", "value");c.header("Cache-Control", "no-store");```
### Variables (request-scoped data)
```ts// In middlewarec.set("user", { id: 1, name: "Alice" });
// In handlerconst user = c.get("user");// orconst user = c.var.user;```
### Environment (Cloudflare Workers)
```tsconst value = await c.env.KV.get("key");const db = c.env.DATABASE;c.executionCtx.waitUntil(promise);```
### Renderer
```tsapp.use(async (c, next) => { c.setRenderer((content) => c.html( <html><body>{content}</body></html> ) ) await next()})
app.get('/', (c) => c.render(<h1>Hello</h1>))```
---
## HonoRequest (c.req)
```tsc.req.param("id"); // path parameterc.req.param(); // all path params as objectc.req.query("page"); // query string parameterc.req.query(); // all query params as objectc.req.queries("tags"); // multiple values: ?tags=A&tags=B → ['A', 'B']c.req.header("Authorization"); // request headerc.req.header(); // all headers (keys are lowercase)
// Body parsingawait c.req.json(); // parse JSON bodyawait c.req.text(); // parse text bodyawait c.req.formData(); // parse as FormDataawait c.req.parseBody(); // parse multipart/form-data or urlencodedawait c.req.arrayBuffer(); // parse as ArrayBufferawait c.req.blob(); // parse as Blob
// Validated data (used with validator middleware)c.req.valid("json");c.req.valid("query");c.req.valid("form");c.req.valid("param");
// Propertiesc.req.url; // full URL stringc.req.path; // pathnamec.req.method; // HTTP methodc.req.raw; // underlying Request object```
---
## Middleware
### Using Built-in Middleware
```tsimport { cors } from "hono/cors";import { logger } from "hono/logger";import { basicAuth } from "hono/basic-auth";import { prettyJSON } from "hono/pretty-json";import { secureHeaders } from "hono/secure-headers";import { etag } from "hono/etag";import { compress } from "hono/compress";import { poweredBy } from "hono/powered-by";import { timing } from "hono/timing";import { cache } from "hono/cache";import { bearerAuth } from "hono/bearer-auth";import { jwt } from "hono/jwt";import { csrf } from "hono/csrf";import { ipRestriction } from "hono/ip-restriction";import { bodyLimit } from "hono/body-limit";import { requestId } from "hono/request-id";import { methodOverride } from "hono/method-override";import { trailingSlash, trimTrailingSlash } from "hono/trailing-slash";
// Registrationapp.use(logger()); // all routesapp.use("/api/*", cors()); // specific pathapp.post("/api/*", basicAuth({ username: "admin", password: "secret" }));```
### Custom Middleware
```ts// Inlineapp.use(async (c, next) => { const start = Date.now(); await next(); const elapsed = Date.now() - start; c.res.headers.set("X-Response-Time", `${elapsed}ms`);});
// Reusable with createMiddlewareimport { createMiddleware } from "hono/factory";
const auth = createMiddleware(async (c, next) => { const token = c.req.header("Authorization"); if (!token) return c.json({ error: "Unauthorized" }, 401); await next();});
app.use("/api/*", auth);```
### Middleware Execution Order
Middleware executes in registration order. `await next()` calls the next middleware/handler, and code after `next()` runs on the way back:
```Request → mw1 before → mw2 before → handler → mw2 after → mw1 after → Response```
```tsapp.use(async (c, next) => { // before handler await next(); // after handler});```
---
## Validation
Validation targets: `json`, `form`, `query`, `header`, `param`, `cookie`.
### Zod Validator
```tsimport { zValidator } from "@hono/zod-validator";import { z } from "zod";
const schema = z.object({ title: z.string().min(1), body: z.string(),});
app.post("/posts", zValidator("json", schema), (c) => { const data = c.req.valid("json"); // fully typed return c.json(data, 201);});```
### Valibot / Standard Schema Validator
```tsimport { sValidator } from "@hono/standard-validator";import * as v from "valibot";
const schema = v.object({ name: v.string(), age: v.number() });
app.post("/users", sValidator("json", schema), (c) => { const data = c.req.valid("json"); return c.json(data, 201);});```
---
## JSX
### Setup
In `tsconfig.json`:
```json{ "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "hono/jsx" }}```
Or use pragma: `/** @jsxImportSource hono/jsx */`
**Important:** Files using JSX must have a `.tsx` extension. Rename `.ts` to `.tsx` or the compiler will fail.
### Components
```tsximport type { PropsWithChildren } from "hono/jsx";
const Layout = (props: PropsWithChildren) => ( <html> <head> <title>My App</title> </head> <body>{props.children}</body> </html>);
const UserCard = ({ name }: { name: string }) => ( <div class="card"> <h2>{name}</h2> </div>);
app.get("/", (c) => { return c.html( <Layout> <UserCard name="Alice" /> </Layout>, );});```
### jsxRenderer Middleware
Use `jsxRenderer` middleware for layouts. See `npx hono docs /docs/middleware/builtin/jsx-renderer` for details.
### Async Components
```tsxconst UserList = async () => { const users = await fetchUsers(); return ( <ul> {users.map((u) => ( <li>{u.name}</li> ))} </ul> );};```
### Fragments
```tsxconst Items = () => ( <> <li>Item 1</li> <li>Item 2</li> </>);```
---
## Streaming
```tsimport { stream, streamText, streamSSE } from "hono/streaming";
// Basic streamapp.get("/stream", (c) => { return stream(c, async (stream) => { stream.onAbort(() => console.log("Aborted")); await stream.write(new Uint8Array([0x48, 0x65])); await stream.pipe(readableStream); });});
// Text streamapp.get("/stream-text", (c) => { return streamText(c, async (stream) => { await stream.writeln("Hello"); await stream.sleep(1000); await stream.write("World"); });});
// Server-Sent Eventsapp.get("/sse", (c) => { return streamSSE(c, async (stream) => { let id = 0; while (true) { await stream.writeSSE({ data: JSON.stringify({ time: new Date().toISOString() }), event: "time-update", id: String(id++), }); await stream.sleep(1000); } });});```
---
## Testing with app.request()
Test endpoints without starting an HTTP server:
```ts// GETconst res = await app.request("/posts");expect(res.status).toBe(200);expect(await res.json()).toEqual({ posts: [] });
// POST with JSONconst res = await app.request("/posts", { method: "POST", body: JSON.stringify({ title: "Hello" }), headers: { "Content-Type": "application/json" },});
// POST with FormDataconst formData = new FormData();formData.append("name", "Alice");const res = await app.request("/users", { method: "POST", body: formData });
// With mock env (Cloudflare Workers bindings)const res = await app.request("/api/data", {}, { KV: mockKV, DATABASE: mockDB });
// Using Request objectconst req = new Request("http://localhost/api", { method: "DELETE" });const res = await app.request(req);```
---
## Hono Client (RPC)
Type-safe API client using shared types between server and client.
**IMPORTANT: Routes MUST be chained for type inference to work. Without chaining, the client cannot infer route types.**
```ts// Server: routes MUST be chained to preserve typesconst route = app .post("/posts", zValidator("json", schema), (c) => { return c.json({ ok: true }, 201); }) .get("/posts", (c) => { return c.json({ posts: [] }); });export type AppType = typeof route;
// Client: use hc() with the exported typeimport { hc } from "hono/client";import type { AppType } from "./server";
const client = hc<AppType>("http://localhost:8787/");const res = await client.posts.$post({ json: { title: "Hello" } });const data = await res.json(); // fully typed```
Type utilities:
```tsimport type { InferRequestType, InferResponseType } from "hono/client";
type ReqType = InferRequestType<typeof client.posts.$post>;type ResType = InferResponseType<typeof client.posts.$post, 200>;```
---
## Helpers
Helpers are utility functions imported from `hono/<helper-name>`:
```tsimport { getConnInfo } from "hono/conninfo";import { getCookie, setCookie, deleteCookie } from "hono/cookie";import { css, Style } from "hono/css";import { createFactory } from "hono/factory";import { html, raw } from "hono/html";import { stream, streamText, streamSSE } from "hono/streaming";import { testClient } from "hono/testing";import { upgradeWebSocket } from "hono/cloudflare-workers"; // or other adapter```
Available helpers: Accepts, Adapter, ConnInfo, Cookie, css, Dev, Factory, html, JWT, Proxy, Route, SSG, Streaming, Testing, WebSocket.
For details, use `npx hono docs /docs/helpers/<helper-name>`.
### Factory
Use `createFactory` to define `Env` once and share it across app, middleware, and handlers:
```tsimport { createFactory } from "hono/factory";
const factory = createFactory<Env>();
// Create app (Env type is inherited)const app = factory.createApp();
// Create middleware (Env type is inherited, no need to pass generics)const mw = factory.createMiddleware(async (c, next) => { await next();});
// Create handlers separately (preserves type inference)const handlers = factory.createHandlers(logger(), (c) => c.json({ message: "Hello" }));app.get("/api", ...handlers);```
---
## Best Practices
- Write handlers inline in route definitions for proper type inference of path params.- Use `app.route()` to organize large apps by feature, not Rails-style controllers.- Use `createFactory()` to share Env type across app, middleware, and handlers.- Use `c.set()`/`c.get()` to pass data between middleware and handlers.- Chain validators for multiple request parts (param + query + json).- Export app type for RPC: `export type AppType = typeof routes`- Use `app.request()` for testing — no server startup needed.
## Adapters
Hono runs on multiple runtimes. The default export works for Cloudflare Workers, Deno, and Bun. For Node.js, use the Node adapter:
```ts// Cloudflare Workers / Deno / Bunexport default app;
// Node.jsimport { serve } from "@hono/node-server";serve(app);```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250---name: shadcndescription: Manages shadcn components and projects — adding, searching, fixing, debugging, styling, and composing UI. Provides project context, component docs, and usage examples. Applies when working with shadcn/ui, component registries, presets, --preset codes, or any project with a components.json file. Also triggers for "shadcn init", "create an app with --preset", or "switch to --preset".user-invocable: falseallowed-tools: Bash(npx shadcn@latest *), Bash(pnpm dlx shadcn@latest *), Bash(bunx --bun shadcn@latest *)---
# shadcn/ui
A framework for building ui, components and design systems. Components are added as source code to the user's project via the CLI.
> **IMPORTANT:** Run all CLI commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest` — based on the project's `packageManager`. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
## Current Project Context
```json!`npx shadcn@latest info --json````
The JSON above contains the project config and installed components. Use `npx shadcn@latest docs <component>` to get documentation and example URLs for any component.
## Principles
1. **Use existing components first.** Use `npx shadcn@latest search` to check registries before writing custom UI. Check community registries too.2. **Compose, don't reinvent.** Settings page = Tabs + Card + form controls. Dashboard = Sidebar + Card + Chart + Table.3. **Use built-in variants before custom styles.** `variant="outline"`, `size="sm"`, etc.4. **Use semantic colors.** `bg-primary`, `text-muted-foreground` — never raw values like `bg-blue-500`.
## Critical Rules
These rules are **always enforced**. Each links to a file with Incorrect/Correct code pairs.
### Styling & Tailwind → [styling.md](./rules/styling.md)
- **`className` for layout, not styling.** Never override component colors or typography.- **No `space-x-*` or `space-y-*`.** Use `flex` with `gap-*`. For vertical stacks, `flex flex-col gap-*`.- **Use `size-*` when width and height are equal.** `size-10` not `w-10 h-10`.- **Use `truncate` shorthand.** Not `overflow-hidden text-ellipsis whitespace-nowrap`.- **No manual `dark:` color overrides.** Use semantic tokens (`bg-background`, `text-muted-foreground`).- **Use `cn()` for conditional classes.** Don't write manual template literal ternaries.- **No manual `z-index` on overlay components.** Dialog, Sheet, Popover, etc. handle their own stacking.
### Forms & Inputs → [forms.md](./rules/forms.md)
- **Forms use `FieldGroup` + `Field`.** Never use raw `div` with `space-y-*` or `grid gap-*` for form layout.- **`InputGroup` uses `InputGroupInput`/`InputGroupTextarea`.** Never raw `Input`/`Textarea` inside `InputGroup`.- **Buttons inside inputs use `InputGroup` + `InputGroupAddon`.**- **Option sets (2–7 choices) use `ToggleGroup`.** Don't loop `Button` with manual active state.- **`FieldSet` + `FieldLegend` for grouping related checkboxes/radios.** Don't use a `div` with a heading.- **Field validation uses `data-invalid` + `aria-invalid`.** `data-invalid` on `Field`, `aria-invalid` on the control. For disabled: `data-disabled` on `Field`, `disabled` on the control.
### Component Structure → [composition.md](./rules/composition.md)
- **Items always inside their Group.** `SelectItem` → `SelectGroup`. `DropdownMenuItem` → `DropdownMenuGroup`. `CommandItem` → `CommandGroup`.- **Use `asChild` (radix) or `render` (base) for custom triggers.** Check `base` field from `npx shadcn@latest info`. → [base-vs-radix.md](./rules/base-vs-radix.md)- **Dialog, Sheet, and Drawer always need a Title.** `DialogTitle`, `SheetTitle`, `DrawerTitle` required for accessibility. Use `className="sr-only"` if visually hidden.- **Use full Card composition.** `CardHeader`/`CardTitle`/`CardDescription`/`CardContent`/`CardFooter`. Don't dump everything in `CardContent`.- **Button has no `isPending`/`isLoading`.** Compose with `Spinner` + `data-icon` + `disabled`.- **`TabsTrigger` must be inside `TabsList`.** Never render triggers directly in `Tabs`.- **`Avatar` always needs `AvatarFallback`.** For when the image fails to load.
### Use Components, Not Custom Markup → [composition.md](./rules/composition.md)
- **Use existing components before custom markup.** Check if a component exists before writing a styled `div`.- **Callouts use `Alert`.** Don't build custom styled divs.- **Empty states use `Empty`.** Don't build custom empty state markup.- **Toast via `sonner`.** Use `toast()` from `sonner`.- **Use `Separator`** instead of `<hr>` or `<div className="border-t">`.- **Use `Skeleton`** for loading placeholders. No custom `animate-pulse` divs.- **Use `Badge`** instead of custom styled spans.
### Icons → [icons.md](./rules/icons.md)
- **Icons in `Button` use `data-icon`.** `data-icon="inline-start"` or `data-icon="inline-end"` on the icon.- **No sizing classes on icons inside components.** Components handle icon sizing via CSS. No `size-4` or `w-4 h-4`.- **Pass icons as objects, not string keys.** `icon={CheckIcon}`, not a string lookup.
### CLI
- **Never decode or fetch preset codes manually.** Pass them directly to `npx shadcn@latest apply --preset <code>` for existing projects, or `npx shadcn@latest init --preset <code>` when initializing.
## Key Patterns
These are the most common patterns that differentiate correct shadcn/ui code. For edge cases, see the linked rule files above.
```tsx// Form layout: FieldGroup + Field, not div + Label.<FieldGroup> <Field> <FieldLabel htmlFor="email">Email</FieldLabel> <Input id="email" /> </Field></FieldGroup>
// Validation: data-invalid on Field, aria-invalid on the control.<Field data-invalid> <FieldLabel>Email</FieldLabel> <Input aria-invalid /> <FieldDescription>Invalid email.</FieldDescription></Field>
// Icons in buttons: data-icon, no sizing classes.<Button> <SearchIcon data-icon="inline-start" /> Search</Button>
// Spacing: gap-*, not space-y-*.<div className="flex flex-col gap-4"> // correct<div className="space-y-4"> // wrong
// Equal dimensions: size-*, not w-* h-*.<Avatar className="size-10"> // correct<Avatar className="w-10 h-10"> // wrong
// Status colors: Badge variants or semantic tokens, not raw colors.<Badge variant="secondary">+20.1%</Badge> // correct<span className="text-emerald-600">+20.1%</span> // wrong```
## Component Selection
| Need | Use || -------------------------- | --------------------------------------------------------------------------------------------------- || Button/action | `Button` with appropriate variant || Form inputs | `Input`, `Select`, `Combobox`, `Switch`, `Checkbox`, `RadioGroup`, `Textarea`, `InputOTP`, `Slider` || Toggle between 2–5 options | `ToggleGroup` + `ToggleGroupItem` || Data display | `Table`, `Card`, `Badge`, `Avatar` || Navigation | `Sidebar`, `NavigationMenu`, `Breadcrumb`, `Tabs`, `Pagination` || Overlays | `Dialog` (modal), `Sheet` (side panel), `Drawer` (bottom sheet), `AlertDialog` (confirmation) || Feedback | `sonner` (toast), `Alert`, `Progress`, `Skeleton`, `Spinner` || Command palette | `Command` inside `Dialog` || Charts | `Chart` (wraps Recharts) || Layout | `Card`, `Separator`, `Resizable`, `ScrollArea`, `Accordion`, `Collapsible` || Empty states | `Empty` || Menus | `DropdownMenu`, `ContextMenu`, `Menubar` || Tooltips/info | `Tooltip`, `HoverCard`, `Popover` |
## Key Fields
The injected project context contains these key fields:
- **`aliases`** → use the actual alias prefix for imports (e.g. `@/`, `~/`), never hardcode.- **`isRSC`** → when `true`, components using `useState`, `useEffect`, event handlers, or browser APIs need `"use client"` at the top of the file. Always reference this field when advising on the directive.- **`tailwindVersion`** → `"v4"` uses `@theme inline` blocks; `"v3"` uses `tailwind.config.js`.- **`tailwindCssFile`** → the global CSS file where custom CSS variables are defined. Always edit this file, never create a new one.- **`style`** → component visual treatment (e.g. `nova`, `vega`).- **`base`** → primitive library (`radix` or `base`). Affects component APIs and available props.- **`iconLibrary`** → determines icon imports. Use `lucide-react` for `lucide`, `@tabler/icons-react` for `tabler`, etc. Never assume `lucide-react`.- **`resolvedPaths`** → exact file-system destinations for components, utils, hooks, etc.- **`framework`** → routing and file conventions (e.g. Next.js App Router vs Vite SPA).- **`packageManager`** → use this for any non-shadcn dependency installs (e.g. `pnpm add date-fns` vs `npm install date-fns`).
See [cli.md — `info` command](./cli.md) for the full field reference.
## Component Docs, Examples, and Usage
Run `npx shadcn@latest docs <component>` to get the URLs for a component's documentation, examples, and API reference. Fetch these URLs to get the actual content.
```bashnpx shadcn@latest docs button dialog select```
**When creating, fixing, debugging, or using a component, always run `npx shadcn@latest docs` and fetch the URLs first.** This ensures you're working with the correct API and usage patterns rather than guessing.
## Workflow
1. **Get project context** — already injected above. Run `npx shadcn@latest info` again if you need to refresh.2. **Check installed components first** — before running `add`, always check the `components` list from project context or list the `resolvedPaths.ui` directory. Don't import components that haven't been added, and don't re-add ones already installed.3. **Find components** — `npx shadcn@latest search`.4. **Get docs and examples** — run `npx shadcn@latest docs <component>` to get URLs, then fetch them. Use `npx shadcn@latest view` to browse registry items you haven't installed. To preview changes to installed components, use `npx shadcn@latest add --diff`.5. **Install or update** — `npx shadcn@latest add`. When updating existing components, use `--dry-run` and `--diff` to preview changes first (see [Updating Components](#updating-components) below).6. **Fix imports in third-party components** — After adding components from community registries (e.g. `@bundui`, `@magicui`), check the added non-UI files for hardcoded import paths like `@/components/ui/...`. These won't match the project's actual aliases. Use `npx shadcn@latest info` to get the correct `ui` alias (e.g. `@workspace/ui/components`) and rewrite the imports accordingly. The CLI rewrites imports for its own UI files, but third-party registry components may use default paths that don't match the project.7. **Review added components** — After adding a component or block from any registry, **always read the added files and verify they are correct**. Check for missing sub-components (e.g. `SelectItem` without `SelectGroup`), missing imports, incorrect composition, or violations of the [Critical Rules](#critical-rules). Also replace any icon imports with the project's `iconLibrary` from the project context (e.g. if the registry item uses `lucide-react` but the project uses `hugeicons`, swap the imports and icon names accordingly). Fix all issues before moving on.8. **Registry must be explicit** — When the user asks to add a block or component, **do not guess the registry**. If no registry is specified (e.g. user says "add a login block" without specifying `@shadcn`, `@tailark`, etc.), ask which registry to use. Never default to a registry on behalf of the user.9. **Switching presets** — Ask the user first: **overwrite**, **partial**, **merge**, or **skip**? - **Overwrite**: `npx shadcn@latest apply --preset <code>`. Overwrites detected components, fonts, and CSS variables. - **Partial**: `npx shadcn@latest apply --preset <code> --only theme,font`. Updates only the selected preset parts without reinstalling UI components. Supported values are `theme` and `font`; comma-separated combinations are allowed. `icon` is intentionally not supported, because icon changes may require full component reinstall and transforms. - **Merge**: `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to list installed components, then for each installed component use `--dry-run` and `--diff` to [smart merge](#updating-components) it individually. - **Skip**: `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS, leaves components as-is. - **Important**: Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.
## Updating Components
When the user asks to update a component from upstream while keeping their local changes, use `--dry-run` and `--diff` to intelligently merge. **NEVER fetch raw files from GitHub manually — always use the CLI.**
1. Run `npx shadcn@latest add <component> --dry-run` to see all files that would be affected.2. For each file, run `npx shadcn@latest add <component> --diff <file>` to see what changed upstream vs local.3. Decide per file based on the diff: - No local changes → safe to overwrite. - Has local changes → read the local file, analyze the diff, and apply upstream updates while preserving local modifications. - User says "just update everything" → use `--overwrite`, but confirm first.4. **Never use `--overwrite` without the user's explicit approval.**
## Quick Reference
```bash# Create a new project.npx shadcn@latest init --name my-app --preset base-novanpx shadcn@latest init --name my-app --preset a2r6bw --template vite
# Create a monorepo project.npx shadcn@latest init --name my-app --preset base-nova --monoreponpx shadcn@latest init --name my-app --preset base-nova --template next --monorepo
# Initialize existing project.npx shadcn@latest init --preset base-novanpx shadcn@latest init --defaults # shortcut: --template=next --preset=nova (base style implied)
# Apply a preset to an existing project.npx shadcn@latest apply --preset a2r6bwnpx shadcn@latest apply a2r6bwnpx shadcn@latest apply --preset a2r6bw --only themenpx shadcn@latest apply --preset a2r6bw --only fontnpx shadcn@latest apply --preset a2r6bw --only theme,font
# Add components.npx shadcn@latest add button card dialognpx shadcn@latest add @magicui/shimmer-buttonnpx shadcn@latest add --all
# Preview changes before adding/updating.npx shadcn@latest add button --dry-runnpx shadcn@latest add button --diff button.tsxnpx shadcn@latest add @acme/form --view button.tsx
# Search registries.npx shadcn@latest search @shadcn -q "sidebar"npx shadcn@latest search @tailark -q "stats"
# Get component docs and example URLs.npx shadcn@latest docs button dialog select
# View registry item details (for items not yet installed).npx shadcn@latest view @shadcn/button```
**Named presets:** `nova`, `vega`, `maia`, `lyra`, `mira`, `luma`**Templates:** `next`, `vite`, `start`, `react-router`, `astro` (all support `--monorepo`) and `laravel` (not supported for monorepo)**Preset codes:** Version-prefixed base62 strings (e.g. `a2r6bw` or `b0`), from [ui.shadcn.com](https://ui.shadcn.com).
## Detailed References
- [rules/forms.md](./rules/forms.md) — FieldGroup, Field, InputGroup, ToggleGroup, FieldSet, validation states- [rules/composition.md](./rules/composition.md) — Groups, overlays, Card, Tabs, Avatar, Alert, Empty, Toast, Separator, Skeleton, Badge, Button loading- [rules/icons.md](./rules/icons.md) — data-icon, icon sizing, passing icons as objects- [rules/styling.md](./rules/styling.md) — Semantic colors, variants, className, spacing, size, truncate, dark mode, cn(), z-index- [rules/base-vs-radix.md](./rules/base-vs-radix.md) — asChild vs render, Select, ToggleGroup, Slider, Accordion- [cli.md](./cli.md) — Commands, flags, presets, templates- [customization.md](./customization.md) — Theming, CSS variables, extending components12345interface: display_name: "shadcn/ui" short_description: "Manages shadcn/ui components — adding, searching, fixing, debugging, styling, and composing UI." icon_small: "./assets/shadcn-small.png" icon_large: "./assets/shadcn.png"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276# shadcn CLI Reference
Configuration is read from `components.json`.
> **IMPORTANT:** Always run commands using the project's package runner: `npx shadcn@latest`, `pnpm dlx shadcn@latest`, or `bunx --bun shadcn@latest`. Check `packageManager` from project context to choose the right one. Examples below use `npx shadcn@latest` but substitute the correct runner for the project.
> **IMPORTANT:** Only use the flags documented below. Do not invent or guess flags — if a flag isn't listed here, it doesn't exist. The CLI auto-detects the package manager from the project's lockfile; there is no `--package-manager` flag.
## Contents
- Commands: init, apply, add (dry-run, smart merge), search, view, docs, info, build- Templates: next, vite, start, react-router, astro- Presets: named, code, URL formats and fields- Switching presets
---
## Commands
### `init` — Initialize or create a project
```bashnpx shadcn@latest init [components...] [options]```
Initializes shadcn/ui in an existing project or creates a new project (when `--name` is provided). Optionally installs components in the same step.
| Flag | Short | Description | Default || ----------------------- | ----- | --------------------------------------------------------- | ------- || `--template <template>` | `-t` | Template (next, start, vite, next-monorepo, react-router) | — || `--preset [name]` | `-p` | Preset configuration (named, code, or URL) | — || `--yes` | `-y` | Skip confirmation prompt | `true` || `--defaults` | `-d` | Use defaults (`--template=next --preset=base-nova`) | `false` || `--force` | `-f` | Force overwrite existing configuration | `false` || `--cwd <cwd>` | `-c` | Working directory | current || `--name <name>` | `-n` | Name for new project | — || `--silent` | `-s` | Mute output | `false` || `--rtl` | | Enable RTL support | — || `--reinstall` | | Re-install existing UI components | `false` || `--monorepo` | | Scaffold a monorepo project | — || `--no-monorepo` | | Skip the monorepo prompt | — |
`npx shadcn@latest create` is an alias for `npx shadcn@latest init`.
### `apply` — Apply a preset to an existing project
```bashnpx shadcn@latest apply [preset] [options]```
Applies a preset to an existing project, overwriting preset-driven config, fonts, CSS variables, and detected UI components.
| Flag | Short | Description | Default || ------------------- | ----- | ------------------------------------------ | ------- || `--preset <preset>` | — | Preset configuration (named, code, or URL) | — || `--yes` | `-y` | Skip confirmation prompt | `false` || `--cwd <cwd>` | `-c` | Working directory | current || `--silent` | `-s` | Mute output | `false` |
`[preset]` is a shorthand for `--preset <preset>`. If both are provided, they must match.If no preset is provided, the CLI offers to open the custom preset builder on `ui.shadcn.com/create`.
### `add` — Add components
> **IMPORTANT:** To compare local components against upstream or to preview changes, ALWAYS use `npx shadcn@latest add <component> --dry-run`, `--diff`, or `--view`. NEVER fetch raw files from GitHub or other sources manually. The CLI handles registry resolution, file paths, and CSS diffing automatically.
```bashnpx shadcn@latest add [components...] [options]```
Accepts component names, registry-prefixed names (`@magicui/shimmer-button`), URLs, or local paths.
| Flag | Short | Description | Default || --------------- | ----- | -------------------------------------------------------------------------------------------------------------------- | ------- || `--yes` | `-y` | Skip confirmation prompt | `false` || `--overwrite` | `-o` | Overwrite existing files | `false` || `--cwd <cwd>` | `-c` | Working directory | current || `--all` | `-a` | Add all available components | `false` || `--path <path>` | `-p` | Target path for the component | — || `--silent` | `-s` | Mute output | `false` || `--dry-run` | | Preview all changes without writing files | `false` || `--diff [path]` | | Show diffs. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — || `--view [path]` | | Show file contents. Without a path, shows the first 5 files. With a path, shows that file only (implies `--dry-run`) | — |
#### Dry-Run Mode
Use `--dry-run` to preview what `add` would do without writing any files. `--diff` and `--view` both imply `--dry-run`.
```bash# Preview all changes.npx shadcn@latest add button --dry-run
# Show diffs for all files (top 5).npx shadcn@latest add button --diff
# Show the diff for a specific file.npx shadcn@latest add button --diff button.tsx
# Show contents for all files (top 5).npx shadcn@latest add button --view
# Show the full content of a specific file.npx shadcn@latest add button --view button.tsx
# Works with URLs too.npx shadcn@latest add https://api.npoint.io/abc123 --dry-run
# CSS diffs.npx shadcn@latest add button --diff globals.css```
**When to use dry-run:**
- When the user asks "what files will this add?" or "what will this change?" — use `--dry-run`.- Before overwriting existing components — use `--diff` to preview the changes first.- When the user wants to inspect component source code without installing — use `--view`.- When checking what CSS changes would be made to `globals.css` — use `--diff globals.css`.- When the user asks to review or audit third-party registry code before installing — use `--view` to inspect the source.
> **`npx shadcn@latest add --dry-run` vs `npx shadcn@latest view`:** Prefer `npx shadcn@latest add --dry-run/--diff/--view` over `npx shadcn@latest view` when the user wants to preview changes to their project. `npx shadcn@latest view` only shows raw registry metadata. `npx shadcn@latest add --dry-run` shows exactly what would happen in the user's project: resolved file paths, diffs against existing files, and CSS updates. Use `npx shadcn@latest view` only when the user wants to browse registry info without a project context.
#### Smart Merge from Upstream
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full workflow.
### `search` — Search registries
```bashnpx shadcn@latest search <registries...> [options]```
Fuzzy search across registries. Also aliased as `npx shadcn@latest list`. Without `-q`, lists all items.
| Flag | Short | Description | Default || ------------------- | ----- | ---------------------- | ------- || `--query <query>` | `-q` | Search query | — || `--limit <number>` | `-l` | Max items per registry | `100` || `--offset <number>` | `-o` | Items to skip | `0` || `--cwd <cwd>` | `-c` | Working directory | current |
### `view` — View item details
```bashnpx shadcn@latest view <items...> [options]```
Displays item info including file contents. Example: `npx shadcn@latest view @shadcn/button`.
### `docs` — Get component documentation URLs
```bashnpx shadcn@latest docs <components...> [options]```
Outputs resolved URLs for component documentation, examples, and API references. Accepts one or more component names. Fetch the URLs to get the actual content.
Example output for `npx shadcn@latest docs input button`:
```base radix
input docs https://ui.shadcn.com/docs/components/radix/input examples https://raw.githubusercontent.com/.../examples/input-example.tsx
button docs https://ui.shadcn.com/docs/components/radix/button examples https://raw.githubusercontent.com/.../examples/button-example.tsx```
Some components include an `api` link to the underlying library (e.g. `cmdk` for the command component).
### `diff` — Check for updates
Do not use this command. Use `npx shadcn@latest add --diff` instead.
### `info` — Project information
```bashnpx shadcn@latest info [options]```
Displays project info and `components.json` configuration. Run this first to discover the project's framework, aliases, Tailwind version, and resolved paths.
| Flag | Short | Description | Default || ------------- | ----- | ----------------- | ------- || `--cwd <cwd>` | `-c` | Working directory | current |
**Project Info fields:**
| Field | Type | Meaning || -------------------- | --------- | ------------------------------------------------------------------ || `framework` | `string` | Detected framework (`next`, `vite`, `react-router`, `start`, etc.) || `frameworkVersion` | `string` | Framework version (e.g. `15.2.4`) || `isSrcDir` | `boolean` | Whether the project uses a `src/` directory || `isRSC` | `boolean` | Whether React Server Components are enabled || `isTsx` | `boolean` | Whether the project uses TypeScript || `tailwindVersion` | `string` | `"v3"` or `"v4"` || `tailwindConfigFile` | `string` | Path to the Tailwind config file || `tailwindCssFile` | `string` | Path to the global CSS file || `aliasPrefix` | `string` | Import alias prefix (e.g. `@`, `~`, `@/`) || `packageManager` | `string` | Detected package manager (`npm`, `pnpm`, `yarn`, `bun`) |
**Components.json fields:**
| Field | Type | Meaning || -------------------- | --------- | ------------------------------------------------------------------------------------------ || `base` | `string` | Primitive library (`radix` or `base`) — determines component APIs and available props || `style` | `string` | Visual style (e.g. `nova`, `vega`) || `rsc` | `boolean` | RSC flag from config || `tsx` | `boolean` | TypeScript flag || `tailwind.config` | `string` | Tailwind config path || `tailwind.css` | `string` | Global CSS path — this is where custom CSS variables go || `iconLibrary` | `string` | Icon library — determines icon import package (e.g. `lucide-react`, `@tabler/icons-react`) || `aliases.components` | `string` | Component import alias (e.g. `@/components`) || `aliases.utils` | `string` | Utils import alias (e.g. `@/lib/utils`) || `aliases.ui` | `string` | UI component alias (e.g. `@/components/ui`) || `aliases.lib` | `string` | Lib alias (e.g. `@/lib`) || `aliases.hooks` | `string` | Hooks alias (e.g. `@/hooks`) || `resolvedPaths` | `object` | Absolute file-system paths for each alias || `registries` | `object` | Configured custom registries |
**Links fields:**
The `info` output includes a **Links** section with templated URLs for component docs, source, and examples. For resolved URLs, use `npx shadcn@latest docs <component>` instead.
### `build` — Build a custom registry
```bashnpx shadcn@latest build [registry] [options]```
Builds `registry.json` into individual JSON files for distribution. Default input: `./registry.json`, default output: `./public/r`.
| Flag | Short | Description | Default || ----------------- | ----- | ----------------- | ------------ || `--output <path>` | `-o` | Output directory | `./public/r` || `--cwd <cwd>` | `-c` | Working directory | current |
---
## Templates
| Value | Framework | Monorepo support || -------------- | -------------- | ---------------- || `next` | Next.js | Yes || `vite` | Vite | Yes || `start` | TanStack Start | Yes || `react-router` | React Router | Yes || `astro` | Astro | Yes || `laravel` | Laravel | No |
All templates support monorepo scaffolding via the `--monorepo` flag. When passed, the CLI uses a monorepo-specific template directory (e.g. `next-monorepo`, `vite-monorepo`). When neither `--monorepo` nor `--no-monorepo` is passed, the CLI prompts interactively. Laravel does not support monorepo scaffolding.
---
## Presets
Three ways to specify a preset via `--preset`:
1. **Named:** `--preset nova` or `--preset lyra`2. **Code:** `--preset a2r6bw` (version-prefixed base62 string, e.g. `a2r6bw` or `b0`)3. **URL:** `--preset "https://ui.shadcn.com/init?base=radix&style=nova&..."`
> **IMPORTANT:** Never try to decode, fetch, or resolve preset codes manually. Preset codes are opaque — pass them directly to `npx shadcn@latest init --preset <code>` and let the CLI handle resolution.> Use `npx shadcn@latest apply --preset <code>` when overwriting an existing project's preset.
## Switching Presets
Ask the user first: **overwrite**, **merge**, or **skip** existing components?
- **Overwrite / Re-install** → `npx shadcn@latest apply --preset <code>`. Overwrites all detected component files with the new preset styles. Use when the user hasn't customized components.- **Merge** → `npx shadcn@latest init --preset <code> --force --no-reinstall`, then run `npx shadcn@latest info` to get the list of installed components and use the [smart merge workflow](./SKILL.md#updating-components) to update them one by one, preserving local changes. Use when the user has customized components.- **Skip** → `npx shadcn@latest init --preset <code> --force --no-reinstall`. Only updates config and CSS variables, leaves existing components as-is.
Always run preset commands inside the user's project directory. `apply` only works in an existing project with a `components.json` file. The CLI automatically preserves the current base (`base` vs `radix`) from `components.json`. If you must use a scratch/temp directory (e.g. for `--dry-run` comparisons), pass `--base <current-base>` explicitly — preset codes do not encode the base.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208# Customization & Theming
Components reference semantic CSS variable tokens. Change the variables to change every component.
## Contents
- How it works (CSS variables → Tailwind utilities → components)- Color variables and OKLCH format- Dark mode setup- Changing the theme (presets, CSS variables)- Adding custom colors (Tailwind v3 and v4)- Border radius- Customizing components (variants, className, wrappers)- Checking for updates
---
## How It Works
1. CSS variables defined in `:root` (light) and `.dark` (dark mode).2. Tailwind maps them to utilities: `bg-primary`, `text-muted-foreground`, etc.3. Components use these utilities — changing a variable changes all components that reference it.
---
## Color Variables
Every color follows the `name` / `name-foreground` convention. The base variable is for backgrounds, `-foreground` is for text/icons on that background.
| Variable | Purpose || -------------------------------------------- | -------------------------------- || `--background` / `--foreground` | Page background and default text || `--card` / `--card-foreground` | Card surfaces || `--primary` / `--primary-foreground` | Primary buttons and actions || `--secondary` / `--secondary-foreground` | Secondary actions || `--muted` / `--muted-foreground` | Muted/disabled states || `--accent` / `--accent-foreground` | Hover and accent states || `--destructive` / `--destructive-foreground` | Error and destructive actions || `--border` | Default border color || `--input` | Form input borders || `--ring` | Focus ring color || `--chart-1` through `--chart-5` | Chart/data visualization || `--sidebar-*` | Sidebar-specific colors || `--surface` / `--surface-foreground` | Secondary surface |
Colors use OKLCH: `--primary: oklch(0.205 0 0)` where values are lightness (0–1), chroma (0 = gray), and hue (0–360).
---
## Dark Mode
Class-based toggle via `.dark` on the root element. In Next.js, use `next-themes`:
```tsximport { ThemeProvider } from "next-themes";
<ThemeProvider attribute="class" defaultTheme="system" enableSystem> {children}</ThemeProvider>;```
---
## Changing the Theme
```bash# Apply a preset code from ui.shadcn.com.npx shadcn@latest apply --preset a2r6bw
# Positional shorthand also works.npx shadcn@latest apply a2r6bw
# Switch to a named preset and overwrite existing components.npx shadcn@latest apply --preset nova
# Preserve existing components instead.npx shadcn@latest init --preset nova --force --no-reinstall
# Use a custom theme URL.npx shadcn@latest apply --preset "https://ui.shadcn.com/init?base=radix&style=nova&theme=blue&..."```
Or edit CSS variables directly in `globals.css`.
---
## Adding Custom Colors
Add variables to the file at `tailwindCssFile` from `npx shadcn@latest info` (typically `globals.css`). Never create a new CSS file for this.
```css/* 1. Define in the global CSS file. */:root { --warning: oklch(0.84 0.16 84); --warning-foreground: oklch(0.28 0.07 46);}.dark { --warning: oklch(0.41 0.11 46); --warning-foreground: oklch(0.99 0.02 95);}```
```css/* 2a. Register with Tailwind v4 (@theme inline). */@theme inline { --color-warning: var(--warning); --color-warning-foreground: var(--warning-foreground);}```
When `tailwindVersion` is `"v3"` (check via `npx shadcn@latest info`), register in `tailwind.config.js` instead:
```js// 2b. Register with Tailwind v3 (tailwind.config.js).module.exports = { theme: { extend: { colors: { warning: "oklch(var(--warning) / <alpha-value>)", "warning-foreground": "oklch(var(--warning-foreground) / <alpha-value>)", }, }, },};```
```tsx// 3. Use in components.<div className="bg-warning text-warning-foreground">Warning</div>```
---
## Border Radius
`--radius` controls border radius globally. Components derive values from it (`rounded-lg` = `var(--radius)`, `rounded-md` = `calc(var(--radius) - 2px)`).
---
## Customizing Components
See also: [rules/styling.md](./rules/styling.md) for Incorrect/Correct examples.
Prefer these approaches in order:
### 1. Built-in variants
```tsx<Button variant="outline" size="sm"> Click</Button>```
### 2. Tailwind classes via `className`
```tsx<Card className="mx-auto max-w-md">...</Card>```
### 3. Add a new variant
Edit the component source to add a variant via `cva`:
```tsx// components/ui/button.tsxwarning: "bg-warning text-warning-foreground hover:bg-warning/90",```
### 4. Wrapper components
Compose shadcn/ui primitives into higher-level components:
```tsxexport function ConfirmDialog({ title, description, onConfirm, children }) { return ( <AlertDialog> <AlertDialogTrigger asChild>{children}</AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{title}</AlertDialogTitle> <AlertDialogDescription>{description}</AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>Cancel</AlertDialogCancel> <AlertDialogAction onClick={onConfirm}>Confirm</AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> );}```
---
## Checking for Updates
```bashnpx shadcn@latest add button --diff```
To preview exactly what would change before updating, use `--dry-run` and `--diff`:
```bashnpx shadcn@latest add button --dry-run # see all affected filesnpx shadcn@latest add button --diff button.tsx # see the diff for a specific file```
See [Updating Components in SKILL.md](./SKILL.md#updating-components) for the full smart merge workflow.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647{ "skill_name": "shadcn", "evals": [ { "id": 1, "prompt": "I'm building a Next.js app with shadcn/ui (base-nova preset, lucide icons). Create a settings form component with fields for: full name, email address, and notification preferences (email, SMS, push notifications as toggle options). Add validation states for required fields.", "expected_output": "A React component using FieldGroup, Field, ToggleGroup, data-invalid/aria-invalid validation, gap-* spacing, and semantic colors.", "files": [], "expectations": [ "Uses FieldGroup and Field components for form layout instead of raw div with space-y", "Uses Switch for independent on/off notification toggles (not looping Button with manual active state)", "Uses data-invalid on Field and aria-invalid on the input control for validation states", "Uses gap-* (e.g. gap-4, gap-6) instead of space-y-* or space-x-* for spacing", "Uses semantic color tokens (e.g. bg-background, text-muted-foreground, text-destructive) instead of raw colors like bg-red-500", "No manual dark: color overrides" ] }, { "id": 2, "prompt": "Create a dialog component for editing a user profile. It should have the user's avatar at the top, input fields for name and bio, and Save/Cancel buttons with appropriate icons. Using shadcn/ui with radix-nova preset and tabler icons.", "expected_output": "A React component with DialogTitle, Avatar+AvatarFallback, data-icon on icon buttons, no icon sizing classes, tabler icon imports.", "files": [], "expectations": [ "Includes DialogTitle for accessibility (visible or with sr-only class)", "Avatar component includes AvatarFallback", "Icons on buttons use the data-icon attribute (data-icon=\"inline-start\" or data-icon=\"inline-end\")", "No sizing classes on icons inside components (no size-4, w-4, h-4, etc.)", "Uses tabler icons (@tabler/icons-react) instead of lucide-react", "Uses asChild for custom triggers (radix preset)" ] }, { "id": 3, "prompt": "Create a dashboard component that shows 4 stat cards in a grid. Each card has a title, large number, percentage change badge, and a loading skeleton state. Using shadcn/ui with base-nova preset and lucide icons.", "expected_output": "A React component with full Card composition, Skeleton for loading, Badge for changes, semantic colors, gap-* spacing.", "files": [], "expectations": [ "Uses full Card composition with CardHeader, CardTitle, CardContent (not dumping everything into CardContent)", "Uses Skeleton component for loading placeholders instead of custom animate-pulse divs", "Uses Badge component for percentage change instead of custom styled spans", "Uses semantic color tokens instead of raw color values like bg-green-500 or text-red-600", "Uses gap-* instead of space-y-* or space-x-* for spacing", "Uses size-* when width and height are equal instead of separate w-* h-*" ] } ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394# shadcn MCP Server
The CLI includes an MCP server that lets AI assistants search, browse, view, and install components from registries.
---
## Setup
```bashshadcn mcp # start the MCP server (stdio)shadcn mcp init # write config for your editor```
Editor config files:
| Editor | Config file || ----------- | ------------------------------- || Claude Code | `.mcp.json` || Cursor | `.cursor/mcp.json` || VS Code | `.vscode/mcp.json` || OpenCode | `opencode.json` || Codex | `~/.codex/config.toml` (manual) |
---
## Tools
> **Tip:** MCP tools handle registry operations (search, view, install). For project configuration (aliases, framework, Tailwind version), use `npx shadcn@latest info` — there is no MCP equivalent.
### `shadcn:get_project_registries`
Returns registry names from `components.json`. Errors if no `components.json` exists.
**Input:** none
### `shadcn:list_items_in_registries`
Lists all items from one or more registries.
**Input:** `registries` (string[]), `limit` (number, optional), `offset` (number, optional)
### `shadcn:search_items_in_registries`
Fuzzy search across registries.
**Input:** `registries` (string[]), `query` (string), `limit` (number, optional), `offset` (number, optional)
### `shadcn:view_items_in_registries`
View item details including full file contents.
**Input:** `items` (string[]) — e.g. `["@shadcn/button", "@shadcn/card"]`
### `shadcn:get_item_examples_from_registries`
Find usage examples and demos with source code.
**Input:** `registries` (string[]), `query` (string) — e.g. `"accordion-demo"`, `"button example"`
### `shadcn:get_add_command_for_items`
Returns the CLI install command.
**Input:** `items` (string[]) — e.g. `["@shadcn/button"]`
### `shadcn:get_audit_checklist`
Returns a checklist for verifying components (imports, deps, lint, TypeScript).
**Input:** none
---
## Configuring Registries
Registries are set in `components.json`. The `@shadcn` registry is always built-in.
```json{ "registries": { "@acme": "https://acme.com/r/{name}.json", "@private": { "url": "https://private.com/r/{name}.json", "headers": { "Authorization": "Bearer ${MY_TOKEN}" } } }}```
- Names must start with `@`.- URLs must contain `{name}`.- `${VAR}` references are resolved from environment variables.
Community registry index: `https://ui.shadcn.com/r/registries.json`123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308# Base vs Radix
API differences between `base` and `radix`. Check the `base` field from `npx shadcn@latest info`.
## Contents
- Composition: asChild vs render- Button / trigger as non-button element- Select (items prop, placeholder, positioning, multiple, object values)- ToggleGroup (type vs multiple)- Slider (scalar vs array)- Accordion (type and defaultValue)
---
## Composition: asChild (radix) vs render (base)
Radix uses `asChild` to replace the default element. Base uses `render`. Don't wrap triggers in extra elements.
**Incorrect:**
```tsx<DialogTrigger> <div> <Button>Open</Button> </div></DialogTrigger>```
**Correct (radix):**
```tsx<DialogTrigger asChild> <Button>Open</Button></DialogTrigger>```
**Correct (base):**
```tsx<DialogTrigger render={<Button />}>Open</DialogTrigger>```
This applies to all trigger and close components: `DialogTrigger`, `SheetTrigger`, `AlertDialogTrigger`, `DropdownMenuTrigger`, `PopoverTrigger`, `TooltipTrigger`, `CollapsibleTrigger`, `DialogClose`, `SheetClose`, `NavigationMenuLink`, `BreadcrumbLink`, `SidebarMenuButton`, `Badge`, `Item`.
---
## Button / trigger as non-button element (base only)
When `render` changes an element to a non-button (`<a>`, `<span>`), add `nativeButton={false}`.
**Incorrect (base):** missing `nativeButton={false}`.
```tsx<Button render={<a href="/docs" />}>Read the docs</Button>```
**Correct (base):**
```tsx<Button render={<a href="/docs" />} nativeButton={false}> Read the docs</Button>```
**Correct (radix):**
```tsx<Button asChild> <a href="/docs">Read the docs</a></Button>```
Same for triggers whose `render` is not a `Button`:
```tsx// base.<PopoverTrigger render={<InputGroupAddon />} nativeButton={false}> Pick date</PopoverTrigger>```
---
## Select
**items prop (base only).** Base requires an `items` prop on the root. Radix uses inline JSX only.
**Incorrect (base):**
```tsx<Select> <SelectTrigger> <SelectValue placeholder="Select a fruit" /> </SelectTrigger></Select>```
**Correct (base):**
```tsxconst items = [ { label: "Select a fruit", value: null }, { label: "Apple", value: "apple" }, { label: "Banana", value: "banana" },]
<Select items={items}> <SelectTrigger> <SelectValue /> </SelectTrigger> <SelectContent> <SelectGroup> {items.map((item) => ( <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem> ))} </SelectGroup> </SelectContent></Select>```
**Correct (radix):**
```tsx<Select> <SelectTrigger> <SelectValue placeholder="Select a fruit" /> </SelectTrigger> <SelectContent> <SelectGroup> <SelectItem value="apple">Apple</SelectItem> <SelectItem value="banana">Banana</SelectItem> </SelectGroup> </SelectContent></Select>```
**Placeholder.** Base uses a `{ value: null }` item in the items array. Radix uses `<SelectValue placeholder="...">`.
**Content positioning.** Base uses `alignItemWithTrigger`. Radix uses `position`.
```tsx// base.<SelectContent alignItemWithTrigger={false} side="bottom">
// radix.<SelectContent position="popper">```
---
## Select — multiple selection and object values (base only)
Base supports `multiple`, render-function children on `SelectValue`, and object values with `itemToStringValue`. Radix is single-select with string values only.
**Correct (base — multiple selection):**
```tsx<Select items={items} multiple defaultValue={[]}> <SelectTrigger> <SelectValue> {(value: string[]) => (value.length === 0 ? "Select fruits" : `${value.length} selected`)} </SelectValue> </SelectTrigger> ...</Select>```
**Correct (base — object values):**
```tsx<Select defaultValue={plans[0]} itemToStringValue={(plan) => plan.name}> <SelectTrigger> <SelectValue>{(value) => value.name}</SelectValue> </SelectTrigger> ...</Select>```
---
## ToggleGroup
Base uses a `multiple` boolean prop. Radix uses `type="single"` or `type="multiple"`.
**Incorrect (base):**
```tsx<ToggleGroup type="single" defaultValue="daily"> <ToggleGroupItem value="daily">Daily</ToggleGroupItem></ToggleGroup>```
**Correct (base):**
```tsx// Single (no prop needed), defaultValue is always an array.<ToggleGroup defaultValue={["daily"]} spacing={2}> <ToggleGroupItem value="daily">Daily</ToggleGroupItem> <ToggleGroupItem value="weekly">Weekly</ToggleGroupItem></ToggleGroup>
// Multi-selection.<ToggleGroup multiple> <ToggleGroupItem value="bold">Bold</ToggleGroupItem> <ToggleGroupItem value="italic">Italic</ToggleGroupItem></ToggleGroup>```
**Correct (radix):**
```tsx// Single, defaultValue is a string.<ToggleGroup type="single" defaultValue="daily" spacing={2}> <ToggleGroupItem value="daily">Daily</ToggleGroupItem> <ToggleGroupItem value="weekly">Weekly</ToggleGroupItem></ToggleGroup>
// Multi-selection.<ToggleGroup type="multiple"> <ToggleGroupItem value="bold">Bold</ToggleGroupItem> <ToggleGroupItem value="italic">Italic</ToggleGroupItem></ToggleGroup>```
**Controlled single value:**
```tsx// base — wrap/unwrap arrays.const [value, setValue] = React.useState("normal")<ToggleGroup value={[value]} onValueChange={(v) => setValue(v[0])}>
// radix — plain string.const [value, setValue] = React.useState("normal")<ToggleGroup type="single" value={value} onValueChange={setValue}>```
---
## Slider
Base accepts a plain number for a single thumb. Radix always requires an array.
**Incorrect (base):**
```tsx<Slider defaultValue={[50]} max={100} step={1} />```
**Correct (base):**
```tsx<Slider defaultValue={50} max={100} step={1} />```
**Correct (radix):**
```tsx<Slider defaultValue={[50]} max={100} step={1} />```
Both use arrays for range sliders. Controlled `onValueChange` in base may need a cast:
```tsx// base.const [value, setValue] = React.useState([0.3, 0.7])<Slider value={value} onValueChange={(v) => setValue(v as number[])} />
// radix.const [value, setValue] = React.useState([0.3, 0.7])<Slider value={value} onValueChange={setValue} />```
---
## Accordion
Radix requires `type="single"` or `type="multiple"` and supports `collapsible`. `defaultValue` is a string. Base uses no `type` prop, uses `multiple` boolean, and `defaultValue` is always an array.
**Incorrect (base):**
```tsx<Accordion type="single" collapsible defaultValue="item-1"> <AccordionItem value="item-1">...</AccordionItem></Accordion>```
**Correct (base):**
```tsx<Accordion defaultValue={["item-1"]}> <AccordionItem value="item-1">...</AccordionItem></Accordion>
// Multi-select.<Accordion multiple defaultValue={["item-1", "item-2"]}> <AccordionItem value="item-1">...</AccordionItem> <AccordionItem value="item-2">...</AccordionItem></Accordion>```
**Correct (radix):**
```tsx<Accordion type="single" collapsible defaultValue="item-1"> <AccordionItem value="item-1">...</AccordionItem></Accordion>```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197# Component Composition
## Contents
- Items always inside their Group component- Callouts use Alert- Empty states use Empty component- Toast notifications use sonner- Choosing between overlay components- Dialog, Sheet, and Drawer always need a Title- Card structure- Button has no isPending or isLoading prop- TabsTrigger must be inside TabsList- Avatar always needs AvatarFallback- Use Separator instead of raw hr or border divs- Use Skeleton for loading placeholders- Use Badge instead of custom styled spans
---
## Items always inside their Group component
Never render items directly inside the content container.
**Incorrect:**
```tsx<SelectContent> <SelectItem value="apple">Apple</SelectItem> <SelectItem value="banana">Banana</SelectItem></SelectContent>```
**Correct:**
```tsx<SelectContent> <SelectGroup> <SelectItem value="apple">Apple</SelectItem> <SelectItem value="banana">Banana</SelectItem> </SelectGroup></SelectContent>```
This applies to all group-based components:
| Item | Group || ---------------------------------------------------------- | ------------------- || `SelectItem`, `SelectLabel` | `SelectGroup` || `DropdownMenuItem`, `DropdownMenuLabel`, `DropdownMenuSub` | `DropdownMenuGroup` || `MenubarItem` | `MenubarGroup` || `ContextMenuItem` | `ContextMenuGroup` || `CommandItem` | `CommandGroup` |
---
## Callouts use Alert
```tsx<Alert> <AlertTitle>Warning</AlertTitle> <AlertDescription>Something needs attention.</AlertDescription></Alert>```
---
## Empty states use Empty component
```tsx<Empty> <EmptyHeader> <EmptyMedia variant="icon"> <FolderIcon /> </EmptyMedia> <EmptyTitle>No projects yet</EmptyTitle> <EmptyDescription>Get started by creating a new project.</EmptyDescription> </EmptyHeader> <EmptyContent> <Button>Create Project</Button> </EmptyContent></Empty>```
---
## Toast notifications use sonner
```tsximport { toast } from "sonner";
toast.success("Changes saved.");toast.error("Something went wrong.");toast("File deleted.", { action: { label: "Undo", onClick: () => undoDelete() },});```
---
## Choosing between overlay components
| Use case | Component || ---------------------------------- | ------------- || Focused task that requires input | `Dialog` || Destructive action confirmation | `AlertDialog` || Side panel with details or filters | `Sheet` || Mobile-first bottom panel | `Drawer` || Quick info on hover | `HoverCard` || Small contextual content on click | `Popover` |
---
## Dialog, Sheet, and Drawer always need a Title
`DialogTitle`, `SheetTitle`, `DrawerTitle` are required for accessibility. Use `className="sr-only"` if visually hidden.
```tsx<DialogContent> <DialogHeader> <DialogTitle>Edit Profile</DialogTitle> <DialogDescription>Update your profile.</DialogDescription> </DialogHeader> ...</DialogContent>```
---
## Card structure
Use full composition — don't dump everything into `CardContent`:
```tsx<Card> <CardHeader> <CardTitle>Team Members</CardTitle> <CardDescription>Manage your team.</CardDescription> </CardHeader> <CardContent>...</CardContent> <CardFooter> <Button>Invite</Button> </CardFooter></Card>```
---
## Button has no isPending or isLoading prop
Compose with `Spinner` + `data-icon` + `disabled`:
```tsx<Button disabled> <Spinner data-icon="inline-start" /> Saving...</Button>```
---
## TabsTrigger must be inside TabsList
Never render `TabsTrigger` directly inside `Tabs` — always wrap in `TabsList`:
```tsx<Tabs defaultValue="account"> <TabsList> <TabsTrigger value="account">Account</TabsTrigger> <TabsTrigger value="password">Password</TabsTrigger> </TabsList> <TabsContent value="account">...</TabsContent></Tabs>```
---
## Avatar always needs AvatarFallback
Always include `AvatarFallback` for when the image fails to load:
```tsx<Avatar> <AvatarImage src="/avatar.png" alt="User" /> <AvatarFallback>JD</AvatarFallback></Avatar>```
---
## Use existing components instead of custom markup
| Instead of | Use || -------------------------------------------------- | ------------------------------------ || `<hr>` or `<div className="border-t">` | `<Separator />` || `<div className="animate-pulse">` with styled divs | `<Skeleton className="h-4 w-3/4" />` || `<span className="rounded-full bg-green-100 ...">` | `<Badge variant="secondary">` |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194# Forms & Inputs
## Contents
- Forms use FieldGroup + Field- InputGroup requires InputGroupInput/InputGroupTextarea- Buttons inside inputs use InputGroup + InputGroupAddon- Option sets (2–7 choices) use ToggleGroup- FieldSet + FieldLegend for grouping related fields- Field validation and disabled states
---
## Forms use FieldGroup + Field
Always use `FieldGroup` + `Field` — never raw `div` with `space-y-*`:
```tsx<FieldGroup> <Field> <FieldLabel htmlFor="email">Email</FieldLabel> <Input id="email" type="email" /> </Field> <Field> <FieldLabel htmlFor="password">Password</FieldLabel> <Input id="password" type="password" /> </Field></FieldGroup>```
Use `Field orientation="horizontal"` for settings pages. Use `FieldLabel className="sr-only"` for visually hidden labels.
**Choosing form controls:**
- Simple text input → `Input`- Dropdown with predefined options → `Select`- Searchable dropdown → `Combobox`- Native HTML select (no JS) → `native-select`- Boolean toggle → `Switch` (for settings) or `Checkbox` (for forms)- Single choice from few options → `RadioGroup`- Toggle between 2–5 options → `ToggleGroup` + `ToggleGroupItem`- OTP/verification code → `InputOTP`- Multi-line text → `Textarea`
---
## InputGroup requires InputGroupInput/InputGroupTextarea
Never use raw `Input` or `Textarea` inside an `InputGroup`.
**Incorrect:**
```tsx<InputGroup> <Input placeholder="Search..." /></InputGroup>```
**Correct:**
```tsximport { InputGroup, InputGroupInput } from "@/components/ui/input-group";
<InputGroup> <InputGroupInput placeholder="Search..." /></InputGroup>;```
---
## Buttons inside inputs use InputGroup + InputGroupAddon
Never place a `Button` directly inside or adjacent to an `Input` with custom positioning.
**Incorrect:**
```tsx<div className="relative"> <Input placeholder="Search..." className="pr-10" /> <Button className="absolute right-0 top-0" size="icon"> <SearchIcon /> </Button></div>```
**Correct:**
```tsximport { InputGroup, InputGroupInput, InputGroupAddon } from "@/components/ui/input-group";
<InputGroup> <InputGroupInput placeholder="Search..." /> <InputGroupAddon> <Button size="icon"> <SearchIcon data-icon="inline-start" /> </Button> </InputGroupAddon></InputGroup>;```
---
## Option sets (2–7 choices) use ToggleGroup
Don't manually loop `Button` components with active state.
**Incorrect:**
```tsxconst [selected, setSelected] = useState("daily")
<div className="flex gap-2"> {["daily", "weekly", "monthly"].map((option) => ( <Button key={option} variant={selected === option ? "default" : "outline"} onClick={() => setSelected(option)} > {option} </Button> ))}</div>```
**Correct:**
```tsximport { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
<ToggleGroup spacing={2}> <ToggleGroupItem value="daily">Daily</ToggleGroupItem> <ToggleGroupItem value="weekly">Weekly</ToggleGroupItem> <ToggleGroupItem value="monthly">Monthly</ToggleGroupItem></ToggleGroup>;```
Combine with `Field` for labelled toggle groups:
```tsx<Field orientation="horizontal"> <FieldTitle id="theme-label">Theme</FieldTitle> <ToggleGroup aria-labelledby="theme-label" spacing={2}> <ToggleGroupItem value="light">Light</ToggleGroupItem> <ToggleGroupItem value="dark">Dark</ToggleGroupItem> <ToggleGroupItem value="system">System</ToggleGroupItem> </ToggleGroup></Field>```
> **Note:** `defaultValue` and `type`/`multiple` props differ between base and radix. See [base-vs-radix.md](./base-vs-radix.md#togglegroup).
---
## FieldSet + FieldLegend for grouping related fields
Use `FieldSet` + `FieldLegend` for related checkboxes, radios, or switches — not `div` with a heading:
```tsx<FieldSet> <FieldLegend variant="label">Preferences</FieldLegend> <FieldDescription>Select all that apply.</FieldDescription> <FieldGroup className="gap-3"> <Field orientation="horizontal"> <Checkbox id="dark" /> <FieldLabel htmlFor="dark" className="font-normal"> Dark mode </FieldLabel> </Field> </FieldGroup></FieldSet>```
---
## Field validation and disabled states
Both attributes are needed — `data-invalid`/`data-disabled` styles the field (label, description), while `aria-invalid`/`disabled` styles the control.
```tsx// Invalid.<Field data-invalid> <FieldLabel htmlFor="email">Email</FieldLabel> <Input id="email" aria-invalid /> <FieldDescription>Invalid email address.</FieldDescription></Field>
// Disabled.<Field data-disabled> <FieldLabel htmlFor="email">Email</FieldLabel> <Input id="email" disabled /></Field>```
Works for all controls: `Input`, `Textarea`, `Select`, `Checkbox`, `RadioGroupItem`, `Switch`, `Slider`, `NativeSelect`, `InputOTP`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Icons
**Always use the project's configured `iconLibrary` for imports.** Check the `iconLibrary` field from project context: `lucide` → `lucide-react`, `tabler` → `@tabler/icons-react`, etc. Never assume `lucide-react`.
---
## Icons in Button use data-icon attribute
Add `data-icon="inline-start"` (prefix) or `data-icon="inline-end"` (suffix) to the icon. No sizing classes on the icon.
**Incorrect:**
```tsx<Button> <SearchIcon className="mr-2 size-4" /> Search</Button>```
**Correct:**
```tsx<Button> <SearchIcon data-icon="inline-start"/> Search</Button>
<Button> Next <ArrowRightIcon data-icon="inline-end"/></Button>```
---
## No sizing classes on icons inside components
Components handle icon sizing via CSS. Don't add `size-4`, `w-4 h-4`, or other sizing classes to icons inside `Button`, `DropdownMenuItem`, `Alert`, `Sidebar*`, or other shadcn components. Unless the user explicitly asks for custom icon sizes.
**Incorrect:**
```tsx<Button> <SearchIcon className="size-4" data-icon="inline-start" /> Search</Button>
<DropdownMenuItem> <SettingsIcon className="mr-2 size-4" /> Settings</DropdownMenuItem>```
**Correct:**
```tsx<Button> <SearchIcon data-icon="inline-start" /> Search</Button>
<DropdownMenuItem> <SettingsIcon /> Settings</DropdownMenuItem>```
---
## Pass icons as component objects, not string keys
Use `icon={CheckIcon}`, not a string key to a lookup map.
**Incorrect:**
```tsxconst iconMap = { check: CheckIcon, alert: AlertIcon,};
function StatusBadge({ icon }: { icon: string }) { const Icon = iconMap[icon]; return <Icon />;}
<StatusBadge icon="check" />;```
**Correct:**
```tsx// Import from the project's configured iconLibrary (e.g. lucide-react, @tabler/icons-react).import { CheckIcon } from "lucide-react";
function StatusBadge({ icon: Icon }: { icon: React.ComponentType }) { return <Icon />;}
<StatusBadge icon={CheckIcon} />;```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161# Styling & Customization
See [customization.md](../customization.md) for theming, CSS variables, and adding custom colors.
## Contents
- Semantic colors- Built-in variants first- className for layout only- No space-x-_ / space-y-_- Prefer size-_ over w-_ h-\* when equal- Prefer truncate shorthand- No manual dark: color overrides- Use cn() for conditional classes- No manual z-index on overlay components
---
## Semantic colors
**Incorrect:**
```tsx<div className="bg-blue-500 text-white"> <p className="text-gray-600">Secondary text</p></div>```
**Correct:**
```tsx<div className="bg-primary text-primary-foreground"> <p className="text-muted-foreground">Secondary text</p></div>```
---
## No raw color values for status/state indicators
For positive, negative, or status indicators, use Badge variants, semantic tokens like `text-destructive`, or define custom CSS variables — don't reach for raw Tailwind colors.
**Incorrect:**
```tsx<span className="text-emerald-600">+20.1%</span><span className="text-green-500">Active</span><span className="text-red-600">-3.2%</span>```
**Correct:**
```tsx<Badge variant="secondary">+20.1%</Badge><Badge>Active</Badge><span className="text-destructive">-3.2%</span>```
If you need a success/positive color that doesn't exist as a semantic token, use a Badge variant or ask the user about adding a custom CSS variable to the theme (see [customization.md](../customization.md)).
---
## Built-in variants first
**Incorrect:**
```tsx<Button className="border border-input bg-transparent hover:bg-accent">Click me</Button>```
**Correct:**
```tsx<Button variant="outline">Click me</Button>```
---
## className for layout only
Use `className` for layout (e.g. `max-w-md`, `mx-auto`, `mt-4`), **not** for overriding component colors or typography. To change colors, use semantic tokens, built-in variants, or CSS variables.
**Incorrect:**
```tsx<Card className="bg-blue-100 text-blue-900 font-bold"> <CardContent>Dashboard</CardContent></Card>```
**Correct:**
```tsx<Card className="max-w-md mx-auto"> <CardContent>Dashboard</CardContent></Card>```
To customize a component's appearance, prefer these approaches in order:
1. **Built-in variants** — `variant="outline"`, `variant="destructive"`, etc.2. **Semantic color tokens** — `bg-primary`, `text-muted-foreground`.3. **CSS variables** — define custom colors in the global CSS file (see [customization.md](../customization.md)).
---
## No space-x-_ / space-y-_
Use `gap-*` instead. `space-y-4` → `flex flex-col gap-4`. `space-x-2` → `flex gap-2`.
```tsx<div className="flex flex-col gap-4"> <Input /> <Input /> <Button>Submit</Button></div>```
---
## Prefer size-_ over w-_ h-\* when equal
`size-10` not `w-10 h-10`. Applies to icons, avatars, skeletons, etc.
---
## Prefer truncate shorthand
`truncate` not `overflow-hidden text-ellipsis whitespace-nowrap`.
---
## No manual dark: color overrides
Use semantic tokens — they handle light/dark via CSS variables. `bg-background text-foreground` not `bg-white dark:bg-gray-950`.
---
## Use cn() for conditional classes
Use the `cn()` utility from the project for conditional or merged class names. Don't write manual ternaries in className strings.
**Incorrect:**
```tsx<div className={`flex items-center ${isActive ? "bg-primary text-primary-foreground" : "bg-muted"}`}>```
**Correct:**
```tsximport { cn } from "@/lib/utils"
<div className={cn("flex items-center", isActive ? "bg-primary text-primary-foreground" : "bg-muted")}>```
---
## No manual z-index on overlay components
`Dialog`, `Sheet`, `Drawer`, `AlertDialog`, `DropdownMenu`, `Popover`, `Tooltip`, `HoverCard` handle their own stacking. Never add `z-50` or `z-[999]`.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951---name: turborepodescription: | Turborepo monorepo build system guidance. Triggers on: turbo.json, task pipelines, dependsOn, caching, remote cache, the "turbo" CLI, --filter, --affected, CI optimization, environment variables, internal packages, monorepo structure/best practices, and boundaries.
Use when user: configures tasks/workflows/pipelines, creates packages, sets up monorepo, shares code between apps, runs changed/affected packages, debugs cache, or has apps/packages directories.metadata: version: 2.9.7-canary.13---
# Turborepo Skill
Build system for JavaScript/TypeScript monorepos. Turborepo caches task outputs and runs tasks in parallel based on dependency graph.
## IMPORTANT: Package Tasks, Not Root Tasks
**DO NOT create Root Tasks. ALWAYS create package tasks.**
When creating tasks/scripts/pipelines, you MUST:
1. Add the script to each relevant package's `package.json`2. Register the task in root `turbo.json`3. Root `package.json` only delegates via `turbo run <task>`
**DO NOT** put task logic in root `package.json`. This defeats Turborepo's parallelization.
```json// DO THIS: Scripts in each package// apps/web/package.json{ "scripts": { "build": "next build", "lint": "eslint .", "test": "vitest" } }
// apps/api/package.json{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
// packages/ui/package.json{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }```
```json// turbo.json - register tasks{ "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] }, "lint": {}, "test": { "dependsOn": ["build"] } }}```
```json// Root package.json - ONLY delegates, no task logic{ "scripts": { "build": "turbo run build", "lint": "turbo run lint", "test": "turbo run test" }}```
```json// DO NOT DO THIS - defeats parallelization// Root package.json{ "scripts": { "build": "cd apps/web && next build && cd ../api && tsc", "lint": "eslint apps/ packages/", "test": "vitest" }}```
Root Tasks (`//#taskname`) are ONLY for tasks that truly cannot exist in packages (rare).
## Secondary Rule: `turbo run` vs `turbo`
**Always use `turbo run` when the command is written into code:**
```json// package.json - ALWAYS "turbo run"{ "scripts": { "build": "turbo run build" }}```
```yaml# CI workflows - ALWAYS "turbo run"- run: turbo run build --affected```
**The shorthand `turbo <tasks>` is ONLY for one-off terminal commands** typed directly by humans or agents. Never write `turbo build` into package.json, CI, or scripts.
## Quick Decision Trees
### "I need to configure a task"
```Configure a task?├─ Define task dependencies → references/configuration/tasks.md├─ Lint/check-types (parallel + caching) → Use Transit Nodes pattern (see below)├─ Specify build outputs → references/configuration/tasks.md#outputs├─ Handle environment variables → references/environment/RULE.md├─ Set up dev/watch tasks → references/configuration/tasks.md#persistent├─ Package-specific config → references/configuration/RULE.md#package-configurations└─ Global settings (cacheDir, daemon) → references/configuration/global-options.md```
### "My cache isn't working"
```Cache problems?├─ Tasks run but outputs not restored → Missing `outputs` key├─ Cache misses unexpectedly → references/caching/gotchas.md├─ Need to debug hash inputs → Use --summarize or --dry├─ Want to skip cache entirely → Use --force or cache: false├─ Remote cache not working → references/caching/remote-cache.md└─ Environment causing misses → references/environment/gotchas.md```
### "I want to run only changed packages"
```Run only what changed?├─ Changed packages + dependents (RECOMMENDED) → turbo run build --affected├─ Custom base branch → --affected --affected-base=origin/develop├─ Manual git comparison → --filter=...[origin/main]└─ See all filter options → references/filtering/RULE.md```
**`--affected` is the primary way to run only changed packages.** It automatically compares against the default branch and includes dependents.
### "I want to filter packages"
```Filter packages?├─ Only changed packages → --affected (see above)├─ By package name → --filter=web├─ By directory → --filter=./apps/*├─ Package + dependencies → --filter=web...├─ Package + dependents → --filter=...web└─ Complex combinations → references/filtering/patterns.md```
### "Environment variables aren't working"
```Environment issues?├─ Vars not available at runtime → Strict mode filtering (default)├─ Cache hits with wrong env → Var not in `env` key├─ .env changes not causing rebuilds → .env not in `inputs`├─ CI variables missing → references/environment/gotchas.md└─ Framework vars (NEXT_PUBLIC_*) → Auto-included via inference```
### "I need to set up CI"
```CI setup?├─ GitHub Actions → references/ci/github-actions.md├─ Vercel deployment → references/ci/vercel.md├─ Remote cache in CI → references/caching/remote-cache.md├─ Only build changed packages → --affected flag├─ Skip unnecessary builds → turbo-ignore (references/cli/commands.md)└─ Skip container setup when no changes → turbo-ignore```
### "I want to watch for changes during development"
```Watch mode?├─ Re-run tasks on change → turbo watch (references/watch/RULE.md)├─ Dev servers with dependencies → Use `with` key (references/configuration/tasks.md#with)├─ Restart dev server on dep change → Use `interruptible: true`└─ Persistent dev tasks → Use `persistent: true````
### "I need to create/structure a package"
```Package creation/structure?├─ Create an internal package → references/best-practices/packages.md├─ Repository structure → references/best-practices/structure.md├─ Dependency management → references/best-practices/dependencies.md├─ Best practices overview → references/best-practices/RULE.md├─ JIT vs Compiled packages → references/best-practices/packages.md#compilation-strategies└─ Sharing code between apps → references/best-practices/RULE.md#package-types```
### "How should I structure my monorepo?"
```Monorepo structure?├─ Standard layout (apps/, packages/) → references/best-practices/RULE.md├─ Package types (apps vs libraries) → references/best-practices/RULE.md#package-types├─ Creating internal packages → references/best-practices/packages.md├─ TypeScript configuration → references/best-practices/structure.md#typescript-configuration├─ ESLint configuration → references/best-practices/structure.md#eslint-configuration├─ Dependency management → references/best-practices/dependencies.md└─ Enforce package boundaries → references/boundaries/RULE.md```
### "I want to enforce architectural boundaries"
```Enforce boundaries?├─ Check for violations → turbo boundaries├─ Tag packages → references/boundaries/RULE.md#tags├─ Restrict which packages can import others → references/boundaries/RULE.md#rule-types└─ Prevent cross-package file imports → references/boundaries/RULE.md```
## Critical Anti-Patterns
### Using `turbo` Shorthand in Code
**`turbo run` is recommended in package.json scripts and CI pipelines.** The shorthand `turbo <task>` is intended for interactive terminal use.
```json// WRONG - using shorthand in package.json{ "scripts": { "build": "turbo build", "dev": "turbo dev" }}
// CORRECT{ "scripts": { "build": "turbo run build", "dev": "turbo run dev" }}```
```yaml# WRONG - using shorthand in CI- run: turbo build --affected
# CORRECT- run: turbo run build --affected```
### Root Scripts Bypassing Turbo
Root `package.json` scripts MUST delegate to `turbo run`, not run tasks directly.
```json// WRONG - bypasses turbo entirely{ "scripts": { "build": "bun build", "dev": "bun dev" }}
// CORRECT - delegates to turbo{ "scripts": { "build": "turbo run build", "dev": "turbo run dev" }}```
### Using `&&` to Chain Turbo Tasks
Don't chain turbo tasks with `&&`. Let turbo orchestrate.
```json// WRONG - turbo task not using turbo run{ "scripts": { "changeset:publish": "bun build && changeset publish" }}
// CORRECT{ "scripts": { "changeset:publish": "turbo run build && changeset publish" }}```
### `prebuild` Scripts That Manually Build Dependencies
Scripts like `prebuild` that manually build other packages bypass Turborepo's dependency graph.
```json// WRONG - manually building dependencies{ "scripts": { "prebuild": "cd ../../packages/types && bun run build && cd ../utils && bun run build", "build": "next build" }}```
**However, the fix depends on whether workspace dependencies are declared:**
1. **If dependencies ARE declared** (e.g., `"@repo/types": "workspace:*"` in package.json), remove the `prebuild` script. Turbo's `dependsOn: ["^build"]` handles this automatically.
2. **If dependencies are NOT declared**, the `prebuild` exists because `^build` won't trigger without a dependency relationship. The fix is to: - Add the dependency to package.json: `"@repo/types": "workspace:*"` - Then remove the `prebuild` script
```json// CORRECT - declare dependency, let turbo handle build order// package.json{ "dependencies": { "@repo/types": "workspace:*", "@repo/utils": "workspace:*" }, "scripts": { "build": "next build" }}
// turbo.json{ "tasks": { "build": { "dependsOn": ["^build"] } }}```
**Key insight:** `^build` only runs build in packages listed as dependencies. No dependency declaration = no automatic build ordering.
### Overly Broad `globalDependencies`
`globalDependencies` affects ALL tasks in ALL packages via the **global hash** — tasks cannot opt out of specific files, even with negation globs in `inputs`. Be specific.
```json// WRONG - heavy hammer, affects all hashes{ "globalDependencies": ["**/.env.*local"]}
// BETTER - move to task-level inputs{ "globalDependencies": [".env"], "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", ".env*"], "outputs": ["dist/**"] } }}```
With `futureFlags.globalConfiguration`, this problem is reduced because `global.inputs` files are folded into each task's inputs (not the global hash). Tasks can exclude specific files:
```json// BEST - global.inputs with per-task exclusion{ "futureFlags": { "globalConfiguration": true }, "global": { "inputs": [".env"] }, "tasks": { "build": { "outputs": ["dist/**"] }, "lint": { "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/.env"] } }}```
### Repetitive Task Configuration
Look for repeated configuration across tasks that can be collapsed. Turborepo supports shared configuration patterns.
```json// WRONG - repetitive env and inputs across tasks{ "tasks": { "build": { "env": ["API_URL", "DATABASE_URL"], "inputs": ["$TURBO_DEFAULT$", ".env*"] }, "test": { "env": ["API_URL", "DATABASE_URL"], "inputs": ["$TURBO_DEFAULT$", ".env*"] }, "dev": { "env": ["API_URL", "DATABASE_URL"], "inputs": ["$TURBO_DEFAULT$", ".env*"], "cache": false, "persistent": true } }}
// BETTER - use globalEnv and globalDependencies for shared config{ "globalEnv": ["API_URL", "DATABASE_URL"], "globalDependencies": [".env*"], "tasks": { "build": {}, "test": {}, "dev": { "cache": false, "persistent": true } }}```
**When to use global vs task-level:**
- `globalEnv` / `globalDependencies` - affects ALL tasks, use for truly shared config- Task-level `env` / `inputs` - use when only specific tasks need it
### NOT an Anti-Pattern: Large `env` Arrays
A large `env` array (even 50+ variables) is **not** a problem. It usually means the user was thorough about declaring their build's environment dependencies. Do not flag this as an issue.
### Using `--parallel` Flag
The `--parallel` flag bypasses Turborepo's dependency graph. If tasks need parallel execution, configure `dependsOn` correctly instead.
```bash# WRONG - bypasses dependency graphturbo run lint --parallel
# CORRECT - configure tasks to allow parallel execution# In turbo.json, set dependsOn appropriately (or use transit nodes)turbo run lint```
### Package-Specific Task Overrides in Root turbo.json
When multiple packages need different task configurations, use **Package Configurations** (`turbo.json` in each package) instead of cluttering root `turbo.json` with `package#task` overrides.
```json// WRONG - root turbo.json with many package-specific overrides{ "tasks": { "test": { "dependsOn": ["build"] }, "@repo/web#test": { "outputs": ["coverage/**"] }, "@repo/api#test": { "outputs": ["coverage/**"] }, "@repo/utils#test": { "outputs": [] }, "@repo/cli#test": { "outputs": [] }, "@repo/core#test": { "outputs": [] } }}
// CORRECT - use Package Configurations// Root turbo.json - base config only{ "tasks": { "test": { "dependsOn": ["build"] } }}
// packages/web/turbo.json - package-specific override{ "extends": ["//"], "tasks": { "test": { "outputs": ["coverage/**"] } }}
// packages/api/turbo.json{ "extends": ["//"], "tasks": { "test": { "outputs": ["coverage/**"] } }}```
**Benefits of Package Configurations:**
- Keeps configuration close to the code it affects- Root turbo.json stays clean and focused on base patterns- Easier to understand what's special about each package- Works with `$TURBO_EXTENDS$` to inherit + extend arrays
**When to use `package#task` in root:**
- Single package needs a unique dependency (e.g., `"deploy": { "dependsOn": ["web#build"] }`)- Temporary override while migrating
See `references/configuration/RULE.md#package-configurations` for full details.
### Using `../` to Traverse Out of Package in `inputs`
Don't use relative paths like `../` to reference files outside the package. Use `$TURBO_ROOT$` instead.
```json// WRONG - traversing out of package{ "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", "../shared-config.json"] } }}
// CORRECT - use $TURBO_ROOT$ for repo root{ "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/shared-config.json"] } }}```
### Missing `outputs` for File-Producing Tasks
**Before flagging missing `outputs`, check what the task actually produces:**
1. Read the package's script (e.g., `"build": "tsc"`, `"test": "vitest"`)2. Determine if it writes files to disk or only outputs to stdout3. Only flag if the task produces files that should be cached
```json// WRONG: build produces files but they're not cached{ "tasks": { "build": { "dependsOn": ["^build"] } }}
// CORRECT: build outputs are cached{ "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] } }}```
Common outputs by framework:
- Next.js: `[".next/**", "!.next/cache/**"]`- Vite/Rollup: `["dist/**"]`- tsc: `["dist/**"]` or custom `outDir`
**TypeScript `--noEmit` can still produce cache files:**
When `incremental: true` in tsconfig.json, `tsc --noEmit` writes `.tsbuildinfo` files even without emitting JS. Check the tsconfig before assuming no outputs:
```json// If tsconfig has incremental: true, tsc --noEmit produces cache files{ "tasks": { "typecheck": { "outputs": ["node_modules/.cache/tsbuildinfo.json"] // or wherever tsBuildInfoFile points } }}```
To determine correct outputs for TypeScript tasks:
1. Check if `incremental` or `composite` is enabled in tsconfig2. Check `tsBuildInfoFile` for custom cache location (default: alongside `outDir` or in project root)3. If no incremental mode, `tsc --noEmit` produces no files
### `^build` vs `build` Confusion
```json{ "tasks": { // ^build = run build in DEPENDENCIES first (other packages this one imports) "build": { "dependsOn": ["^build"] }, // build (no ^) = run build in SAME PACKAGE first "test": { "dependsOn": ["build"] }, // pkg#task = specific package's task "deploy": { "dependsOn": ["web#build"] } }}```
### Environment Variables Not Hashed
```json// WRONG: API_URL changes won't cause rebuilds{ "tasks": { "build": { "outputs": ["dist/**"] } }}
// CORRECT: API_URL changes invalidate cache{ "tasks": { "build": { "outputs": ["dist/**"], "env": ["API_URL", "API_KEY"] } }}```
### `.env` Files Not in Inputs
Turbo does NOT load `.env` files - your framework does. But Turbo needs to know about changes:
```json// WRONG: .env changes don't invalidate cache{ "tasks": { "build": { "env": ["API_URL"] } }}
// CORRECT: .env file changes invalidate cache{ "tasks": { "build": { "env": ["API_URL"], "inputs": ["$TURBO_DEFAULT$", ".env", ".env.*"] } }}```
### Root `.env` File in Monorepo
A `.env` file at the repo root is an anti-pattern — even for small monorepos or starter templates. It creates implicit coupling between packages and makes it unclear which packages depend on which variables.
```// WRONG - root .env affects all packages implicitlymy-monorepo/├── .env # Which packages use this?├── apps/│ ├── web/│ └── api/└── packages/
// CORRECT - .env files in packages that need themmy-monorepo/├── apps/│ ├── web/│ │ └── .env # Clear: web needs DATABASE_URL│ └── api/│ └── .env # Clear: api needs API_KEY└── packages/```
**Problems with root `.env`:**
- Unclear which packages consume which variables- All packages get all variables (even ones they don't need)- Cache invalidation is coarse-grained (root .env change invalidates everything)- Security risk: packages may accidentally access sensitive vars meant for others- Bad habits start small — starter templates should model correct patterns
**If you must share variables**, use `globalEnv` to be explicit about what's shared, and document why.
### Strict Mode Filtering CI Variables
By default, Turborepo filters environment variables to only those in `env`/`globalEnv`. CI variables may be missing:
```json// If CI scripts need GITHUB_TOKEN but it's not in env:{ "globalPassThroughEnv": ["GITHUB_TOKEN", "CI"], "tasks": { ... }}```
Or use `--env-mode=loose` (not recommended for production).
### Shared Code in Apps (Should Be a Package)
```// WRONG: Shared code inside an appapps/ web/ shared/ # This breaks monorepo principles! utils.ts
// CORRECT: Extract to a packagepackages/ utils/ src/utils.ts```
### Accessing Files Across Package Boundaries
```typescript// WRONG: Reaching into another package's internalsimport { Button } from "../../packages/ui/src/button";
// CORRECT: Install and import properlyimport { Button } from "@repo/ui/button";```
### Too Many Root Dependencies
```json// WRONG: App dependencies in root{ "dependencies": { "react": "^18", "next": "^14" }}
// CORRECT: Only repo tools in root{ "devDependencies": { "turbo": "latest" }}```
## Common Task Configurations
### Standard Build Pipeline
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**", ".next/**", "!.next/cache/**"] }, "dev": { "cache": false, "persistent": true } }}```
Add a `transit` task if you have tasks that need parallel execution with cache invalidation (see below).
### Dev Task with `^dev` Pattern (for `turbo watch`)
A `dev` task with `dependsOn: ["^dev"]` and `persistent: false` in root turbo.json may look unusual but is **correct for `turbo watch` workflows**:
```json// Root turbo.json{ "tasks": { "dev": { "dependsOn": ["^dev"], "cache": false, "persistent": false // Packages have one-shot dev scripts } }}
// Package turbo.json (apps/web/turbo.json){ "extends": ["//"], "tasks": { "dev": { "persistent": true // Apps run long-running dev servers } }}```
**Why this works:**
- **Packages** (e.g., `@acme/db`, `@acme/validators`) have `"dev": "tsc"` — one-shot type generation that completes quickly- **Apps** override with `persistent: true` for actual dev servers (Next.js, etc.)- **`turbo watch`** re-runs the one-shot package `dev` scripts when source files change, keeping types in sync
**Intended usage:** Run `turbo watch dev` (not `turbo run dev`). Watch mode re-executes one-shot tasks on file changes while keeping persistent tasks running.
**Alternative pattern:** Use a separate task name like `prepare` or `generate` for one-shot dependency builds to make the intent clearer:
```json{ "tasks": { "prepare": { "dependsOn": ["^prepare"], "outputs": ["dist/**"] }, "dev": { "dependsOn": ["prepare"], "cache": false, "persistent": true } }}```
### Transit Nodes for Parallel Tasks with Cache Invalidation
Some tasks can run in parallel (don't need built output from dependencies) but must invalidate cache when dependency source code changes.
**The problem with `dependsOn: ["^taskname"]`:**
- Forces sequential execution (slow)
**The problem with `dependsOn: []` (no dependencies):**
- Allows parallel execution (fast)- But cache is INCORRECT - changing dependency source won't invalidate cache
**Transit Nodes solve both:**
```json{ "tasks": { "transit": { "dependsOn": ["^transit"] }, "my-task": { "dependsOn": ["transit"] } }}```
The `transit` task creates dependency relationships without matching any actual script, so tasks run in parallel with correct cache invalidation.
**How to identify tasks that need this pattern:** Look for tasks that read source files from dependencies but don't need their build outputs.
### With Environment Variables
```json{ "globalEnv": ["NODE_ENV"], "globalDependencies": [".env"], "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"], "env": ["API_URL", "DATABASE_URL"] } }}```
With `futureFlags.globalConfiguration`, the same config moves global settings under `global` — and `.env` becomes a per-task input instead of a global hash input:
```json{ "futureFlags": { "globalConfiguration": true }, "global": { "env": ["NODE_ENV"], "inputs": [".env"] }, "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"], "env": ["API_URL", "DATABASE_URL"] } }}```
## Reference Index
### Configuration
| File | Purpose || ------------------------------------------------------------------------------- | ------------------------------------------------------------------------- || [configuration/RULE.md](./references/configuration/RULE.md) | turbo.json overview, Package Configurations || [configuration/tasks.md](./references/configuration/tasks.md) | dependsOn, outputs, inputs, env, cache, persistent || [configuration/global-options.md](./references/configuration/global-options.md) | globalEnv, globalDependencies, global key, futureFlags, cacheDir, envMode || [configuration/gotchas.md](./references/configuration/gotchas.md) | Common configuration mistakes |
### Caching
| File | Purpose || --------------------------------------------------------------- | -------------------------------------------- || [caching/RULE.md](./references/caching/RULE.md) | How caching works, hash inputs || [caching/remote-cache.md](./references/caching/remote-cache.md) | Vercel Remote Cache, self-hosted, login/link || [caching/gotchas.md](./references/caching/gotchas.md) | Debugging cache misses, --summarize, --dry |
### Environment Variables
| File | Purpose || ------------------------------------------------------------- | ----------------------------------------- || [environment/RULE.md](./references/environment/RULE.md) | env, globalEnv, passThroughEnv || [environment/modes.md](./references/environment/modes.md) | Strict vs Loose mode, framework inference || [environment/gotchas.md](./references/environment/gotchas.md) | .env files, CI issues |
### Filtering
| File | Purpose || ----------------------------------------------------------- | ------------------------ || [filtering/RULE.md](./references/filtering/RULE.md) | --filter syntax overview || [filtering/patterns.md](./references/filtering/patterns.md) | Common filter patterns |
### CI/CD
| File | Purpose || --------------------------------------------------------- | ------------------------------- || [ci/RULE.md](./references/ci/RULE.md) | General CI principles || [ci/github-actions.md](./references/ci/github-actions.md) | Complete GitHub Actions setup || [ci/vercel.md](./references/ci/vercel.md) | Vercel deployment, turbo-ignore || [ci/patterns.md](./references/ci/patterns.md) | --affected, caching strategies |
### CLI
| File | Purpose || ----------------------------------------------- | --------------------------------------------- || [cli/RULE.md](./references/cli/RULE.md) | turbo run basics || [cli/commands.md](./references/cli/commands.md) | turbo run flags, turbo-ignore, other commands |
### Best Practices
| File | Purpose || ----------------------------------------------------------------------------- | --------------------------------------------------------------- || [best-practices/RULE.md](./references/best-practices/RULE.md) | Monorepo best practices overview || [best-practices/structure.md](./references/best-practices/structure.md) | Repository structure, workspace config, TypeScript/ESLint setup || [best-practices/packages.md](./references/best-practices/packages.md) | Creating internal packages, JIT vs Compiled, exports || [best-practices/dependencies.md](./references/best-practices/dependencies.md) | Dependency management, installing, version sync |
### Watch Mode
| File | Purpose || ------------------------------------------- | ----------------------------------------------- || [watch/RULE.md](./references/watch/RULE.md) | turbo watch, interruptible tasks, dev workflows |
### Boundaries (Experimental)
| File | Purpose || ----------------------------------------------------- | ----------------------------------------------------- || [boundaries/RULE.md](./references/boundaries/RULE.md) | Enforce package isolation, tag-based dependency rules |
## Source Documentation
This skill is based on the official Turborepo documentation at:
- Source: `apps/docs/content/docs/` in the Turborepo repository- Live: https://turborepo.dev/docs12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970---description: Load Turborepo skill for creating workflows, tasks, and pipelines in monorepos. Use when users ask to "create a workflow", "make a task", "generate a pipeline", or set up build orchestration.---
Load the Turborepo skill and help with monorepo task orchestration: creating workflows, configuring tasks, setting up pipelines, and optimizing builds.
## Workflow
### Step 1: Load turborepo skill
```skill({ name: 'turborepo' })```
### Step 2: Identify task type from user request
Analyze $ARGUMENTS to determine:
- **Topic**: configuration, caching, filtering, environment, CI, or CLI- **Task type**: new setup, debugging, optimization, or implementation
Use decision trees in SKILL.md to select the relevant reference files.
### Step 3: Read relevant reference files
Based on task type, read from `references/<topic>/`:
| Task | Files to Read || -------------------- | ------------------------------------------------------- || Configure turbo.json | `configuration/RULE.md` + `configuration/tasks.md` || Debug cache issues | `caching/gotchas.md` || Set up remote cache | `caching/remote-cache.md` || Filter packages | `filtering/RULE.md` + `filtering/patterns.md` || Environment problems | `environment/gotchas.md` + `environment/modes.md` || Set up CI | `ci/RULE.md` + `ci/github-actions.md` or `ci/vercel.md` || CLI usage | `cli/commands.md` |
### Step 4: Execute task
Apply Turborepo-specific patterns from references to complete the user's request.
**CRITICAL - When creating tasks/scripts/pipelines:**
1. **DO NOT create Root Tasks** - Always create package tasks2. Add scripts to each relevant package's `package.json` (e.g., `apps/web/package.json`, `packages/ui/package.json`)3. Register the task in root `turbo.json`4. Root `package.json` only contains `turbo run <task>` - never actual task logic
**Other things to verify:**
- `outputs` defined for cacheable tasks- `dependsOn` uses correct syntax (`^task` vs `task`)- Environment variables in `env` key- `.env` files in `inputs` if used- Use `turbo run` (not `turbo`) in package.json and CI
### Step 5: Summarize
```=== Turborepo Task Complete ===
Topic: <configuration|caching|filtering|environment|ci|cli>Files referenced: <reference files consulted>
<brief summary of what was done>```
<user-request>$ARGUMENTS</user-request>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241# Monorepo Best Practices
Essential patterns for structuring and maintaining a healthy Turborepo monorepo.
## Repository Structure
### Standard Layout
```my-monorepo/├── apps/ # Application packages (deployable)│ ├── web/│ ├── docs/│ └── api/├── packages/ # Library packages (shared code)│ ├── ui/│ ├── utils/│ └── config-*/ # Shared configs (eslint, typescript, etc.)├── package.json # Root package.json (minimal deps)├── turbo.json # Turborepo configuration├── pnpm-workspace.yaml # (pnpm) or workspaces in package.json└── pnpm-lock.yaml # Lockfile (required)```
### Key Principles
1. **`apps/` for deployables**: Next.js sites, APIs, CLIs - things that get deployed2. **`packages/` for libraries**: Shared code consumed by apps or other packages3. **One purpose per package**: Each package should do one thing well4. **No nested packages**: Don't put packages inside packages
## Package Types
### Application Packages (`apps/`)
- **Deployable**: These are the "endpoints" of your package graph- **Not installed by other packages**: Apps shouldn't be dependencies of other packages- **No shared code**: If code needs sharing, extract to `packages/`
```json// apps/web/package.json{ "name": "web", "private": true, "dependencies": { "@repo/ui": "workspace:*", "next": "latest" }}```
### Library Packages (`packages/`)
- **Shared code**: Utilities, components, configs- **Namespaced names**: Use `@repo/` or `@yourorg/` prefix- **Clear exports**: Define what the package exposes
```json// packages/ui/package.json{ "name": "@repo/ui", "exports": { "./button": "./src/button.tsx", "./card": "./src/card.tsx" }}```
## Package Compilation Strategies
### Just-in-Time (Simplest)
Export TypeScript directly; let the app's bundler compile it.
```json{ "name": "@repo/ui", "exports": { "./button": "./src/button.tsx" }}```
**Pros**: Zero build config, instant changes**Cons**: Can't cache builds, requires app bundler support
### Compiled (Recommended for Libraries)
Package compiles itself with `tsc` or bundler.
```json{ "name": "@repo/ui", "exports": { "./button": { "types": "./src/button.tsx", "default": "./dist/button.js" } }, "scripts": { "build": "tsc" }}```
**Pros**: Cacheable by Turborepo, works everywhere**Cons**: More configuration
## Dependency Management
### Install Where Used
Install dependencies in the package that uses them, not the root.
```bash# Good: Install in the package that needs itpnpm add lodash --filter=@repo/utils
# Avoid: Installing everything at rootpnpm add lodash -w # Only for repo-level tools```
### Root Dependencies
Only these belong in root `package.json`:
- `turbo` - The build system- `husky`, `lint-staged` - Git hooks- Repository-level tooling
### Internal Dependencies
Use workspace protocol for internal packages:
```json// pnpm/bun{ "@repo/ui": "workspace:*" }
// npm/yarn{ "@repo/ui": "*" }```
## Exports Best Practices
### Use `exports` Field (Not `main`)
```json{ "exports": { ".": "./src/index.ts", "./button": "./src/button.tsx", "./utils": "./src/utils.ts" }}```
### Avoid Barrel Files
Don't create `index.ts` files that re-export everything:
```typescript// BAD: packages/ui/src/index.tsexport * from './button';export * from './card';export * from './modal';// ... imports everything even if you need one thing
// GOOD: Direct exports in package.json{ "exports": { "./button": "./src/button.tsx", "./card": "./src/card.tsx" }}```
### Namespace Your Packages
```json// Good{ "name": "@repo/ui" }{ "name": "@acme/utils" }
// Avoid (conflicts with npm registry){ "name": "ui" }{ "name": "utils" }```
## Common Anti-Patterns
### Accessing Files Across Package Boundaries
```typescript// BAD: Reaching into another packageimport { Button } from "../../packages/ui/src/button";
// GOOD: Install and import properlyimport { Button } from "@repo/ui/button";```
### Shared Code in Apps
```// BADapps/ web/ shared/ # This should be a package! utils.ts
// GOODpackages/ utils/ # Proper shared package src/utils.ts```
### Too Many Root Dependencies
```json// BAD: Root has app dependencies{ "dependencies": { "react": "^18", "next": "^14", "lodash": "^4" }}
// GOOD: Root only has repo tools{ "devDependencies": { "turbo": "latest", "husky": "latest" }}```
## See Also
- [structure.md](./structure.md) - Detailed repository structure patterns- [packages.md](./packages.md) - Creating and managing internal packages- [dependencies.md](./dependencies.md) - Dependency management strategies123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246# Dependency Management
Best practices for managing dependencies in a Turborepo monorepo.
## Core Principle: Install Where Used
Dependencies belong in the package that uses them, not the root.
```bash# Good: Install in specific packagepnpm add react --filter=@repo/uipnpm add next --filter=web
# Avoid: Installing in rootpnpm add react -w # Only for repo-level tools!```
## Benefits of Local Installation
### 1. Clarity
Each package's `package.json` lists exactly what it needs:
```json// packages/ui/package.json{ "dependencies": { "react": "^18.0.0", "class-variance-authority": "^0.7.0" }}```
### 2. Flexibility
Different packages can use different versions when needed:
```json// packages/legacy-ui/package.json{ "dependencies": { "react": "^17.0.0" } }
// packages/ui/package.json{ "dependencies": { "react": "^18.0.0" } }```
### 3. Better Caching
Installing in root changes workspace lockfile, invalidating all caches.
### 4. Pruning Support
`turbo prune` can remove unused dependencies for Docker images.
## What Belongs in Root
Only repository-level tools:
```json// Root package.json{ "devDependencies": { "turbo": "latest", "husky": "^8.0.0", "lint-staged": "^15.0.0" }}```
**NOT** application dependencies:
- react, next, express- lodash, axios, zod- Testing libraries (unless truly repo-wide)
## Installing Dependencies
### Single Package
```bash# pnpmpnpm add lodash --filter=@repo/utils
# npmnpm install lodash --workspace=@repo/utils
# yarnyarn workspace @repo/utils add lodash
# buncd packages/utils && bun add lodash```
### Multiple Packages
```bash# pnpmpnpm add jest --save-dev --filter=web --filter=@repo/ui
# npmnpm install jest --save-dev --workspace=web --workspace=@repo/ui
# yarn (v2+)yarn workspaces foreach -R --from '{web,@repo/ui}' add jest --dev```
### Internal Packages
```bash# pnpmpnpm add @repo/ui --filter=web
# This updates package.json:{ "dependencies": { "@repo/ui": "workspace:*" }}```
## Keeping Versions in Sync
### Option 1: Tooling
```bash# syncpack - Check and fix version mismatchesnpx syncpack list-mismatchesnpx syncpack fix-mismatches
# manypkg - Similar functionalitynpx @manypkg/cli checknpx @manypkg/cli fix
# sherif - Rust-based, very fastnpx sherif```
### Option 2: Package Manager Commands
```bash# pnpm - Update everywherepnpm up --recursive typescript@latest
# npm - Update in all workspacesnpm install typescript@latest --workspaces```
### Option 3: pnpm Catalogs (pnpm 9.5+)
```yaml# pnpm-workspace.yamlpackages: - "apps/*" - "packages/*"
catalog: react: ^18.2.0 typescript: ^5.3.0```
```json// Any package.json{ "dependencies": { "react": "catalog:" // Uses version from catalog }}```
## Internal vs External Dependencies
### Internal (Workspace)
```json// pnpm/bun{ "@repo/ui": "workspace:*" }
// npm/yarn{ "@repo/ui": "*" }```
Turborepo understands these relationships and orders builds accordingly.
### External (npm Registry)
```json{ "lodash": "^4.17.21" }```
Standard semver versioning from npm.
## Peer Dependencies
For library packages that expect the consumer to provide dependencies:
```json// packages/ui/package.json{ "peerDependencies": { "react": "^18.0.0", "react-dom": "^18.0.0" }, "devDependencies": { "react": "^18.0.0", // For development/testing "react-dom": "^18.0.0" }}```
## Common Issues
### "Module not found"
1. Check the dependency is installed in the right package2. Run `pnpm install` / `npm install` to update lockfile3. Check exports are defined in the package
### Version Conflicts
Packages can use different versions - this is a feature, not a bug. But if you need consistency:
1. Use tooling (syncpack, manypkg)2. Use pnpm catalogs3. Create a lint rule
### Hoisting Issues
Some tools expect dependencies in specific locations. Use package manager config:
```yaml# .npmrc (pnpm)public-hoist-pattern[]=*eslint*public-hoist-pattern[]=*prettier*```
## Lockfile
**Required** for:
- Reproducible builds- Turborepo dependency analysis- Cache correctness
```bash# Commit your lockfile!git add pnpm-lock.yaml # or package-lock.json, yarn.lock```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335# Creating Internal Packages
How to create and structure internal packages in your monorepo.
## Package Creation Checklist
1. Create directory in `packages/`2. Add `package.json` with name and exports3. Add source code in `src/`4. Add `tsconfig.json` if using TypeScript5. Install as dependency in consuming packages6. Run package manager install to update lockfile
## Package Compilation Strategies
### Just-in-Time (JIT)
Export TypeScript directly. The consuming app's bundler compiles it.
```json// packages/ui/package.json{ "name": "@repo/ui", "exports": { "./button": "./src/button.tsx", "./card": "./src/card.tsx" }, "scripts": { "lint": "eslint .", "check-types": "tsc --noEmit" }}```
**When to use:**
- Apps use modern bundlers (Turbopack, webpack, Vite)- You want minimal configuration- Build times are acceptable without caching
**Limitations:**
- No Turborepo cache for the package itself- Consumer must support TypeScript compilation- Can't use TypeScript `paths` (use Node.js subpath imports instead)
### Compiled
Package handles its own compilation.
```json// packages/ui/package.json{ "name": "@repo/ui", "exports": { "./button": { "types": "./src/button.tsx", "default": "./dist/button.js" } }, "scripts": { "build": "tsc", "dev": "tsc --watch" }}```
```json// packages/ui/tsconfig.json{ "extends": "@repo/typescript-config/library.json", "compilerOptions": { "outDir": "dist", "rootDir": "src" }, "include": ["src"], "exclude": ["node_modules", "dist"]}```
**When to use:**
- You want Turborepo to cache builds- Package will be used by non-bundler tools- You need maximum compatibility
**Remember:** Add `dist/**` to turbo.json outputs!
## Defining Exports
### Multiple Entrypoints
```json{ "exports": { ".": "./src/index.ts", // @repo/ui "./button": "./src/button.tsx", // @repo/ui/button "./card": "./src/card.tsx", // @repo/ui/card "./hooks": "./src/hooks/index.ts" // @repo/ui/hooks }}```
### Conditional Exports (Compiled)
```json{ "exports": { "./button": { "types": "./src/button.tsx", "import": "./dist/button.mjs", "require": "./dist/button.cjs", "default": "./dist/button.js" } }}```
## Installing Internal Packages
### Add to Consuming Package
```json// apps/web/package.json{ "dependencies": { "@repo/ui": "workspace:*" // pnpm/bun // "@repo/ui": "*" // npm/yarn }}```
### Run Install
```bashpnpm install # Updates lockfile with new dependency```
### Import and Use
```typescript// apps/web/src/page.tsximport { Button } from '@repo/ui/button';
export default function Page() { return <Button>Click me</Button>;}```
## One Purpose Per Package
### Good Examples
```packages/├── ui/ # Shared UI components├── utils/ # General utilities├── auth/ # Authentication logic├── database/ # Database client/schemas├── eslint-config/ # ESLint configuration├── typescript-config/ # TypeScript configuration└── api-client/ # Generated API client```
### Avoid Mega-Packages
```// BAD: One package for everythingpackages/└── shared/ ├── components/ ├── utils/ ├── hooks/ ├── types/ └── api/
// GOOD: Separate by purposepackages/├── ui/ # Components├── utils/ # Utilities├── hooks/ # React hooks├── types/ # Shared TypeScript types└── api-client/ # API utilities```
## Config Packages
### TypeScript Config
```json// packages/typescript-config/package.json{ "name": "@repo/typescript-config", "exports": { "./base.json": "./base.json", "./nextjs.json": "./nextjs.json", "./library.json": "./library.json" }}```
### ESLint Config
```json// packages/eslint-config/package.json{ "name": "@repo/eslint-config", "exports": { "./base": "./base.js", "./next": "./next.js" }, "dependencies": { "eslint": "^8.0.0", "eslint-config-next": "latest" }}```
## Common Mistakes
### Forgetting to Export
```json// BAD: No exports defined{ "name": "@repo/ui"}
// GOOD: Clear exports{ "name": "@repo/ui", "exports": { "./button": "./src/button.tsx" }}```
### Wrong Workspace Syntax
```json// pnpm/bun{ "@repo/ui": "workspace:*" } // Correct
// npm/yarn{ "@repo/ui": "*" } // Correct{ "@repo/ui": "workspace:*" } // Wrong for npm/yarn!```
### Missing from turbo.json Outputs
```json// Package builds to dist/, but turbo.json doesn't know{ "tasks": { "build": { "outputs": [".next/**"] // Missing dist/**! } }}
// Correct{ "tasks": { "build": { "outputs": [".next/**", "dist/**"] } }}```
## TypeScript Best Practices
### Use Node.js Subpath Imports (Not `paths`)
TypeScript `compilerOptions.paths` breaks with JIT packages. Use Node.js subpath imports instead (TypeScript 5.4+).
**JIT Package:**
```json// packages/ui/package.json{ "imports": { "#*": "./src/*" }}```
```typescript// packages/ui/button.tsximport { MY_STRING } from "#utils.ts"; // Uses .ts extension```
**Compiled Package:**
```json// packages/ui/package.json{ "imports": { "#*": "./dist/*" }}```
```typescript// packages/ui/button.tsximport { MY_STRING } from "#utils.js"; // Uses .js extension```
### Use `tsc` for Internal Packages
For internal packages, prefer `tsc` over bundlers. Bundlers can mangle code before it reaches your app's bundler, causing hard-to-debug issues.
### Enable Go-to-Definition
For Compiled Packages, enable declaration maps:
```json// tsconfig.json{ "compilerOptions": { "declaration": true, "declarationMap": true }}```
This creates `.d.ts` and `.d.ts.map` files for IDE navigation.
### No Root tsconfig.json Needed
Each package should have its own `tsconfig.json`. A root one causes all tasks to miss cache when changed. Only use root `tsconfig.json` for non-package scripts.
### Avoid TypeScript Project References
They add complexity and another caching layer. Turborepo handles dependencies better.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297# Repository Structure
Detailed guidance on structuring a Turborepo monorepo.
## Workspace Configuration
### pnpm (Recommended)
```yaml# pnpm-workspace.yamlpackages: - "apps/*" - "packages/*"```
### npm/yarn/bun
```json// package.json{ "workspaces": ["apps/*", "packages/*"]}```
## Root package.json
```json{ "name": "my-monorepo", "private": true, "packageManager": "pnpm@9.0.0", "scripts": { "build": "turbo run build", "dev": "turbo run dev", "lint": "turbo run lint", "test": "turbo run test" }, "devDependencies": { "turbo": "latest" }}```
Key points:
- `private: true` - Prevents accidental publishing- `packageManager` - Enforces consistent package manager version- **Scripts only delegate to `turbo run`** - No actual build logic here!- Minimal devDependencies (just turbo and repo tools)
## Always Prefer Package Tasks
**Always use package tasks. Only use Root Tasks if you cannot succeed with package tasks.**
```json// packages/web/package.json{ "scripts": { "build": "next build", "lint": "eslint .", "test": "vitest", "typecheck": "tsc --noEmit" }}
// packages/api/package.json{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest", "typecheck": "tsc --noEmit" }}```
Package tasks enable Turborepo to:
1. **Parallelize** - Run `web#lint` and `api#lint` simultaneously2. **Cache individually** - Each package's task output is cached separately3. **Filter precisely** - Run `turbo run test --filter=web` for just one package
**Root Tasks are a fallback** for tasks that truly cannot run per-package:
```json// AVOID unless necessary - sequential, not parallelized, can't filter{ "scripts": { "lint": "eslint apps/web && eslint apps/api && eslint packages/ui" }}```
## Root turbo.json
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**", ".next/**", "!.next/cache/**"] }, "lint": {}, "test": { "dependsOn": ["build"] }, "dev": { "cache": false, "persistent": true } }}```
With `futureFlags.globalConfiguration`, global settings move under a `global` key:
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "futureFlags": { "globalConfiguration": true }, "global": { "inputs": ["tsconfig.json"], "env": ["CI"] }, "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**", ".next/**", "!.next/cache/**"] }, "lint": {}, "test": { "dependsOn": ["build"] }, "dev": { "cache": false, "persistent": true } }}```
## Directory Organization
### Grouping Packages
You can group packages by adding more workspace paths:
```yaml# pnpm-workspace.yamlpackages: - "apps/*" - "packages/*" - "packages/config/*" # Grouped configs - "packages/features/*" # Feature packages```
This allows:
```packages/├── ui/├── utils/├── config/│ ├── eslint/│ ├── typescript/│ └── tailwind/└── features/ ├── auth/ └── payments/```
### What NOT to Do
```yaml# BAD: Nested wildcards cause ambiguous behaviorpackages: - "packages/**" # Don't do this!```
## Package Anatomy
### Minimum Required Files
```packages/ui/├── package.json # Required: Makes it a package├── src/ # Source code│ └── button.tsx└── tsconfig.json # TypeScript config (if using TS)```
### package.json Requirements
```json{ "name": "@repo/ui", // Unique, namespaced name "version": "0.0.0", // Version (can be 0.0.0 for internal) "private": true, // Prevents accidental publishing "exports": { // Entry points "./button": "./src/button.tsx" }}```
## TypeScript Configuration
### Shared Base Config
Create a shared TypeScript config package:
```packages/└── typescript-config/ ├── package.json ├── base.json ├── nextjs.json └── library.json```
```json// packages/typescript-config/base.json{ "compilerOptions": { "strict": true, "esModuleInterop": true, "skipLibCheck": true, "moduleResolution": "bundler", "module": "ESNext", "target": "ES2022" }}```
### Extending in Packages
```json// packages/ui/tsconfig.json{ "extends": "@repo/typescript-config/library.json", "compilerOptions": { "outDir": "dist", "rootDir": "src" }, "include": ["src"], "exclude": ["node_modules", "dist"]}```
### No Root tsconfig.json
You likely don't need a `tsconfig.json` in the workspace root. Each package should have its own config extending from the shared config package.
## ESLint Configuration
### Shared Config Package
```packages/└── eslint-config/ ├── package.json ├── base.js ├── next.js └── library.js```
```json// packages/eslint-config/package.json{ "name": "@repo/eslint-config", "exports": { "./base": "./base.js", "./next": "./next.js", "./library": "./library.js" }}```
### Using in Packages
```js// apps/web/.eslintrc.jsmodule.exports = { extends: ["@repo/eslint-config/next"],};```
## Lockfile
A lockfile is **required** for:
- Reproducible builds- Turborepo to understand package dependencies- Cache correctness
Without a lockfile, you'll see unpredictable behavior.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126# Boundaries
**Experimental feature** - See [RFC](https://github.com/vercel/turborepo/discussions/9435)
Full docs: https://turborepo.dev/docs/reference/boundaries
Boundaries enforce package isolation by detecting:
1. Imports of files outside the package's directory2. Imports of packages not declared in `package.json` dependencies
## Usage
```bashturbo boundaries```
Run this to check for workspace violations across your monorepo.
## Tags
Tags allow you to create rules for which packages can depend on each other.
### Adding Tags to a Package
```json// packages/ui/turbo.json{ "tags": ["internal"]}```
### Configuring Tag Rules
Rules go in root `turbo.json`:
```json// turbo.json{ "boundaries": { "tags": { "public": { "dependencies": { "deny": ["internal"] } } } }}```
This prevents `public`-tagged packages from importing `internal`-tagged packages.
### Rule Types
**Allow-list approach** (only allow specific tags):
```json{ "boundaries": { "tags": { "public": { "dependencies": { "allow": ["public"] } } } }}```
**Deny-list approach** (block specific tags):
```json{ "boundaries": { "tags": { "public": { "dependencies": { "deny": ["internal"] } } } }}```
**Restrict dependents** (who can import this package):
```json{ "boundaries": { "tags": { "private": { "dependents": { "deny": ["public"] } } } }}```
### Using Package Names
Package names work in place of tags:
```json{ "boundaries": { "tags": { "private": { "dependents": { "deny": ["@repo/my-pkg"] } } } }}```
## Key Points
- Rules apply transitively (dependencies of dependencies)- Helps enforce architectural boundaries at scale- Catches violations before runtime/build errors123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153# How Turborepo Caching Works
Turborepo's core principle: **never do the same work twice**.
## The Cache Equation
```fingerprint(inputs) → stored outputs```
If inputs haven't changed, restore outputs from cache instead of re-running the task.
## What Determines the Cache Key
### Global Hash Inputs
These affect ALL tasks in the repo:
- `package-lock.json` / `yarn.lock` / `pnpm-lock.yaml`- Files listed in `globalDependencies` (or `global.env` when using `globalConfiguration`)- Environment variables in `globalEnv` (or `global.env`)- `turbo.json` configuration
```json{ "globalDependencies": [".env", "tsconfig.base.json"], "globalEnv": ["CI", "NODE_ENV"]}```
### Task Hash Inputs
These affect specific tasks:
- All files in the package (unless filtered by `inputs`)- `package.json` contents- Environment variables in task's `env` key- Task configuration (command, outputs, dependencies)- Hashes of dependent tasks (`dependsOn`)- Files from `global.inputs` (when using `futureFlags.globalConfiguration` — see below)
```json{ "tasks": { "build": { "dependsOn": ["^build"], "inputs": ["src/**", "package.json", "tsconfig.json"], "env": ["API_URL"] } }}```
### How `global.inputs` Changes the Hash Equation
When `futureFlags.globalConfiguration` is enabled, `global.inputs` files are **not** part of the global hash. Instead, they are prepended to every task's `inputs` and folded into the **task hash**. This is a fundamental change from `globalDependencies`.
**With `globalDependencies` (default):**
```task cache key = hash(global hash, task hash) ↑ includes globalDependencies file hashes```
Changing a `globalDependencies` file invalidates **every** task, regardless of task-level `inputs`. There is no way for a task to opt out.
**With `global.inputs` (`futureFlags.globalConfiguration`):**
```task cache key = hash(global hash, task hash) ↑ includes global.inputs file hashes (merged with task inputs)```
`global.inputs` files are merged into each task's input globs. This means:
- Tasks can **exclude** specific global files with negation globs: `"inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/tsconfig.json"]`- The global hash is smaller (it still includes lockfile, engines, `global.env`, etc. — but not file hashes from `global.inputs`)- The task hash correctly includes the global input file hashes alongside the task's own inputs
```json{ "futureFlags": { "globalConfiguration": true }, "global": { "inputs": ["tsconfig.json", ".env"] }, "tasks": { "build": { "outputs": ["dist/**"] }, "lint": { "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/tsconfig.json"] } }}```
In this example, changing `tsconfig.json` invalidates `build` (it's in the task's inputs) but **not** `lint` (which explicitly excludes it). With `globalDependencies`, both would have been invalidated.
## What Gets Cached
1. **File outputs** - files/directories specified in `outputs`2. **Task logs** - stdout/stderr for replay on cache hit
```json{ "tasks": { "build": { "outputs": ["dist/**", ".next/**"] } }}```
## Local Cache Location
```.turbo/cache/├── <hash1>.tar.zst # compressed outputs├── <hash2>.tar.zst└── ...```
Add `.turbo` to `.gitignore`.
## Cache Restoration
On cache hit, Turborepo:
1. Extracts archived outputs to their original locations2. Replays the logged stdout/stderr3. Reports the task as cached (shows `FULL TURBO` in output)
## Example Flow
```bash# First run - executes build, caches resultturbo build# → packages/ui: cache miss, executing...# → packages/web: cache miss, executing...
# Second run - same inputs, restores from cacheturbo build# → packages/ui: cache hit, replaying output# → packages/web: cache hit, replaying output# → FULL TURBO```
## Key Points
- Cache is content-addressed (based on input hash, not timestamps)- Empty `outputs` array means task runs but nothing is cached- Tasks without `outputs` key cache nothing (use `"outputs": []` to be explicit)- Cache is invalidated when ANY input changes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190# Debugging Cache Issues
## Diagnostic Tools
### `--summarize`
Generates a JSON file with all hash inputs. Compare two runs to find differences.
```bashturbo build --summarize# Creates .turbo/runs/<run-id>.json```
The summary includes:
- Global hash and its inputs- Per-task hashes and their inputs- Environment variables that affected the hash
**Comparing runs:**
```bash# Run twice, compare the summariesdiff .turbo/runs/<first-run>.json .turbo/runs/<second-run>.json```
### `--dry` / `--dry=json`
See what would run without executing anything:
```bashturbo build --dryturbo build --dry=json # machine-readable output```
Shows cache status for each task without running them.
### `--force`
Skip reading cache, re-execute all tasks:
```bashturbo build --force```
Useful to verify tasks actually work (not just cached results).
## Unexpected Cache Misses
**Symptom:** Task runs when you expected a cache hit.
### Environment Variable Changed
Check if an env var in the `env` key changed:
```json{ "tasks": { "build": { "env": ["API_URL", "NODE_ENV"] } }}```
Different `API_URL` between runs = cache miss.
### .env File Changed
`.env` files aren't tracked by default. Add to `inputs`:
```json{ "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", ".env", ".env.local"] } }}```
Or use `globalDependencies` for repo-wide env files:
```json{ "globalDependencies": [".env"]}```
With `futureFlags.globalConfiguration`, use `global.inputs` instead. The key difference: `global.inputs` files are folded into each task's hash individually (not the global hash), so tasks can exclude specific files with negation globs.
```json{ "futureFlags": { "globalConfiguration": true }, "global": { "inputs": [".env"] }}```
### Lockfile Changed
Installing/updating packages changes the global hash.
### Source Files Changed
Any file in the package (or in `inputs`) triggers a miss.
### turbo.json Changed
Config changes invalidate the global hash.
## Incorrect Cache Hits
**Symptom:** Cached output is stale/wrong.
### Missing Environment Variable
Task uses an env var not listed in `env`:
```javascript// build.jsconst apiUrl = process.env.API_URL; // not tracked!```
Fix: add to task config:
```json{ "tasks": { "build": { "env": ["API_URL"] } }}```
### Missing File in Inputs
Task reads a file outside default inputs:
```json{ "tasks": { "build": { "inputs": [ "$TURBO_DEFAULT$", "../../shared-config.json" // file outside package ] } }}```
## Useful Flags
```bash# Only show output for cache missesturbo build --output-logs=new-only
# Show output for everything (debugging)turbo build --output-logs=full
# See why tasks are runningturbo build --verbosity=2```
## Debugging with `globalConfiguration` Enabled
When `futureFlags.globalConfiguration` is on, `global.inputs` files appear in per-task hash inputs (not the global hash). If you're getting unexpected cache misses:
1. Check `--summarize` output — global input files will show up in the **task inputs** section, not the global hash section2. Verify tasks aren't accidentally excluding global inputs via negation globs in `inputs`3. Remember that toggling the `globalConfiguration` flag itself invalidates all caches (the flag value is part of the global hash)
If you're getting unexpected cache **hits** after changing a global input file, the task may be excluding that file with a negation glob. Check the task's `inputs` for `!$TURBO_ROOT$/...` patterns.
## Quick Checklist
Cache miss when expected hit:
1. Run with `--summarize`, compare with previous run2. Check env vars with `--dry=json`3. Look for lockfile/config changes in git
Cache hit when expected miss:
1. Verify env var is in `env` array2. Verify file is in `inputs` array3. Check if file is outside package directory123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127# Remote Caching
Share cache artifacts across your team and CI pipelines.
## Benefits
- Team members get cache hits from each other's work- CI gets cache hits from local development (and vice versa)- Dramatically faster CI runs after first build- No more "works on my machine" rebuilds
## Vercel Remote Cache
Free, zero-config when deploying on Vercel. For local dev and other CI:
### Local Development Setup
```bash# Authenticate with Vercelnpx turbo login
# Link repo to your Vercel teamnpx turbo link```
This creates `.turbo/config.json` with your team info (gitignored by default).
### CI Setup
Set these environment variables:
```bashTURBO_TOKEN=<your-token>TURBO_TEAM=<your-team-slug>```
Get your token from Vercel dashboard → Settings → Tokens.
**GitHub Actions example:**
```yaml- name: Build run: npx turbo build env: TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ vars.TURBO_TEAM }}```
## Configuration in turbo.json
```json{ "remoteCache": { "enabled": true, "signature": false }}```
Options:
- `enabled`: toggle remote cache (default: true when authenticated)- `signature`: require artifact signing (default: false)
## Artifact Signing
Verify cache artifacts haven't been tampered with:
```bash# Set a secret key (use same key across all environments)export TURBO_REMOTE_CACHE_SIGNATURE_KEY="your-secret-key"```
Enable in config:
```json{ "remoteCache": { "signature": true }}```
Signed artifacts can only be restored if the signature matches.
## Self-Hosted Options
Community implementations for running your own cache server:
- **turbo-remote-cache** (Node.js) - supports S3, GCS, Azure- **turborepo-remote-cache** (Go) - lightweight, S3-compatible- **ducktape** (Rust) - high-performance option
Configure with environment variables:
```bashTURBO_API=https://your-cache-server.comTURBO_TOKEN=your-auth-tokenTURBO_TEAM=your-team```
## Cache Behavior Control
```bash# Disable remote cache for a runturbo build --remote-cache-read-only # read but don't writeturbo build --no-cache # skip cache entirely
# Environment variable alternativeTURBO_REMOTE_ONLY=true # only use remote, skip local```
## Debugging Remote Cache
```bash# Verbose output shows cache operationsturbo build --verbosity=2
# Check if remote cache is configuredturbo config```
Look for:
- "Remote caching enabled" in output- Upload/download messages during runs- "cache hit, replaying output" with remote cache indicator12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879# CI/CD with Turborepo
General principles for running Turborepo in continuous integration environments.
## Core Principles
### Always Use `turbo run` in CI
**Never use the `turbo <tasks>` shorthand in CI or scripts.** Always use `turbo run`:
```bash# CORRECT - Always use in CI, package.json, scriptsturbo run build test lint
# WRONG - Shorthand is only for one-off terminal commandsturbo build test lint```
The shorthand `turbo <tasks>` is only for one-off invocations typed directly in terminal by humans or agents. Anywhere the command is written into code (CI, package.json, scripts), use `turbo run`.
### Enable Remote Caching
Remote caching dramatically speeds up CI by sharing cached artifacts across runs.
Required environment variables:
```bashTURBO_TOKEN=your_vercel_tokenTURBO_TEAM=your_team_slug```
### Use --affected for PR Builds
The `--affected` flag only runs tasks for packages changed since the base branch:
```bashturbo run build test --affected```
This requires Git history to compute what changed.
## Git History Requirements
### Fetch Depth
`--affected` needs access to the merge base. Shallow clones break this.
```yaml# GitHub Actions- uses: actions/checkout@v4 with: fetch-depth: 2 # Minimum for --affected # Use 0 for full history if merge base is far```
### Why Shallow Clones Break --affected
Turborepo compares the current HEAD to the merge base with `main`. If that commit isn't fetched, `--affected` falls back to running everything.
For PRs with many commits, consider:
```yamlfetch-depth: 0 # Full history```
## Environment Variables Reference
| Variable | Purpose || ------------------- | ------------------------------------ || `TURBO_TOKEN` | Vercel access token for remote cache || `TURBO_TEAM` | Your Vercel team slug || `TURBO_REMOTE_ONLY` | Skip local cache, use remote only || `TURBO_LOG_ORDER` | Set to `grouped` for cleaner CI logs |
## See Also
- [github-actions.md](./github-actions.md) - GitHub Actions setup- [vercel.md](./vercel.md) - Vercel deployment- [patterns.md](./patterns.md) - CI optimization patterns123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162# GitHub Actions
Complete setup guide for Turborepo with GitHub Actions.
## Basic Workflow Structure
```yamlname: CI
on: push: branches: [main] pull_request: branches: [main]
jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 2
- uses: actions/setup-node@v4 with: node-version: 20
- name: Install dependencies run: npm ci
- name: Build and Test run: turbo run build test lint```
## Package Manager Setup
### pnpm
```yaml- uses: pnpm/action-setup@v3 with: version: 9
- uses: actions/setup-node@v4 with: node-version: 20 cache: "pnpm"
- run: pnpm install --frozen-lockfile```
### Yarn
```yaml- uses: actions/setup-node@v4 with: node-version: 20 cache: "yarn"
- run: yarn install --frozen-lockfile```
### Bun
```yaml- uses: oven-sh/setup-bun@v1 with: bun-version: latest
- run: bun install --frozen-lockfile```
## Remote Cache Setup
### 1. Create Vercel Access Token
1. Go to [Vercel Dashboard](https://vercel.com/account/tokens)2. Create a new token with appropriate scope3. Copy the token value
### 2. Add Secrets and Variables
In your GitHub repository settings:
**Secrets** (Settings > Secrets and variables > Actions > Secrets):
- `TURBO_TOKEN`: Your Vercel access token
**Variables** (Settings > Secrets and variables > Actions > Variables):
- `TURBO_TEAM`: Your Vercel team slug
### 3. Add to Workflow
```yamljobs: build: runs-on: ubuntu-latest env: TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ vars.TURBO_TEAM }}```
## Alternative: actions/cache
If you can't use remote cache, cache Turborepo's local cache directory:
```yaml- uses: actions/cache@v4 with: path: .turbo key: turbo-${{ runner.os }}-${{ hashFiles('**/turbo.json', '**/package-lock.json') }} restore-keys: | turbo-${{ runner.os }}-```
Note: This is less effective than remote cache since it's per-branch.
## Complete Example
```yamlname: CI
on: push: branches: [main] pull_request: branches: [main]
jobs: build: runs-on: ubuntu-latest env: TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ vars.TURBO_TEAM }}
steps: - uses: actions/checkout@v4 with: fetch-depth: 2
- uses: pnpm/action-setup@v3 with: version: 9
- uses: actions/setup-node@v4 with: node-version: 20 cache: "pnpm"
- name: Install dependencies run: pnpm install --frozen-lockfile
- name: Build run: turbo run build --affected
- name: Test run: turbo run test --affected
- name: Lint run: turbo run lint --affected```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145# CI Optimization Patterns
Strategies for efficient CI/CD with Turborepo.
## PR vs Main Branch Builds
### PR Builds: Only Affected
Test only what changed in the PR:
```yaml- name: Test (PR) if: github.event_name == 'pull_request' run: turbo run build test --affected```
### Main Branch: Full Build
Ensure complete validation on merge:
```yaml- name: Test (Main) if: github.ref == 'refs/heads/main' run: turbo run build test```
## Custom Git Ranges with --filter
For advanced scenarios, use `--filter` with git refs:
```bash# Changes since specific committurbo run test --filter="...[abc123]"
# Changes between refsturbo run test --filter="...[main...HEAD]"
# Changes in last 3 commitsturbo run test --filter="...[HEAD~3]"```
## Caching Strategies
### Remote Cache (Recommended)
Best performance - shared across all CI runs and developers:
```yamlenv: TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }} TURBO_TEAM: ${{ vars.TURBO_TEAM }}```
### actions/cache Fallback
When remote cache isn't available:
```yaml- uses: actions/cache@v4 with: path: .turbo key: turbo-${{ runner.os }}-${{ github.sha }} restore-keys: | turbo-${{ runner.os }}-${{ github.ref }}- turbo-${{ runner.os }}-```
Limitations:
- Cache is branch-scoped- PRs restore from base branch cache- Less efficient than remote cache
## Matrix Builds
Test across Node versions:
```yamlstrategy: matrix: node: [18, 20, 22]
steps: - uses: actions/setup-node@v4 with: node-version: ${{ matrix.node }}
- run: turbo run test```
## Parallelizing Across Jobs
Split tasks into separate jobs:
```yamljobs: lint: runs-on: ubuntu-latest steps: - run: turbo run lint --affected
test: runs-on: ubuntu-latest steps: - run: turbo run test --affected
build: runs-on: ubuntu-latest needs: [lint, test] steps: - run: turbo run build```
### Cache Considerations
When parallelizing:
- Each job has separate cache writes- Remote cache handles this automatically- With actions/cache, use unique keys per job to avoid conflicts
```yaml- uses: actions/cache@v4 with: path: .turbo key: turbo-${{ runner.os }}-${{ github.job }}-${{ github.sha }}```
## Conditional Tasks
Skip expensive tasks on draft PRs:
```yaml- name: E2E Tests if: github.event.pull_request.draft == false run: turbo run test:e2e --affected```
Or require label for full test:
```yaml- name: Full Test Suite if: contains(github.event.pull_request.labels.*.name, 'full-test') run: turbo run test```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103# Vercel Deployment
Turborepo integrates seamlessly with Vercel for monorepo deployments.
## Remote Cache
Remote caching is **automatically enabled** when deploying to Vercel. No configuration needed - Vercel detects Turborepo and enables caching.
This means:
- No `TURBO_TOKEN` or `TURBO_TEAM` setup required on Vercel- Cache is shared across all deployments- Preview and production builds benefit from cache
## turbo-ignore
Skip unnecessary builds when a package hasn't changed using `turbo-ignore`.
### Installation
```bashnpx turbo-ignore```
Or install globally in your project:
```bashpnpm add -D turbo-ignore```
### Setup in Vercel
1. Go to your project in Vercel Dashboard2. Navigate to Settings > Git > Ignored Build Step3. Select "Custom" and enter:
```bashnpx turbo-ignore```
### How It Works
`turbo-ignore` checks if the current package (or its dependencies) changed since the last successful deployment:
1. Compares current commit to last deployed commit2. Uses Turborepo's dependency graph3. Returns exit code 0 (skip) if no changes4. Returns exit code 1 (build) if changes detected
### Options
```bash# Check specific packagenpx turbo-ignore web
# Use specific comparison refnpx turbo-ignore --fallback=HEAD~1
# Verbose outputnpx turbo-ignore --verbose```
## Environment Variables
Set environment variables in Vercel Dashboard:
1. Go to Project Settings > Environment Variables2. Add variables for each environment (Production, Preview, Development)
Common variables:
- `DATABASE_URL`- `API_KEY`- Package-specific config
## Monorepo Root Directory
For monorepos, set the root directory in Vercel:
1. Project Settings > General > Root Directory2. Set to the package path (e.g., `apps/web`)
Vercel automatically:
- Installs dependencies from monorepo root- Runs build from the package directory- Detects framework settings
## Build Command
Vercel auto-detects `turbo run build` when `turbo.json` exists at root.
Override if needed:
```bashturbo run build --filter=web```
Or for production-only optimizations:
```bashturbo run build --filter=web --env-mode=strict```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100# turbo run
The primary command for executing tasks across your monorepo.
## Basic Usage
```bash# Full form (use in CI, package.json, scripts)turbo run <tasks>
# Shorthand (only for one-off terminal invocations)turbo <tasks>```
## When to Use `turbo run` vs `turbo`
**Always use `turbo run` when the command is written into code:**
- `package.json` scripts- CI/CD workflows (GitHub Actions, etc.)- Shell scripts- Documentation- Any static/committed configuration
**Only use `turbo` (shorthand) for:**
- One-off commands typed directly in terminal- Ad-hoc invocations by humans or agents
```json// package.json - ALWAYS use "turbo run"{ "scripts": { "build": "turbo run build", "dev": "turbo run dev", "lint": "turbo run lint", "test": "turbo run test" }}```
```yaml# CI workflow - ALWAYS use "turbo run"- run: turbo run build --affected- run: turbo run test --affected```
```bash# Terminal one-off - shorthand OKturbo build --filter=web```
## Running Tasks
Tasks must be defined in `turbo.json` before running.
```bash# Single taskturbo build
# Multiple tasksturbo run build lint test
# See available tasks (run without arguments)turbo run```
## Passing Arguments to Scripts
Use `--` to pass arguments through to the underlying package scripts:
```bashturbo run build -- --sourcemapturbo test -- --watchturbo lint -- --fix```
Everything after `--` goes directly to the task's script.
## Package Selection
By default, turbo runs tasks in all packages. Use `--filter` to narrow scope:
```bashturbo build --filter=webturbo test --filter=./apps/*```
See `filtering/` for complete filter syntax.
## Quick Reference
| Goal | Command || ------------------- | -------------------------- || Build everything | `turbo build` || Build one package | `turbo build --filter=web` || Multiple tasks | `turbo build lint test` || Pass args to script | `turbo build -- --arg` || Preview run | `turbo build --dry` || Force rebuild | `turbo build --force` |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297# turbo run Flags Reference
Full docs: https://turborepo.dev/docs/reference/run
## Package Selection
### `--filter` / `-F`
Select specific packages to run tasks in.
```bashturbo build --filter=webturbo build -F=@repo/ui -F=@repo/utilsturbo test --filter=./apps/*```
See `filtering/` for complete syntax (globs, dependencies, git ranges).
### Task Identifier Syntax (v2.2.4+)
Run specific package tasks directly:
```bashturbo run web#build # Build web packageturbo run web#build docs#lint # Multiple specific tasks```
### `--affected`
Run only in packages changed since the base branch.
```bashturbo build --affectedturbo test --affected --filter=./apps/* # combine with filter```
**How it works:**
- Default: compares `main...HEAD`- In GitHub Actions: auto-detects `GITHUB_BASE_REF`- Override base: `TURBO_SCM_BASE=development turbo build --affected`- Override head: `TURBO_SCM_HEAD=your-branch turbo build --affected`
**Requires git history** - shallow clones may fall back to running all tasks.
## Execution Control
### `--dry` / `--dry=json`
Preview what would run without executing.
```bashturbo build --dry # human-readableturbo build --dry=json # machine-readable```
### `--force`
Ignore all cached artifacts, re-run everything.
```bashturbo build --force```
### `--concurrency`
Limit parallel task execution.
```bashturbo build --concurrency=4 # max 4 tasksturbo build --concurrency=50% # 50% of CPU cores```
### `--continue`
Keep running other tasks when one fails.
```bashturbo build test --continue```
### `--only`
Run only the specified task, skip its dependencies.
```bashturbo build --only # skip running dependsOn tasks```
### `--parallel` (Discouraged)
Ignores task graph dependencies, runs all tasks simultaneously. **Avoid using this flag**—if tasks need to run in parallel, configure `dependsOn` correctly instead. Using `--parallel` bypasses Turborepo's dependency graph, which can cause race conditions and incorrect builds.
## Cache Control
### `--cache`
Fine-grained cache behavior control.
```bash# Default: read/write both local and remoteturbo build --cache=local:rw,remote:rw
# Read-only local, no remoteturbo build --cache=local:r,remote:
# Disable local, read-only remoteturbo build --cache=local:,remote:r
# Disable all cachingturbo build --cache=local:,remote:```
## Output & Debugging
### `--graph`
Generate task graph visualization.
```bashturbo build --graph # opens in browserturbo build --graph=graph.svg # SVG fileturbo build --graph=graph.png # PNG fileturbo build --graph=graph.json # JSON dataturbo build --graph=graph.mermaid # Mermaid diagram```
### `--summarize`
Generate JSON run summary for debugging.
```bashturbo build --summarize# creates .turbo/runs/<run-id>.json```
### `--output-logs`
Control log output verbosity.
```bashturbo build --output-logs=full # all logs (default)turbo build --output-logs=new-only # only cache missesturbo build --output-logs=errors-only # only failuresturbo build --output-logs=none # silent```
### `--profile`
Generate Chrome tracing profile for performance analysis.
```bashturbo build --profile=profile.json# open chrome://tracing and load the file```
### `--verbosity` / `-v`
Control turbo's own log level.
```bashturbo build -v # verboseturbo build -vv # more verboseturbo build -vvv # maximum verbosity```
## Environment
### `--env-mode`
Control environment variable handling.
```bashturbo build --env-mode=strict # only declared env vars (default)turbo build --env-mode=loose # include all env vars in hash```
## UI
### `--ui`
Select output interface.
```bashturbo build --ui=tui # interactive terminal UI (default in TTY)turbo build --ui=stream # streaming logs (default in CI)```
---
# turbo-ignore
Full docs: https://turborepo.dev/docs/reference/turbo-ignore
Skip CI work when nothing relevant changed. Useful for skipping container setup.
## Basic Usage
```bash# Check if build is needed for current package (uses Automatic Package Scoping)npx turbo-ignore
# Check specific packagenpx turbo-ignore web
# Check specific tasknpx turbo-ignore --task=test```
## Exit Codes
- `0`: No changes detected - skip CI work- `1`: Changes detected - proceed with CI
## CI Integration Example
```yaml# GitHub Actions- name: Check for changes id: turbo-ignore run: npx turbo-ignore web continue-on-error: true
- name: Build if: steps.turbo-ignore.outcome == 'failure' # changes detected run: pnpm build```
## Comparison Depth
Default: compares to parent commit (`HEAD^1`).
```bash# Compare to specific commitnpx turbo-ignore --fallback=abc123
# Compare to branchnpx turbo-ignore --fallback=main```
---
# Other Commands
## turbo boundaries
Check workspace violations (experimental).
```bashturbo boundaries```
See `references/boundaries/` for configuration.
## turbo watch
Re-run tasks on file changes.
```bashturbo watch build test```
See `references/watch/` for details.
## turbo prune
Create sparse checkout for Docker.
```bashturbo prune web --docker```
## turbo link / unlink
Connect/disconnect Remote Cache.
```bashturbo link # connect to Vercel Remote Cacheturbo unlink # disconnect```
## turbo login / logout
Authenticate with Remote Cache provider.
```bashturbo login # authenticateturbo logout # log out```
## turbo generate
Scaffold new packages.
```bashturbo generate```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235# turbo.json Configuration Overview
Configuration reference for Turborepo. Full docs: https://turborepo.dev/docs/reference/configuration
## File Location
Root `turbo.json` lives at repo root, sibling to root `package.json`:
```my-monorepo/├── turbo.json # Root configuration├── package.json└── packages/ └── web/ ├── turbo.json # Package Configuration (optional) └── package.json```
## Always Prefer Package Tasks Over Root Tasks
**Always use package tasks. Only use Root Tasks if you cannot succeed with package tasks.**
Package tasks enable parallelization, individual caching, and filtering. Define scripts in each package's `package.json`:
```json// packages/web/package.json{ "scripts": { "build": "next build", "lint": "eslint .", "test": "vitest", "typecheck": "tsc --noEmit" }}
// packages/api/package.json{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest", "typecheck": "tsc --noEmit" }}```
```json// Root package.json - delegates to turbo{ "scripts": { "build": "turbo run build", "lint": "turbo run lint", "test": "turbo run test", "typecheck": "turbo run typecheck" }}```
When you run `turbo run lint`, Turborepo finds all packages with a `lint` script and runs them **in parallel**.
**Root Tasks are a fallback**, not the default. Only use them for tasks that truly cannot run per-package (e.g., repo-level CI scripts, workspace-wide config generation).
```json// AVOID: Task logic in root defeats parallelization{ "scripts": { "lint": "eslint apps/web && eslint apps/api && eslint packages/ui" }}```
## Basic Structure
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "globalEnv": ["CI"], "globalDependencies": ["tsconfig.json"], "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] }, "dev": { "cache": false, "persistent": true } }}```
The `$schema` key enables IDE autocompletion and validation.
### With `futureFlags.globalConfiguration`
When the `globalConfiguration` future flag is enabled, global options move under a `global` key with cleaner names:
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "futureFlags": { "globalConfiguration": true }, "global": { "inputs": ["tsconfig.json"], "env": ["CI"], "ui": "tui" }, "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] } }}```
See the [global options reference](./global-options.md) for the full rename mapping and behavior changes.
## Configuration Sections
**Global options** - Settings affecting all tasks:
- Without flag: `globalEnv`, `globalDependencies`, `globalPassThroughEnv`, `cacheDir`, `daemon`, `envMode`, `ui`, `remoteCache`- With `globalConfiguration` flag: all of the above move under the `global` key (see [global options](./global-options.md))
**Task definitions** - Per-task settings in `tasks` object:
- `dependsOn`, `outputs`, `inputs`, `env`- `cache`, `persistent`, `interactive`, `outputLogs`
## Package Configurations
Use `turbo.json` in individual packages to override root settings:
```json// packages/web/turbo.json{ "extends": ["//"], "tasks": { "build": { "outputs": [".next/**", "!.next/cache/**"] } }}```
The `"extends": ["//"]` is required - it references the root configuration.
**When to use Package Configurations:**
- Framework-specific outputs (Next.js, Vite, etc.)- Package-specific env vars- Different caching rules for specific packages- Keeping framework config close to the framework code
### Extending from Other Packages
You can extend from config packages instead of just root:
```json// packages/web/turbo.json{ "extends": ["//", "@repo/turbo-config"]}```
### Adding to Inherited Arrays with `$TURBO_EXTENDS$`
By default, array fields in Package Configurations **replace** root values. Use `$TURBO_EXTENDS$` to **append** instead:
```json// Root turbo.json{ "tasks": { "build": { "outputs": ["dist/**"] } }}```
```json// packages/web/turbo.json{ "extends": ["//"], "tasks": { "build": { // Inherits "dist/**" from root, adds ".next/**" "outputs": ["$TURBO_EXTENDS$", ".next/**", "!.next/cache/**"] } }}```
Without `$TURBO_EXTENDS$`, outputs would only be `[".next/**", "!.next/cache/**"]`.
**Works with:**
- `dependsOn`- `env`- `inputs`- `outputs`- `passThroughEnv`- `with`
### Excluding Tasks from Packages
Use `extends: false` to exclude a task from a package:
```json// packages/ui/turbo.json{ "extends": ["//"], "tasks": { "e2e": { "extends": false // UI package doesn't have e2e tests } }}```
## `turbo.jsonc` for Comments
Use `turbo.jsonc` extension to add comments with IDE support:
```jsonc// turbo.jsonc{ "tasks": { "build": { // Next.js outputs "outputs": [".next/**", "!.next/cache/**"], }, },}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239# Global Options Reference
Options that affect all tasks. Full docs: https://turborepo.dev/docs/reference/configuration
## globalEnv
Environment variables affecting all task hashes.
```json{ "globalEnv": ["CI", "NODE_ENV", "VERCEL_*"]}```
Use for variables that should invalidate all caches when changed.
## globalDependencies
Files that affect all task hashes.
```json{ "globalDependencies": ["tsconfig.json", ".env", "pnpm-lock.yaml"]}```
Lockfile is included by default. Add shared configs here.
## globalPassThroughEnv
Variables available to tasks but not included in hash.
```json{ "globalPassThroughEnv": ["AWS_SECRET_KEY", "GITHUB_TOKEN"]}```
Use for credentials that shouldn't affect cache keys.
## cacheDir
Custom cache location. Default: `node_modules/.cache/turbo`.
```json{ "cacheDir": ".turbo/cache"}```
## daemon
**Deprecated**: The daemon is no longer used for `turbo run` and this option will be removed in version 3.0. The daemon is still used by `turbo watch` and the Turborepo LSP.
## envMode
How unspecified env vars are handled. Default: `"strict"`.
```json{ "envMode": "strict" // Only specified vars available // or "envMode": "loose" // All vars pass through}```
Strict mode catches missing env declarations.
## ui
Terminal UI mode. Default: `"stream"`.
```json{ "ui": "tui" // Interactive terminal UI // or "ui": "stream" // Traditional streaming logs}```
TUI provides better UX for parallel tasks.
## remoteCache
Configure remote caching.
```json{ "remoteCache": { "enabled": true, "signature": true, "timeout": 30, "uploadTimeout": 60 }}```
| Option | Default | Description || --------------- | ---------------------- | ------------------------------------------------------ || `enabled` | `true` | Enable/disable remote caching || `signature` | `false` | Sign artifacts with `TURBO_REMOTE_CACHE_SIGNATURE_KEY` || `preflight` | `false` | Send OPTIONS request before cache requests || `timeout` | `30` | Timeout in seconds for cache operations || `uploadTimeout` | `60` | Timeout in seconds for uploads || `apiUrl` | `"https://vercel.com"` | Remote cache API endpoint || `loginUrl` | `"https://vercel.com"` | Login endpoint || `teamId` | - | Team ID (must start with `team_`) || `teamSlug` | - | Team slug for querystring |
See https://turborepo.dev/docs/core-concepts/remote-caching for setup.
## concurrency
Default: `"10"`
Limit parallel task execution.
```json{ "concurrency": "4" // Max 4 tasks at once // or "concurrency": "50%" // 50% of available CPUs}```
## futureFlags
Enable experimental features that will become default in future versions.
```json{ "futureFlags": { "errorsOnlyShowHash": true }}```
### `errorsOnlyShowHash`
When using `outputLogs: "errors-only"`, show task hashes on start/completion:
- Cache miss: `cache miss, executing <hash> (only logging errors)`- Cache hit: `cache hit, replaying logs (no errors) <hash>`
### `longerSignatureKey`
Enforce a minimum key length of 32 bytes for `TURBO_REMOTE_CACHE_SIGNATURE_KEY` when `remoteCache.signature` is enabled. Short keys weaken HMAC-SHA256 signatures. Fails the run immediately if the key is too short.
### `globalConfiguration`
Moves global configuration keys under a top-level `global` key for clarity and changes how `global.inputs` (formerly `globalDependencies`) affects task hashing.
When enabled:
- Global config keys move under `global` with cleaner names- `global.inputs` files are **prepended to every task's inputs** instead of being folded into the global hash — tasks can opt out of specific global inputs using negation globs
```json{ "futureFlags": { "globalConfiguration": true }, "global": { "inputs": ["tsconfig.json", ".env"], "env": ["CI", "NODE_ENV"], "passThroughEnv": ["AWS_SECRET_KEY"], "ui": "tui", "envMode": "strict", "cacheDir": ".turbo/cache", "remoteCache": { "enabled": true }, "concurrency": "50%" }, "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] } }}```
**Key rename mapping:**
| Old (top-level) | New (`global.`) || -------------------------------------------------------------------------------------------------------------------------------- | ------------------------- || `globalDependencies` | `inputs` || `globalEnv` | `env` || `globalPassThroughEnv` | `passThroughEnv` || `ui`, `envMode`, `cacheDir`, `daemon`, `concurrency`, `noUpdateNotifier`, `dangerouslyDisablePackageManagerCheck`, `remoteCache` | Same names under `global` |
**Behavior change for `global.inputs`:**
With `globalDependencies` (old): files are hashed into the **global hash**, which is embedded in every task's cache key. Changing any of these files invalidates all tasks — there is no opt-out.
With `global.inputs` (new): files are treated as **implicit task inputs** prepended to each task's `inputs` globs. This means:
- Tasks can exclude specific global files: `"inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/tsconfig.json"]`- The global hash no longer includes these file hashes (it still includes lockfile, engines, global env, etc.)- Tasks with no explicit `inputs` still hash all package files plus the global inputs
See the [gotchas doc](./gotchas.md) for guidance on using `$TURBO_DEFAULT$` with `global.inputs`.
## noUpdateNotifier
Disable update notifications when new turbo versions are available.
```json{ "noUpdateNotifier": true}```
## dangerouslyDisablePackageManagerCheck
Bypass the `packageManager` field requirement. Use for incremental migration.
```json{ "dangerouslyDisablePackageManagerCheck": true}```
**Warning**: Unstable lockfiles can cause unpredictable behavior.
## Git Worktree Cache Sharing
When working in Git worktrees, Turborepo automatically shares local cache between the main worktree and linked worktrees.
**How it works:**
- Detects worktree configuration- Redirects cache to main worktree's `.turbo/cache`- Works alongside Remote Cache
**Benefits:**
- Cache hits across branches- Reduced disk usage- Faster branch switching
**Disabled by**: Setting explicit `cacheDir` in turbo.json.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368# Configuration Gotchas
Common mistakes and how to fix them.
## #1 Root Scripts Not Using `turbo run`
Root `package.json` scripts for turbo tasks MUST use `turbo run`, not direct commands.
```json// WRONG - bypasses turbo, no parallelization or caching{ "scripts": { "build": "bun build", "dev": "bun dev" }}
// CORRECT - delegates to turbo{ "scripts": { "build": "turbo run build", "dev": "turbo run dev" }}```
**Why this matters:** Running `bun build` or `npm run build` at root bypasses Turborepo entirely - no parallelization, no caching, no dependency graph awareness.
## #2 Using `&&` to Chain Turbo Tasks
Don't use `&&` to chain tasks that turbo should orchestrate.
```json// WRONG - changeset:publish chains turbo task with non-turbo command{ "scripts": { "changeset:publish": "bun build && changeset publish" }}
// CORRECT - use turbo run, let turbo handle dependencies{ "scripts": { "changeset:publish": "turbo run build && changeset publish" }}```
If the second command (`changeset publish`) depends on build outputs, the turbo task should run through turbo to get caching and parallelization benefits.
## #3 Overly Broad globalDependencies
`globalDependencies` affects hash for ALL tasks in ALL packages. Be specific.
```json// WRONG - affects all hashes{ "globalDependencies": ["**/.env.*local"]}
// CORRECT - move to specific tasks that need it{ "globalDependencies": [".env"], "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", ".env*"], "outputs": ["dist/**"] } }}```
**Why this matters:** `**/.env.*local` matches .env files in ALL packages, causing unnecessary cache invalidation. Instead:
- Use `globalDependencies` only for truly global files (root `.env`)- Use task-level `inputs` for package-specific .env files with `$TURBO_DEFAULT$` to preserve default behavior
With `futureFlags.globalConfiguration`, this is less of a concern because `global.inputs` acts as implicit task inputs — tasks can opt out of specific files with negation globs. But keeping the list focused is still good practice.
## #4 Repetitive Task Configuration
Look for repeated configuration across tasks that can be collapsed.
```json// WRONG - repetitive env and inputs across tasks{ "tasks": { "build": { "env": ["API_URL", "DATABASE_URL"], "inputs": ["$TURBO_DEFAULT$", ".env*"] }, "test": { "env": ["API_URL", "DATABASE_URL"], "inputs": ["$TURBO_DEFAULT$", ".env*"] } }}
// BETTER - use globalEnv and globalDependencies{ "globalEnv": ["API_URL", "DATABASE_URL"], "globalDependencies": [".env*"], "tasks": { "build": {}, "test": {} }}```
**When to use global vs task-level:**
- `globalEnv` / `globalDependencies` - affects ALL tasks, use for truly shared config- Task-level `env` / `inputs` - use when only specific tasks need it
## #5 Using `../` to Traverse Out of Package in `inputs`
Don't use relative paths like `../` to reference files outside the package. Use `$TURBO_ROOT$` instead.
```json// WRONG - traversing out of package{ "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", "../shared-config.json"] } }}
// CORRECT - use $TURBO_ROOT$ for repo root{ "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/shared-config.json"] } }}```
## #6 MOST COMMON MISTAKE: Creating Root Tasks
**DO NOT create Root Tasks. ALWAYS create package tasks.**
When you need to create a task (build, lint, test, typecheck, etc.):
1. Add the script to **each relevant package's** `package.json`2. Register the task in root `turbo.json`3. Root `package.json` only contains `turbo run <task>`
```json// WRONG - DO NOT DO THIS// Root package.json with task logic{ "scripts": { "build": "cd apps/web && next build && cd ../api && tsc", "lint": "eslint apps/ packages/", "test": "vitest" }}
// CORRECT - DO THIS// apps/web/package.json{ "scripts": { "build": "next build", "lint": "eslint .", "test": "vitest" } }
// apps/api/package.json{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
// packages/ui/package.json{ "scripts": { "build": "tsc", "lint": "eslint .", "test": "vitest" } }
// Root package.json - ONLY delegates{ "scripts": { "build": "turbo run build", "lint": "turbo run lint", "test": "turbo run test" } }
// turbo.json - register tasks{ "tasks": { "build": { "dependsOn": ["^build"], "outputs": ["dist/**"] }, "lint": {}, "test": {} }}```
**Why this matters:**
- Package tasks run in **parallel** across all packages- Each package's output is cached **individually**- You can **filter** to specific packages: `turbo run test --filter=web`
Root Tasks (`//#taskname`) defeat all these benefits. Only use them for tasks that truly cannot exist in any package (extremely rare).
## #7 Tasks That Need Parallel Execution + Cache Invalidation
Some tasks can run in parallel (don't need built output from dependencies) but must still invalidate cache when dependency source code changes. Using `dependsOn: ["^taskname"]` forces sequential execution. Using no dependencies breaks cache invalidation.
**Use Transit Nodes for these tasks:**
```json// WRONG - forces sequential execution (SLOW)"my-task": { "dependsOn": ["^my-task"]}
// ALSO WRONG - no dependency awareness (INCORRECT CACHING)"my-task": {}
// CORRECT - use Transit Nodes for parallel + correct caching{ "tasks": { "transit": { "dependsOn": ["^transit"] }, "my-task": { "dependsOn": ["transit"] } }}```
**Why Transit Nodes work:**
- `transit` creates dependency relationships without matching any actual script- Tasks that depend on `transit` gain dependency awareness- Since `transit` completes instantly (no script), tasks run in parallel- Cache correctly invalidates when dependency source code changes
**How to identify tasks that need this pattern:** Look for tasks that read source files from dependencies but don't need their build outputs.
## Missing outputs for File-Producing Tasks
**Before flagging missing `outputs`, check what the task actually produces:**
1. Read the package's script (e.g., `"build": "tsc"`, `"test": "vitest"`)2. Determine if it writes files to disk or only outputs to stdout3. Only flag if the task produces files that should be cached
```json// WRONG - build produces files but they're not cached"build": { "dependsOn": ["^build"]}
// CORRECT - outputs are cached"build": { "dependsOn": ["^build"], "outputs": ["dist/**"]}```
No `outputs` key is fine for stdout-only tasks. For file-producing tasks, missing `outputs` means Turbo has nothing to cache.
## Forgetting ^ in dependsOn
```json// WRONG - looks for "build" in SAME package (infinite loop or missing)"build": { "dependsOn": ["build"]}
// CORRECT - runs dependencies' build first"build": { "dependsOn": ["^build"]}```
The `^` means "in dependency packages", not "in this package".
## Missing persistent on Dev Tasks
```json// WRONG - dependent tasks hang waiting for dev to "finish""dev": { "cache": false}
// CORRECT"dev": { "cache": false, "persistent": true}```
## Package Config Missing extends
```json// WRONG - packages/web/turbo.json{ "tasks": { "build": { "outputs": [".next/**"] } }}
// CORRECT{ "extends": ["//"], "tasks": { "build": { "outputs": [".next/**"] } }}```
Without `"extends": ["//"]`, Package Configurations are invalid.
## Root Tasks Need Special Syntax
To run a task defined only in root `package.json`:
```bash# WRONGturbo run format
# CORRECTturbo run //#format```
And in dependsOn:
```json"build": { "dependsOn": ["//#codegen"] // Root package's codegen}```
## Overwriting Default Inputs
```json// WRONG - only watches test files, ignores source changes"test": { "inputs": ["tests/**"]}
// CORRECT - extends defaults, adds test files"test": { "inputs": ["$TURBO_DEFAULT$", "tests/**"]}```
Without `$TURBO_DEFAULT$`, you replace all default file watching.
## Excluding `global.inputs` Without `$TURBO_DEFAULT$`
When using `futureFlags.globalConfiguration`, `global.inputs` values are prepended to every task's inputs. If you want to exclude a global input from a specific task, you **must** include `$TURBO_DEFAULT$` to preserve default file hashing.
```json// WRONG - task hashes NO files at all (global input cancelled, no defaults)"build": { "inputs": ["!$TURBO_ROOT$/config.txt"]}
// CORRECT - task hashes all package files, minus config.txt"build": { "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/config.txt"]}```
Without `$TURBO_DEFAULT$`, the only inclusion glob comes from `global.inputs`, which the negation cancels out. The task ends up with no inclusions and no default file hashing, so it hashes nothing. Changes to source files won't cause cache misses.
## Caching Tasks with Side Effects
```json// WRONG - deploy might be skipped on cache hit"deploy": { "dependsOn": ["build"]}
// CORRECT"deploy": { "dependsOn": ["build"], "cache": false}```
Always disable cache for deploy, publish, or mutation tasks.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321# Task Configuration Reference
Full docs: https://turborepo.dev/docs/reference/configuration#tasks
## dependsOn
Controls task execution order.
```json{ "tasks": { "build": { "dependsOn": [ "^build", // Dependencies' build tasks first "codegen", // Same package's codegen task first "shared#build" // Specific package's build task ] } }}```
| Syntax | Meaning || ---------- | ------------------------------------ || `^task` | Run `task` in all dependencies first || `task` | Run `task` in same package first || `pkg#task` | Run specific package's task first |
The `^` prefix is crucial - without it, you're referencing the same package.
### Transit Nodes for Parallel Tasks
For tasks like `lint` and `check-types` that can run in parallel but need dependency-aware caching:
```json{ "tasks": { "transit": { "dependsOn": ["^transit"] }, "lint": { "dependsOn": ["transit"] }, "check-types": { "dependsOn": ["transit"] } }}```
**DO NOT use `dependsOn: ["^lint"]`** - this forces sequential execution.**DO NOT use `dependsOn: []`** - this breaks cache invalidation.
The `transit` task creates dependency relationships without running anything (no matching script), so tasks run in parallel with correct caching.
## outputs
Glob patterns for files to cache. **If omitted, nothing is cached.**
```json{ "tasks": { "build": { "outputs": ["dist/**", "build/**"] } }}```
**Framework examples:**
```json// Next.js"outputs": [".next/**", "!.next/cache/**"]
// Vite"outputs": ["dist/**"]
// TypeScript (tsc)"outputs": ["dist/**", "*.tsbuildinfo"]
// No file outputs (lint, typecheck)"outputs": []```
Use `!` prefix to exclude patterns from caching.
## inputs
Files considered when calculating task hash. Defaults to all tracked files in package.
```json{ "tasks": { "test": { "inputs": ["src/**", "tests/**", "vitest.config.ts"] } }}```
**Special values:**
| Value | Meaning || --------------------- | --------------------------------------- || `$TURBO_DEFAULT$` | Include default inputs, then add/remove || `$TURBO_ROOT$/<path>` | Reference files from repo root |
```json{ "tasks": { "build": { "inputs": ["$TURBO_DEFAULT$", "!README.md", "$TURBO_ROOT$/tsconfig.base.json"] } }}```
### Interaction with `global.inputs`
When `futureFlags.globalConfiguration` is enabled, files listed in `global.inputs` are prepended to every task's `inputs`. The combined list is then used to compute the task hash.
This is different from `globalDependencies`, where files were hashed into the **global** hash and could not be influenced by task-level `inputs`.
**With `globalDependencies` (old behavior):**
- `globalDependencies` files contribute to the global hash- Task `inputs` only control which **package** files are hashed- There is no way for a task to "opt out" of a `globalDependencies` file
**With `global.inputs` (new behavior):**
- `global.inputs` files are merged into each task's `inputs` globs- Task `inputs` and `global.inputs` are combined, then the full list is hashed into the **task** hash- Tasks can exclude specific global files with negation globs
```json{ "futureFlags": { "globalConfiguration": true }, "global": { "inputs": ["tsconfig.json", ".env"] }, "tasks": { "build": {}, "lint": { "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/.env"] } }}```
In this example:
- `build` hashes all package files + `tsconfig.json` + `.env` (from `global.inputs`)- `lint` hashes all package files + `tsconfig.json`, but **excludes** `.env` because of the negation glob
Tasks with no explicit `inputs` key still hash all package files (the default behavior) plus the `global.inputs` files.
## env
Environment variables to include in task hash.
```json{ "tasks": { "build": { "env": [ "API_URL", "NEXT_PUBLIC_*", // Wildcard matching "!DEBUG" // Exclude from hash ] } }}```
Variables listed here affect cache hits - changing the value invalidates cache.
## cache
Enable/disable caching for a task. Default: `true`.
```json{ "tasks": { "dev": { "cache": false }, "deploy": { "cache": false } }}```
Disable for: dev servers, deploy commands, tasks with side effects.
## persistent
Mark long-running tasks that don't exit. Default: `false`.
```json{ "tasks": { "dev": { "cache": false, "persistent": true } }}```
Required for dev servers - without it, dependent tasks wait forever.
## interactive
Allow task to receive stdin input. Default: `false`.
```json{ "tasks": { "login": { "cache": false, "interactive": true } }}```
## outputLogs
Control when logs are shown. Options: `full`, `hash-only`, `new-only`, `errors-only`, `none`.
```json{ "tasks": { "build": { "outputLogs": "new-only" // Only show logs on cache miss } }}```
## with
Run tasks alongside this task. For long-running tasks that need runtime dependencies.
```json{ "tasks": { "dev": { "with": ["api#dev"], "persistent": true, "cache": false } }}```
Unlike `dependsOn`, `with` runs tasks concurrently (not sequentially). Use for dev servers that need other services running.
## interruptible
Allow `turbo watch` to restart the task on changes. Default: `false`.
```json{ "tasks": { "dev": { "persistent": true, "interruptible": true, "cache": false } }}```
Use for dev servers that don't automatically detect dependency changes.
## description
Human-readable description of the task.
```json{ "tasks": { "build": { "description": "Compiles the application for production deployment" } }}```
For documentation only - doesn't affect execution or caching.
## passThroughEnv
Environment variables available at runtime but NOT included in cache hash.
```json{ "tasks": { "build": { "passThroughEnv": ["AWS_SECRET_KEY", "GITHUB_TOKEN"] } }}```
**Warning**: Changes to these vars won't cause cache misses. Use `env` if changes should invalidate cache.
## extends (Package Configuration only)
Control task inheritance in Package Configurations.
```json// packages/ui/turbo.json{ "extends": ["//"], "tasks": { "lint": { "extends": false // Exclude from this package } }}```
| Value | Behavior || ---------------- | -------------------------------------------------------------- || `true` (default) | Inherit from root turbo.json || `false` | Exclude task from package, or define fresh without inheritance |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123# Environment Variables in Turborepo
Turborepo provides fine-grained control over which environment variables affect task hashing and runtime availability.
## Configuration Keys
### `env` - Task-Specific Variables
Variables that affect a specific task's hash. When these change, only that task rebuilds.
```json{ "tasks": { "build": { "env": ["DATABASE_URL", "API_KEY"] } }}```
### `globalEnv` - Variables Affecting All Tasks
Variables that affect EVERY task's hash. When these change, all tasks rebuild.
```json{ "globalEnv": ["CI", "NODE_ENV"]}```
### `passThroughEnv` - Runtime-Only Variables (Not Hashed)
Variables available at runtime but NOT included in hash. **Use with caution** - changes won't trigger rebuilds.
```json{ "tasks": { "deploy": { "passThroughEnv": ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"] } }}```
### `globalPassThroughEnv` - Global Runtime Variables
Same as `passThroughEnv` but for all tasks.
```json{ "globalPassThroughEnv": ["GITHUB_TOKEN"]}```
## Wildcards and Negation
### Wildcards
Match multiple variables with `*`:
```json{ "env": ["MY_API_*", "FEATURE_FLAG_*"]}```
This matches `MY_API_URL`, `MY_API_KEY`, `FEATURE_FLAG_DARK_MODE`, etc.
### Negation
Exclude variables (useful with framework inference):
```json{ "env": ["!NEXT_PUBLIC_ANALYTICS_ID"]}```
## With `futureFlags.globalConfiguration`
When the `globalConfiguration` future flag is enabled, global environment keys move under the `global` key with cleaner names:
| Old (top-level) | New (`global.`) || ---------------------- | ---------------- || `globalEnv` | `env` || `globalPassThroughEnv` | `passThroughEnv` |
`global.env` and `global.passThroughEnv` behave identically to their top-level counterparts — they affect the global hash and all tasks, respectively. The rename is purely organizational.
```json{ "futureFlags": { "globalConfiguration": true }, "global": { "env": ["CI", "NODE_ENV"], "passThroughEnv": ["GITHUB_TOKEN", "NPM_TOKEN"] }, "tasks": { "build": { "env": ["DATABASE_URL", "API_*"], "passThroughEnv": ["SENTRY_AUTH_TOKEN"] } }}```
## Complete Example
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "globalEnv": ["CI", "NODE_ENV"], "globalPassThroughEnv": ["GITHUB_TOKEN", "NPM_TOKEN"], "tasks": { "build": { "env": ["DATABASE_URL", "API_*"], "passThroughEnv": ["SENTRY_AUTH_TOKEN"] }, "test": { "env": ["TEST_DATABASE_URL"] } }}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175# Environment Variable Gotchas
Common mistakes and how to fix them.
## .env Files Must Be in `inputs`
Turbo does NOT read `.env` files. Your framework (Next.js, Vite, etc.) or `dotenv` loads them. But Turbo needs to know when they change.
**Wrong:**
```json{ "tasks": { "build": { "env": ["DATABASE_URL"] } }}```
**Right:**
```json{ "tasks": { "build": { "env": ["DATABASE_URL"], "inputs": ["$TURBO_DEFAULT$", ".env", ".env.local", ".env.production"] } }}```
## Strict Mode Filters CI Variables
In strict mode, CI provider variables (GITHUB_TOKEN, GITLAB_CI, etc.) are filtered unless explicitly listed.
**Symptom:** Task fails with "authentication required" or "permission denied" in CI.
**Solution:**
```json{ "globalPassThroughEnv": ["GITHUB_TOKEN", "GITLAB_CI", "CI"]}```
## passThroughEnv Doesn't Affect Hash
Variables in `passThroughEnv` are available at runtime but changes WON'T trigger rebuilds.
**Dangerous example:**
```json{ "tasks": { "build": { "passThroughEnv": ["API_URL"] } }}```
If `API_URL` changes from staging to production, Turbo may serve a cached build pointing to the wrong API.
**Use passThroughEnv only for:**
- Auth tokens that don't affect output (SENTRY_AUTH_TOKEN)- CI metadata (GITHUB_RUN_ID)- Variables consumed after build (deploy credentials)
## Runtime-Created Variables Are Invisible
Turbo captures env vars at startup. Variables created during execution aren't seen.
**Won't work:**
```bash# In package.json scripts"build": "export API_URL=$COMPUTED_VALUE && next build"```
**Solution:** Set vars before invoking turbo:
```bashAPI_URL=$COMPUTED_VALUE turbo run build```
## Different .env Files for Different Environments
If you use `.env.development` and `.env.production`, both should be in inputs.
```json{ "tasks": { "build": { "inputs": [ "$TURBO_DEFAULT$", ".env", ".env.local", ".env.development", ".env.development.local", ".env.production", ".env.production.local" ] } }}```
## Complete Next.js Example
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "globalEnv": ["CI", "NODE_ENV", "VERCEL"], "globalPassThroughEnv": ["GITHUB_TOKEN", "VERCEL_URL"], "tasks": { "build": { "dependsOn": ["^build"], "env": ["DATABASE_URL", "NEXT_PUBLIC_*", "!NEXT_PUBLIC_ANALYTICS_ID"], "passThroughEnv": ["SENTRY_AUTH_TOKEN"], "inputs": [ "$TURBO_DEFAULT$", ".env", ".env.local", ".env.production", ".env.production.local" ], "outputs": [".next/**", "!.next/cache/**"] } }}```
This config:
- Hashes DATABASE*URL and NEXT_PUBLIC*\* vars (except analytics)- Passes through SENTRY_AUTH_TOKEN without hashing- Includes all .env file variants in the hash- Makes CI tokens available globally
### With `futureFlags.globalConfiguration`
The same config using the `global` key. The `.env` files move to `global.inputs`, which means they get folded into each task's hash individually rather than the global hash. This lets tasks exclude specific `.env` files if needed.
```json{ "$schema": "https://v2-9-7-canary-13.turborepo.dev/schema.json", "futureFlags": { "globalConfiguration": true }, "global": { "env": ["CI", "NODE_ENV", "VERCEL"], "passThroughEnv": ["GITHUB_TOKEN", "VERCEL_URL"], "inputs": [".env", ".env.local", ".env.production", ".env.production.local"] }, "tasks": { "build": { "dependsOn": ["^build"], "env": ["DATABASE_URL", "NEXT_PUBLIC_*", "!NEXT_PUBLIC_ANALYTICS_ID"], "passThroughEnv": ["SENTRY_AUTH_TOKEN"], "outputs": [".next/**", "!.next/cache/**"] } }}```
With this approach, a task that doesn't care about `.env.production` can exclude it:
```json"lint": { "inputs": ["$TURBO_DEFAULT$", "!$TURBO_ROOT$/.env.production"]}```
This wouldn't have been possible with `globalDependencies`, where `.env.production` would be baked into the global hash and affect every task unconditionally.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101# Environment Modes
Turborepo supports different modes for handling environment variables during task execution.
## Strict Mode (Default)
Only explicitly configured variables are available to tasks.
**Behavior:**
- Tasks only see vars listed in `env`, `globalEnv`, `passThroughEnv`, or `globalPassThroughEnv`- Unlisted vars are filtered out- Tasks fail if they require unlisted variables
**Benefits:**
- Guarantees cache correctness- Prevents accidental dependencies on system vars- Reproducible builds across machines
```bash# Explicit (though it's the default)turbo run build --env-mode=strict```
## Loose Mode
All system environment variables are available to tasks.
```bashturbo run build --env-mode=loose```
**Behavior:**
- Every system env var is passed through- Only vars in `env`/`globalEnv` affect the hash- Other vars are available but NOT hashed
**Risks:**
- Cache may restore incorrect results if unhashed vars changed- "Works on my machine" bugs- CI vs local environment mismatches
**Use case:** Migrating legacy projects or debugging strict mode issues.
## Framework Inference (Automatic)
Turborepo automatically detects frameworks and includes their conventional env vars.
### Inferred Variables by Framework
| Framework | Pattern || ---------------- | ------------------- || Next.js | `NEXT_PUBLIC_*` || Vite | `VITE_*` || Create React App | `REACT_APP_*` || Gatsby | `GATSBY_*` || Nuxt | `NUXT_*`, `NITRO_*` || Expo | `EXPO_PUBLIC_*` || Astro | `PUBLIC_*` || SvelteKit | `PUBLIC_*` || Remix | `REMIX_*` || Redwood | `REDWOOD_ENV_*` || Sanity | `SANITY_STUDIO_*` || Solid | `VITE_*` |
### Disabling Framework Inference
Globally via CLI:
```bashturbo run build --framework-inference=false```
Or exclude specific patterns in config:
```json{ "tasks": { "build": { "env": ["!NEXT_PUBLIC_*"] } }}```
### Why Disable?
- You want explicit control over all env vars- Framework vars shouldn't bust the cache (e.g., analytics IDs)- Debugging unexpected cache misses
## Checking Environment Mode
Use `--dry` to see which vars affect each task:
```bashturbo run build --dry=json | jq '.tasks[].environmentVariables'```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148# Turborepo Filter Syntax Reference
## Running Only Changed Packages: `--affected`
**The primary way to run only changed packages is `--affected`:**
```bash# Run build/test/lint only in changed packages and their dependentsturbo run build test lint --affected```
This compares your current branch to the default branch (usually `main` or `master`) and runs tasks in:
1. Packages with file changes2. Packages that depend on changed packages (dependents)
### Why Include Dependents?
If you change `@repo/ui`, packages that import `@repo/ui` (like `apps/web`) need to re-run their tasks to verify they still work with the changes.
### Customizing --affected
```bash# Use a different base branchturbo run build --affected --affected-base=origin/develop
# Use a different head (current state)turbo run build --affected --affected-head=HEAD~5```
### Common CI Pattern
```yaml# .github/workflows/ci.yml- run: turbo run build test lint --affected```
This is the most efficient CI setup - only run tasks for what actually changed.
---
## Manual Git Comparison with --filter
For more control, use `--filter` with git comparison syntax:
```bash# Changed packages + dependents (same as --affected)turbo run build --filter=...[origin/main]
# Only changed packages (no dependents)turbo run build --filter=[origin/main]
# Changed packages + dependencies (packages they import)turbo run build --filter=[origin/main]...
# Changed since last committurbo run build --filter=...[HEAD^1]
# Changed between two commitsturbo run build --filter=[a1b2c3d...e4f5g6h]```
### Comparison Syntax
| Syntax | Meaning || ------------- | ------------------------------------- || `[ref]` | Packages changed since `ref` || `...[ref]` | Changed packages + their dependents || `[ref]...` | Changed packages + their dependencies || `...[ref]...` | Dependencies, changed, AND dependents |
---
## Other Filter Types
Filters select which packages to include in a `turbo run` invocation.
### Basic Syntax
```bashturbo run build --filter=<package-name>turbo run build -F <package-name>```
Multiple filters combine as a union (packages matching ANY filter run).
### By Package Name
```bash--filter=web # exact match--filter=@acme/* # scope glob--filter=*-app # name glob```
### By Directory
```bash--filter=./apps/* # all packages in apps/--filter=./packages/ui # specific directory```
### By Dependencies/Dependents
| Syntax | Meaning || ----------- | -------------------------------------- || `pkg...` | Package AND all its dependencies || `...pkg` | Package AND all its dependents || `...pkg...` | Dependencies, package, AND dependents || `^pkg...` | Only dependencies (exclude pkg itself) || `...^pkg` | Only dependents (exclude pkg itself) |
### Negation
Exclude packages with `!`:
```bash--filter=!web # exclude web--filter=./apps/* --filter=!admin # apps except admin```
### Task Identifiers
Run a specific task in a specific package:
```bashturbo run web#build # only web's build taskturbo run web#build api#test # web build + api test```
### Combining Filters
Multiple `--filter` flags create a union:
```bashturbo run build --filter=web --filter=api # runs in both```
---
## Quick Reference: Changed Packages
| Goal | Command || ---------------------------------- | ----------------------------------------------------------- || Changed + dependents (recommended) | `turbo run build --affected` || Custom base branch | `turbo run build --affected --affected-base=origin/develop` || Only changed (no dependents) | `turbo run build --filter=[origin/main]` || Changed + dependencies | `turbo run build --filter=[origin/main]...` || Since last commit | `turbo run build --filter=...[HEAD^1]` |123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152# Common Filter Patterns
Practical examples for typical monorepo scenarios.
## Single Package
Run task in one package:
```bashturbo run build --filter=webturbo run test --filter=@acme/api```
## Package with Dependencies
Build a package and everything it depends on:
```bashturbo run build --filter=web...```
Useful for: ensuring all dependencies are built before the target.
## Package Dependents
Run in all packages that depend on a library:
```bashturbo run test --filter=...ui```
Useful for: testing consumers after changing a shared package.
## Dependents Only (Exclude Target)
Test packages that depend on ui, but not ui itself:
```bashturbo run test --filter=...^ui```
## Changed Packages
Run only in packages with file changes since last commit:
```bashturbo run lint --filter=[HEAD^1]```
Since a specific branch point:
```bashturbo run lint --filter=[main...HEAD]```
## Changed + Dependents (PR Builds)
Run in changed packages AND packages that depend on them:
```bashturbo run build test --filter=...[HEAD^1]```
Or use the shortcut:
```bashturbo run build test --affected```
## Directory-Based
Run in all apps:
```bashturbo run build --filter=./apps/*```
Run in specific directories:
```bashturbo run build --filter=./apps/web --filter=./apps/api```
## Scope-Based
Run in all packages under a scope:
```bashturbo run build --filter=@acme/*```
## Exclusions
Run in all apps except admin:
```bashturbo run build --filter=./apps/* --filter=!admin```
Run everywhere except specific packages:
```bashturbo run lint --filter=!legacy-app --filter=!deprecated-pkg```
## Complex Combinations
Apps that changed, plus their dependents:
```bashturbo run build --filter=...[HEAD^1] --filter=./apps/*```
All packages except docs, but only if changed:
```bashturbo run build --filter=[main...HEAD] --filter=!docs```
## Debugging Filters
Use `--dry` to see what would run without executing:
```bashturbo run build --filter=web... --dry```
Use `--dry=json` for machine-readable output:
```bashturbo run build --filter=...[HEAD^1] --dry=json```
## CI/CD Patterns
PR validation (most common):
```bashturbo run build test lint --affected```
Deploy only changed apps:
```bashturbo run deploy --filter=./apps/* --filter=[main...HEAD]```
Full rebuild of specific app and deps:
```bashturbo run build --filter=production-app...```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# turbo watch
Full docs: https://turborepo.dev/docs/reference/watch
Re-run tasks automatically when code changes. Dependency-aware.
```bashturbo watch [tasks]```
## Basic Usage
```bash# Watch and re-run build task when code changesturbo watch build
# Watch multiple tasksturbo watch build test lint```
Tasks re-run in order configured in `turbo.json` when source files change.
## With Persistent Tasks
Persistent tasks (`"persistent": true`) won't exit, so they can't be depended on. They work the same in `turbo watch` as `turbo run`.
### Dependency-Aware Persistent Tasks
If your tool has built-in watching (like `next dev`), use its watcher:
```json{ "tasks": { "dev": { "persistent": true, "cache": false } }}```
### Non-Dependency-Aware Tools
For tools that don't detect dependency changes, use `interruptible`:
```json{ "tasks": { "dev": { "persistent": true, "interruptible": true, "cache": false } }}```
`turbo watch` will restart interruptible tasks when dependencies change.
## Limitations
### Caching
Caching is experimental with watch mode:
```bashturbo watch your-tasks --experimental-write-cache```
### Task Outputs in Source Control
If tasks write files tracked by git, watch mode may loop infinitely. Watch mode uses file hashes to prevent this but it's not foolproof.
**Recommendation**: Remove task outputs from git.
## vs turbo run
| Feature | `turbo run` | `turbo watch` || ----------------- | ----------- | ------------- || Runs once | Yes | No || Re-runs on change | No | Yes || Caching | Full | Experimental || Use case | CI, one-off | Development |
## Common Patterns
### Development Workflow
```bash# Run dev servers and watch for build changesturbo watch dev build```
### Type Checking During Development
```bash# Watch and re-run type checksturbo watch check-types```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917# React Composition Patterns
**Version 1.0.0** Engineering January 2026
> **Note:** > This document is mainly for agents and LLMs to follow when maintaining, > generating, or refactoring React codebases using composition. Humans > may also find it useful, but guidance here is optimized for automation > and consistency by AI-assisted workflows.
---
## 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.
---
## Table of Contents
1. [Component Architecture](#1-component-architecture) — **HIGH** - 1.1 [Avoid Boolean Prop Proliferation](#11-avoid-boolean-prop-proliferation) - 1.2 [Use Compound Components](#12-use-compound-components)2. [State Management](#2-state-management) — **MEDIUM** - 2.1 [Decouple State Management from UI](#21-decouple-state-management-from-ui) - 2.2 [Define Generic Context Interfaces for Dependency Injection](#22-define-generic-context-interfaces-for-dependency-injection) - 2.3 [Lift State into Provider Components](#23-lift-state-into-provider-components)3. [Implementation Patterns](#3-implementation-patterns) — **MEDIUM** - 3.1 [Create Explicit Component Variants](#31-create-explicit-component-variants) - 3.2 [Prefer Composing Children Over Render Props](#32-prefer-composing-children-over-render-props)4. [React 19 APIs](#4-react-19-apis) — **MEDIUM** - 4.1 [React 19 API Changes](#41-react-19-api-changes)
---
## 1. Component Architecture
**Impact: HIGH**
Fundamental patterns for structuring components to avoid propproliferation and enable flexible composition.
### 1.1 Avoid Boolean Prop Proliferation
**Impact: CRITICAL (prevents unmaintainable component variants)**
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**
```tsxfunction 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 composerfunction 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" fieldfunction 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 actionsfunction 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.2 Use Compound Components
**Impact: HIGH (enables flexible composition without prop drilling)**
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**
```tsxfunction 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**
```tsxconst 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 componentconst 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.
---
## 2. State Management
**Impact: MEDIUM**
Patterns for lifting state and managing shared context acrosscomposed components.
### 2.1 Decouple State Management from UI
**Impact: MEDIUM (enables swapping state implementations without changing 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**
```tsxfunction 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 detailsfunction 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 interfacefunction ChannelComposer() { return ( <Composer.Frame> <Composer.Header /> <Composer.Input /> <Composer.Footer> <Composer.Submit /> </Composer.Footer> </Composer.Frame> );}
// Usagefunction Channel({ channelId }: { channelId: string }) { return ( <ChannelProvider channelId={channelId}> <ChannelComposer /> </ChannelProvider> );}```
**Different providers, same UI:**
```tsx// Local state for ephemeral formsfunction 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 channelsfunction 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.
### 2.2 Define Generic Context Interfaces for Dependency Injection
**Impact: HIGH (enables dependency-injectable state across use-cases)**
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**
```tsxfunction 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 implementinterface 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:**
```tsxfunction 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 formsfunction 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 channelsfunction 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:**
```tsxfunction 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 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.
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.
### 2.3 Lift State into Provider Components
**Impact: HIGH (enables state sharing outside component boundaries)**
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**
```tsxfunction 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**
```tsxfunction 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**
```tsxfunction ForwardMessageDialog() { const stateRef = useRef(null); return ( <Dialog> <ForwardMessageComposer stateRef={stateRef} /> <ForwardButton onPress={() => submit(stateRef.current)} /> </Dialog> );}```
**Correct: state lifted to provider**
```tsxfunction 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.
---
## 3. Implementation Patterns
**Impact: MEDIUM**
Specific techniques for implementing compound components andcontext providers.
### 3.1 Create Explicit Component Variants
**Impact: MEDIUM (self-documenting code, no hidden conditionals)**
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:**
```tsxfunction 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.
### 3.2 Prefer Composing Children Over Render Props
**Impact: MEDIUM (cleaner composition, better readability)**
Use `children` for composition instead of `renderX` props. Children are more
readable, compose naturally, and don't require understanding callback
signatures.
**Incorrect: render props**
```tsxfunction 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 inflexiblereturn ( <Composer renderHeader={() => <CustomHeader />} renderFooter={() => ( <> <Formatting /> <Emojis /> </> )} renderActions={() => <SubmitButton />} />);```
**Correct: compound components with children**
```tsxfunction ComposerFrame({ children }: { children: React.ReactNode }) { return <form>{children}</form>;}
function ComposerFooter({ children }: { children: React.ReactNode }) { return <footer className="flex">{children}</footer>;}
// Usage is flexiblereturn ( <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.
---
## 4. React 19 APIs
**Impact: MEDIUM**
React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.
### 4.1 React 19 API Changes
**Impact: MEDIUM (cleaner component definitions and context usage)**
> **⚠️ 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**
```tsxconst ComposerInput = forwardRef<TextInput, Props>((props, ref) => { return <TextInput ref={ref} {...props} />;});```
**Correct: ref as a regular prop**
```tsxfunction ComposerInput({ ref, ...props }: Props & { ref?: React.Ref<TextInput> }) { return <TextInput ref={ref} {...props} />;}```
**Incorrect: useContext in React 19**
```tsxconst value = useContext(MyContext);```
**Correct: use instead of useContext**
```tsxconst value = use(MyContext);```
`use()` can also be called conditionally, unlike `useContext()`.
---
## References
1. [https://react.dev](https://react.dev)2. [https://react.dev/learn/passing-data-deeply-with-context](https://react.dev/learn/passing-data-deeply-with-context)3. [https://react.dev/reference/react/use](https://react.dev/reference/react/use)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960# React Composition Patterns
A structured repository for React composition patterns that scale. Thesepatterns 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 compose2. **Lift your state** — State in providers, not trapped in components3. **Compose your internals** — Subcomponents access context, not props4. **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 Patterns3. Fill in the frontmatter and content4. Ensure you have clear examples with explanations
## Impact Levels
- `CRITICAL` - Foundational patterns, prevents unmaintainable code- `HIGH` - Significant maintainability improvements- `MEDIUM` - Good practices for cleaner code12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788---name: vercel-composition-patternsdescription: 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: MITmetadata: author: vercel version: "1.0.0"---
# React Composition Patterns
Composition patterns for building flexible, maintainable React components. Avoidboolean prop proliferation by using compound components, lifting state, andcomposing internals. These patterns make codebases easier for both humans and AIagents 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.mdrules/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`1234567891011{ "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" ]}1234567891011121314151617181920212223242526272829# 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 propproliferation and enable flexible composition.
## 2. State Management (state)
**Impact:** MEDIUM **Description:** Patterns for lifting state and managing shared context acrosscomposed components.
## 3. Implementation Patterns (patterns)
**Impact:** MEDIUM **Description:** Specific techniques for implementing compound components andcontext providers.
## 4. React 19 APIs (react19)
**Impact:** MEDIUM **Description:** React 19+ only. Don't use `forwardRef`; use `use()` instead of `useContext()`.123456789101112131415161718192021222324---title: Rule Title Hereimpact: MEDIUMimpactDescription: brief description of impacttags: 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)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394---title: Avoid Boolean Prop Proliferationimpact: CRITICALimpactDescription: prevents unmaintainable component variantstags: composition, props, architecture---
## Avoid Boolean Prop Proliferation
Don't add boolean props like `isThread`, `isEditing`, `isDMThread` to customizecomponent behavior. Each boolean doubles possible states and createsunmaintainable conditional logic. Use composition instead.
**Incorrect (boolean props create exponential complexity):**
```tsxfunction 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 composerfunction 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" fieldfunction 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 actionsfunction 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 withoutsharing a single monolithic parent.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108---title: Use Compound Componentsimpact: HIGHimpactDescription: enables flexible composition without prop drillingtags: composition, compound-components, architecture---
## Use Compound Components
Structure complex components as compound components with a shared context. Eachsubcomponent accesses shared state via context, not props. Consumers compose thepieces they need.
**Incorrect (monolithic component with render props):**
```tsxfunction 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):**
```tsxconst 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 componentconst 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.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384---title: Prefer Composing Children Over Render Propsimpact: MEDIUMimpactDescription: cleaner composition, better readabilitytags: composition, children, render-props---
## Prefer Children Over Render Props
Use `children` for composition instead of `renderX` props. Children are morereadable, compose naturally, and don't require understanding callbacksignatures.
**Incorrect (render props):**
```tsxfunction 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 inflexiblereturn ( <Composer renderHeader={() => <CustomHeader />} renderFooter={() => ( <> <Formatting /> <Emojis /> </> )} renderActions={() => <SubmitButton />} />);```
**Correct (compound components with children):**
```tsxfunction ComposerFrame({ children }: { children: React.ReactNode }) { return <form>{children}</form>;}
function ComposerFooter({ children }: { children: React.ReactNode }) { return <footer className="flex">{children}</footer>;}
// Usage is flexiblereturn ( <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..agents/skills/better-auth-best-practices/SKILL.mdAdded+183
.agents/skills/hono/SKILL.mdAdded+579
.agents/skills/shadcn/SKILL.mdAdded+250
.agents/skills/shadcn/agents/openai.ymlAdded+5
.agents/skills/shadcn/assets/shadcn-small.pngAdded

Large File Pointer Details
- SHA256: 0ecc62d682727f68fc4937eed19960c706714fa084d44f63028d611ae02bf3d7
- Pointer size: 129 Bytes
- Size of remote file: 1.05 kB
.agents/skills/shadcn/assets/shadcn.pngAdded

Large File Pointer Details
- SHA256: 7d60ad6fec4d89a0d44ba5a3c9283d2fea0047af5467f9227040e20d927d39b7
- Pointer size: 129 Bytes
- Size of remote file: 3.85 kB
.agents/skills/shadcn/cli.mdAdded+276
.agents/skills/shadcn/customization.mdAdded+208
.agents/skills/shadcn/evals/evals.jsonAdded+47
.agents/skills/shadcn/mcp.mdAdded+94
.agents/skills/shadcn/rules/base-vs-radix.mdAdded+308
.agents/skills/shadcn/rules/composition.mdAdded+197
.agents/skills/shadcn/rules/forms.mdAdded+194
.agents/skills/shadcn/rules/icons.mdAdded+101
.agents/skills/shadcn/rules/styling.mdAdded+161
.agents/skills/turborepo/SKILL.mdAdded+951
.agents/skills/turborepo/command/turborepo.mdAdded+70
.agents/skills/turborepo/references/best-practices/RULE.mdAdded+241
.agents/skills/turborepo/references/best-practices/dependencies.mdAdded+246
.agents/skills/turborepo/references/best-practices/packages.mdAdded+335
.agents/skills/turborepo/references/best-practices/structure.mdAdded+297
.agents/skills/turborepo/references/boundaries/RULE.mdAdded+126
.agents/skills/turborepo/references/caching/RULE.mdAdded+153
.agents/skills/turborepo/references/caching/gotchas.mdAdded+190
.agents/skills/turborepo/references/caching/remote-cache.mdAdded+127
.agents/skills/turborepo/references/ci/RULE.mdAdded+79
.agents/skills/turborepo/references/ci/github-actions.mdAdded+162
.agents/skills/turborepo/references/ci/patterns.mdAdded+145
.agents/skills/turborepo/references/ci/vercel.mdAdded+103
.agents/skills/turborepo/references/cli/RULE.mdAdded+100
.agents/skills/turborepo/references/cli/commands.mdAdded+297
.agents/skills/turborepo/references/configuration/RULE.mdAdded+235
.agents/skills/turborepo/references/configuration/global-options.mdAdded+239
.agents/skills/turborepo/references/configuration/gotchas.mdAdded+368
.agents/skills/turborepo/references/configuration/tasks.mdAdded+321
.agents/skills/turborepo/references/environment/RULE.mdAdded+123
.agents/skills/turborepo/references/environment/gotchas.mdAdded+175
.agents/skills/turborepo/references/environment/modes.mdAdded+101
.agents/skills/turborepo/references/filtering/RULE.mdAdded+148
.agents/skills/turborepo/references/filtering/patterns.mdAdded+152
.agents/skills/turborepo/references/watch/RULE.mdAdded+99
.agents/skills/vercel-composition-patterns/AGENTS.mdAdded+917
.agents/skills/vercel-composition-patterns/README.mdAdded+60
.agents/skills/vercel-composition-patterns/SKILL.mdAdded+88
.agents/skills/vercel-composition-patterns/metadata.jsonAdded+11
.agents/skills/vercel-composition-patterns/rules/_sections.mdAdded+29
.agents/skills/vercel-composition-patterns/rules/_template.mdAdded+24
.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.mdAdded+94
.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.mdAdded+108
.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.mdAdded+84