diff --git a/.agents/skills/docs-writer/SKILL.md b/.agents/skills/docs-writer/SKILL.md new file mode 100644 index 00000000..1bfd87c5 --- /dev/null +++ b/.agents/skills/docs-writer/SKILL.md @@ -0,0 +1,178 @@ +--- +name: docs-writer +description: + Always use this skill when the task involves writing, reviewing, or editing + files in the `apps/docs` directory or any `.md` files in the repository. +--- + +# `docs-writer` skill instructions + +As an expert technical writer and editor for the DockStat project, you produce +accurate, clear, and consistent documentation. When asked to write, edit, or +review documentation, you must ensure the content strictly adheres to the +provided documentation standards and accurately reflects the current codebase. +Adhere to the contribution process in `CONTRIBUTING.md` and the following +project standards. + +## Phase 1: Documentation standards + +Adhering to these principles and standards when writing, editing, and reviewing. + +### Voice and tone +Adopt a tone that balances professionalism with a helpful, conversational +approach. + +- **Perspective and tense:** Address the reader as "you." Use active voice and + present tense (e.g., "The API returns..."). +- **Tone:** Professional, friendly, and direct. +- **Clarity:** Use simple vocabulary. Avoid jargon, slang, and marketing hype. +- **Global Audience:** Write in standard US English. Avoid idioms and cultural + references. +- **Requirements:** Be clear about requirements ("must") vs. recommendations + ("we recommend"). Avoid "should." +- **Word Choice:** Avoid "please" and anthropomorphism (e.g., "the server + thinks"). Use contractions (don't, it's). + +### Language and grammar +Write precisely to ensure your instructions are unambiguous. + +- **Abbreviations:** Avoid Latin abbreviations; use "for example" (not "e.g.") + and "that is" (not "i.e."). +- **Punctuation:** Use the serial comma. Place periods and commas inside + quotation marks. +- **Dates:** Use unambiguous formats (e.g., "January 22, 2026"). +- **Conciseness:** Use "lets you" instead of "allows you to." Use precise, + specific verbs. +- **Examples:** Use meaningful names in examples; avoid placeholders like + "foo" or "bar." + +### Formatting and syntax +Apply consistent formatting to make documentation visually organized and +accessible. + +- **Overview paragraphs:** Every heading must be followed by at least one + introductory overview paragraph before any lists or sub-headings. +- **Text wrap:** Wrap text at 80 characters (except long links or tables). +- **Casing:** Use sentence case for headings, titles, and bolded text. +- **Naming:** Always refer to the project as `DockStat`. +- **Lists:** Use numbered lists for sequential steps and bulleted lists + otherwise. Keep list items parallel in structure. +- **UI and code:** Use **bold** for UI elements and `code font` for filenames, + snippets, commands, and API elements. Focus on the task when discussing + interaction. +- **Accessibility:** Use semantic HTML elements correctly (headings, lists, + tables). +- **Media:** Use lowercase hyphenated filenames. Provide descriptive alt text + for all images. +- **Details section:** Use the `
` tag to create a collapsible section. + This is useful for supplementary or data-heavy information that isn't critical + to the main flow. + + Example: + +
+ Title + + - First entry + - Second entry + +
+ +- **Callouts**: Use GitHub-flavored markdown alerts to highlight important + information. The callout type (`[!TYPE]`) + should be on the first line, followed by a newline, and then the content, with + each subsequent line of content starting with `>`. Available types are `NOTE`, + `TIP`, `IMPORTANT`, `WARNING`, and `CAUTION`. + + Example (.md): + + +> [!NOTE] +> This is an example of a multi-line note that will be preserved +> by Prettier. + + Example (.mdx): + +{/* prettier-ignore */} +> [!NOTE] +> This is an example of a multi-line note that will be preserved +> by Prettier. + +### Links +- **Accessibility:** Use descriptive anchor text; avoid "click here." Ensure the + link makes sense out of context, such as when being read by a screen reader. +- **Use relative links in docs:** Use relative links in documentation (`apps/docs/`) + to ensure portability. Use paths relative to the current file's directory + (for example, `../tools/` from `docs/cli/`). Do not include the `/docs/` + section of a path, but do verify that the resulting relative link exists. This + does not apply to meta files such as README.MD and CONTRIBUTING.MD. +- **When changing headings, check for deep links:** If a user is changing a + heading, check for deep links to that heading in other pages and update + accordingly. + +### Structure +- **BLUF:** Start with an introduction explaining what to expect. +- **Experimental features:** If a feature is clearly noted as experimental, + add the following note immediately after the introductory paragraph: + +> [!NOTE] +> This is an experimental feature currently under active development. + +- **Headings:** Use hierarchical headings to support the user journey. +- **Procedures:** + - Introduce lists of steps with a complete sentence. + - Start each step with an imperative verb. + - Number sequential steps; use bullets for non-sequential lists. + - Put conditions before instructions (e.g., "On the Settings page, click..."). + - Provide clear context for where the action takes place. + - Indicate optional steps clearly (e.g., "Optional: ..."). +- **Elements:** Use bullet lists, tables, details, and callouts. +- **Avoid using a table of contents:** If a table of contents is present, remove + it. +- **Next steps:** Conclude with a "Next steps" section if applicable. + +## Phase 2: Preparation +Before modifying any documentation, thoroughly investigate the request and the +surrounding context. + +1. **Clarify:** Understand the core request. Differentiate between writing new + content and editing existing content. If the request is ambiguous (e.g., + "fix the docs"), ask for clarification. +2. **Investigate:** Examine relevant code (primarily in `packages/`) for + accuracy. +3. **Audit:** Read the latest versions of relevant files in `apps/docs/`. +4. **Connect:** Identify all referencing pages if changing behavior. +5. **Plan:** Create a step-by-step plan before making changes. + + +## Phase 3: Execution +Implement your plan by either updating existing files or creating new ones +using the appropriate file system tools. Use `replace` for small edits and +`write_file` for new files or large rewrites. + +### Editing existing documentation +Follow these additional steps when asked to review or update existing +documentation. + +- **Gaps:** Identify areas where the documentation is incomplete or no longer + reflects existing code. +- **Structure:** Apply "Structure (New Docs)" rules (BLUF, headings, etc.) when + adding new sections to existing pages. +- **Headers**: If you change a header, you must check for links that lead to + that header and update them. +- **Tone:** Ensure the tone is active and engaging. Use "you" and contractions. +- **Clarity:** Correct awkward wording, spelling, and grammar. Rephrase + sentences to make them easier for users to understand. +- **Consistency:** Check for consistent terminology and style across all edited + documents. + +## Phase 4: Verification and finalization +Perform a final quality check to ensure that all changes are correctly +formatted and that all links are functional. + +1. **Accuracy:** Ensure content accurately reflects the implementation and + technical behavior. +2. **Self-review:** Re-read changes for formatting, correctness, and flow. +3. **Link check:** Verify all new and existing links leading to or from + modified pages. If you changed a header, ensure that any links that lead to + it are updated. diff --git a/.agents/skills/elysiajs/SKILL.md b/.agents/skills/elysiajs/SKILL.md new file mode 100644 index 00000000..d707a647 --- /dev/null +++ b/.agents/skills/elysiajs/SKILL.md @@ -0,0 +1,475 @@ +--- +name: elysiajs +description: Create backend with ElysiaJS, a type-safe, high-performance framework. +--- + +# ElysiaJS Development Skill + +Always consult [elysiajs.com/llms.txt](https://elysiajs.com/llms.txt) for code examples and latest API. + +## Overview + +ElysiaJS is a TypeScript framework for building Bun-first (but not limited to Bun) type-safe, high-performance backend servers. This skill provides comprehensive guidance for developing with Elysia, including routing, validation, authentication, plugins, integrations, and deployment. + +## When to Use This Skill + +Trigger this skill when the user asks to: +- Create or modify ElysiaJS routes, handlers, or servers +- Setup validation with TypeBox or other schema libraries (Zod, Valibot) +- Implement authentication (JWT, session-based, macros, guards) +- Add plugins (CORS, OpenAPI, Static files, JWT) +- Integrate with external services (Drizzle ORM, Better Auth, Next.js, Eden Treaty) +- Setup WebSocket endpoints for real-time features +- Create unit tests for Elysia instances +- Deploy Elysia servers to production + +## Quick Start +Quick scaffold: +```bash +bun create elysia app +``` + +### Basic Server +```typescript +import { Elysia, t, status } from 'elysia' + +const app = new Elysia() + .get('/', () => 'Hello World') + .post('/user', ({ body }) => body, { + body: t.Object({ + name: t.String(), + age: t.Number() + }) + }) + .get('/id/:id', ({ params: { id } }) => { + if(id > 1_000_000) return status(404, 'Not Found') + + return id + }, { + params: t.Object({ + id: t.Number({ + minimum: 1 + }) + }), + response: { + 200: t.Number(), + 404: t.Literal('Not Found') + } + }) + .listen(3000) +``` + +## Basic Usage + +### HTTP Methods +```typescript +import { Elysia } from 'elysia' + +new Elysia() + .get('/', 'GET') + .post('/', 'POST') + .put('/', 'PUT') + .patch('/', 'PATCH') + .delete('/', 'DELETE') + .options('/', 'OPTIONS') + .head('/', 'HEAD') +``` + +### Path Parameters +```typescript +.get('/user/:id', ({ params: { id } }) => id) +.get('/post/:id/:slug', ({ params }) => params) +``` + +### Query Parameters +```typescript +.get('/search', ({ query }) => query.q) +// GET /search?q=elysia → "elysia" +``` + +### Request Body +```typescript +.post('/user', ({ body }) => body) +``` + +### Headers +```typescript +.get('/', ({ headers }) => headers.authorization) +``` + +## TypeBox Validation + +### Basic Types +```typescript +import { Elysia, t } from 'elysia' + +.post('/user', ({ body }) => body, { + body: t.Object({ + name: t.String(), + age: t.Number(), + email: t.String({ format: 'email' }), + website: t.Optional(t.String({ format: 'uri' })) + }) +}) +``` + +### Nested Objects +```typescript +body: t.Object({ + user: t.Object({ + name: t.String(), + address: t.Object({ + street: t.String(), + city: t.String() + }) + }) +}) +``` + +### Arrays +```typescript +body: t.Object({ + tags: t.Array(t.String()), + users: t.Array(t.Object({ + id: t.String(), + name: t.String() + })) +}) +``` + +### File Upload +```typescript +.post('/upload', ({ body }) => body.file, { + body: t.Object({ + file: t.File({ + type: 'image', // image/* mime types + maxSize: '5m' // 5 megabytes + }), + files: t.Files({ // Multiple files + type: ['image/png', 'image/jpeg'] + }) + }) +}) +``` + +### Response Validation +```typescript +.get('/user/:id', ({ params: { id } }) => ({ + id, + name: 'John', + email: 'john@example.com' +}), { + params: t.Object({ + id: t.Number() + }), + response: { + 200: t.Object({ + id: t.Number(), + name: t.String(), + email: t.String() + }), + 404: t.String() + } +}) +``` + +## Standard Schema (Zod, Valibot, ArkType) + +### Zod +```typescript +import { z } from 'zod' + +.post('/user', ({ body }) => body, { + body: z.object({ + name: z.string(), + age: z.number().min(0), + email: z.string().email() + }) +}) +``` + +## Error Handling + +```typescript +.get('/user/:id', ({ params: { id }, status }) => { + const user = findUser(id) + + if (!user) { + return status(404, 'User not found') + } + + return user +}) +``` + +## Guards (Apply to Multiple Routes) + +```typescript +.guard({ + params: t.Object({ + id: t.Number() + }) +}, app => app + .get('/user/:id', ({ params: { id } }) => id) + .delete('/user/:id', ({ params: { id } }) => id) +) +``` + +## Macro + +```typescript +.macro({ + hi: (word: string) => ({ + beforeHandle() { console.log(word) } + }) +}) +.get('/', () => 'hi', { hi: 'Elysia' }) +``` + +### Project Structure (Recommended) +Elysia takes an unopinionated approach but based on user request. But without any specific preference, we recommend a feature-based and domain driven folder structure where each feature has its own folder containing controllers, services, and models. + +``` +src/ +├── index.ts # Main server entry +├── modules/ +│ ├── auth/ +│ │ ├── index.ts # Auth routes (Elysia instance) +│ │ ├── service.ts # Business logic +│ │ └── model.ts # TypeBox schemas/DTOs +│ └── user/ +│ ├── index.ts +│ ├── service.ts +│ └── model.ts +└── plugins/ + └── custom.ts + +public/ # Static files (if using static plugin) +test/ # Unit tests +``` + +Each file has its own responsibility as follows: +- **Controller (index.ts)**: Handle HTTP routing, request validation, and cookie. +- **Service (service.ts)**: Handle business logic, decoupled from Elysia controller if possible. +- **Model (model.ts)**: Define the data structure and validation for the request and response. + +## Best Practice +Elysia is unopinionated on design pattern, but if not provided, we can relies on MVC pattern pair with feature based folder structure. + +- Controller: + - Prefers Elysia as a controller for HTTP dependant controller + - For non HTTP dependent, prefers service instead unless explicitly asked + - Use `onError` to handle local custom errors + - Register Model to Elysia instance via `Elysia.models({ ...models })` and prefix model by namespace `Elysia.prefix('model', 'Namespace.') + - Prefers Reference Model by name provided by Elysia instead of using an actual `Model.name` +- Service: + - Prefers class (or abstract class if possible) + - Prefers interface/type derive from `Model` + - Return `status` (`import { status } from 'elysia'`) for error + - Prefers `return Error` instead of `throw Error` +- Models: + - Always export validation model and type of validation model + - Custom Error should be in contains in Model + +## Elysia Key Concept +Elysia has a every important concepts/rules to understand before use. + +## Encapsulation - Isolates by Default + +Lifecycles (hooks, middleware) **don't leak** between instances unless scoped. + +**Scope levels:** +- `local` (default) - current instance + descendants +- `scoped` - parent + current + descendants +- `global` - all instances + +```ts +.onBeforeHandle(() => {}) // only local instance +.onBeforeHandle({ as: 'global' }, () => {}) // exports to all +``` + +## Method Chaining - Required for Types + +**Must chain**. Each method returns new type reference. + +❌ Don't: +```ts +const app = new Elysia() +app.state('build', 1) // loses type +app.get('/', ({ store }) => store.build) // build doesn't exists +``` + +✅ Do: +```ts +new Elysia() + .state('build', 1) + .get('/', ({ store }) => store.build) +``` + +## Explicit Dependencies + +Each instance independent. **Declare what you use.** + +```ts +const auth = new Elysia() + .decorate('Auth', Auth) + .model(Auth.models) + +new Elysia() + .get('/', ({ Auth }) => Auth.getProfile()) // Auth doesn't exists + +new Elysia() + .use(auth) // must declare + .get('/', ({ Auth }) => Auth.getProfile()) +``` + +**Global scope when:** +- No types added (cors, helmet) +- Global lifecycle (logging, tracing) + +**Explicit when:** +- Adds types (state, models) +- Business logic (auth, db) + +## Deduplication + +Plugins re-execute unless named: + +```ts +new Elysia() // rerun on `.use` +new Elysia({ name: 'ip' }) // runs once across all instances +``` + +## Order Matters + +Events apply to routes **registered after** them. + +```ts +.onBeforeHandle(() => console.log('1')) +.get('/', () => 'hi') // has hook +.onBeforeHandle(() => console.log('2')) // doesn't affect '/' +``` + +## Type Inference + +**Inline functions only** for accurate types. + +For controllers, destructure in inline wrapper: + +```ts +.post('/', ({ body }) => Controller.greet(body), { + body: t.Object({ name: t.String() }) +}) +``` + +Get type from schema: +```ts +type MyType = typeof MyType.static +``` + +## Reference Model +Model can be reference by name, especially great for documenting an API +```ts +new Elysia() + .model({ + book: t.Object({ + name: t.String() + }) + }) + .post('/', ({ body }) => body.name, { + body: 'book' + }) +``` + +Model can be renamed by using `.prefix` / `.suffix` +```ts +new Elysia() + .model({ + book: t.Object({ + name: t.String() + }) + }) + .prefix('model', 'Namespace') + .post('/', ({ body }) => body.name, { + body: 'Namespace.Book' + }) +``` + +Once `prefix`, model name will be capitalized by default. + +## Technical Terms +The following are technical terms that is use for Elysia: +- `OpenAPI Type Gen` - function name `fromTypes` from `@elysiajs/openapi` for generating OpenAPI from types, see `plugins/openapi.md` +- `Eden`, `Eden Treaty` - e2e type safe RPC client for share type from backend to frontend + +## Resources +Use the following references as needed. + +It's recommended to checkout `route.md` for as it contains the most important foundation building blocks with examples. + +`plugin.md` and `validation.md` is important as well but can be check as needed. + +### references/ +Detailed documentation split by topic: +- `bun-fullstack-dev-server.md` - Bun Fullstack Dev Server with HMR. React without bundler. +- `cookie.md` - Detailed documentation on cookie +- `deployment.md` - Production deployment guide / Docker +- `eden.md` - e2e type safe RPC client for share type from backend to frontend +- `guard.md` - Setting validation/lifecycle all at once +- `macro.md` - Compose multiple schema/lifecycle as a reusable Elysia via key-value (recommended for complex setup, eg. authentication, authorization, Role-based Access Check) +- `plugin.md` - Decouple part of Elysia into a standalone component +- `route.md` - Elysia foundation building block: Routing, Handler and Context +- `testing.md` - Unit tests with examples +- `validation.md` - Setup input/output validation and list of all custom validation rules +- `websocket.md` - Real-time features + +### plugins/ +Detailed documentation, usage and configuration reference for official Elysia plugin: +- `bearer.md` - Add bearer capability to Elysia (`@elysiajs/bearer`) +- `cors.md` - Out of box configuration for CORS (`@elysiajs/cors`) +- `cron.md` - Run cron job with access to Elysia context (`@elysiajs/cron`) +- `graphql-apollo.md` - Integration GraphQL Apollo (`@elysiajs/graphql-apollo`) +- `graphql-yoga.md` - Integration with GraphQL Yoga (`@elysiajs/graphql-yoga`) +- `html.md` - HTML and JSX plugin setup and usage (`@elysiajs/html`) +- `jwt.md` - JWT / JWK plugin (`@elysiajs/jwt`) +- `openapi.md` - OpenAPI documentation and OpenAPI Type Gen / OpenAPI from types (`@elysiajs/openapi`) +- `opentelemetry.md` - OpenTelemetry, instrumentation, and record span utilities (`@elysiajs/opentelemetry`) +- `server-timing.md` - Server Timing metric for debug (`@elysiajs/server-timing`) +- `static.md` - Serve static files/folders for Elysia Server (`@elysiajs/static`) + +### integrations/ +Guide to integrate Elysia with external library/runtime: +- `ai-sdk.md` - Using Vercel AI SDK with Elysia +- `astro.md` - Elysia in Astro API route +- `better-auth.md` - Integrate Elysia with better-auth +- `cloudflare-worker.md` - Elysia on Cloudflare Worker adapter +- `deno.md` - Elysia on Deno +- `drizzle.md` - Integrate Elysia with Drizzle ORM +- `expo.md` - Elysia in Expo API route +- `nextjs.md` - Elysia in Nextjs API route +- `nodejs.md` - Run Elysia on Node.js +- `nuxt.md` - Elysia on API route +- `prisma.md` - Integrate Elysia with Prisma +- `react-email.d` - Create and Send Email with React and Elysia +- `sveltekit.md` - Run Elysia on Svelte Kit API route +- `tanstack-start.md` - Run Elysia on Tanstack Start / React Query +- `vercel.md` - Deploy Elysia to Vercel + +### examples/ (optional) +- `basic.ts` - Basic Elysia example +- `body-parser.ts` - Custom body parser example via `.onParse` +- `complex.ts` - Comprehensive usage of Elysia server +- `cookie.ts` - Setting cookie +- `error.ts` - Error handling +- `file.ts` - Returning local file from server +- `guard.ts` - Setting mulitple validation schema and lifecycle +- `map-response.ts` - Custom response mapper +- `redirect.ts` - Redirect response +- `rename.ts` - Rename context's property +- `schema.ts` - Setup validation +- `state.ts` - Setup global state +- `upload-file.ts` - File upload with validation +- `websocket.ts` - Web Socket for realtime communication + +### patterns/ (optional) +- `patterns/mvc.md` - Detail guideline for using Elysia with MVC patterns diff --git a/.agents/skills/elysiajs/examples/basic.ts b/.agents/skills/elysiajs/examples/basic.ts new file mode 100644 index 00000000..61c8d14e --- /dev/null +++ b/.agents/skills/elysiajs/examples/basic.ts @@ -0,0 +1,9 @@ +import { Elysia, t } from 'elysia' + +new Elysia() + .get('/', 'Hello Elysia') + .post('/', ({ body: { name } }) => name, { + body: t.Object({ + name: t.String() + }) + }) diff --git a/.agents/skills/elysiajs/examples/body-parser.ts b/.agents/skills/elysiajs/examples/body-parser.ts new file mode 100644 index 00000000..533c7bf5 --- /dev/null +++ b/.agents/skills/elysiajs/examples/body-parser.ts @@ -0,0 +1,33 @@ +import { Elysia, t } from 'elysia' + +const app = new Elysia() + // Add custom body parser + .onParse(async ({ request, contentType }) => { + switch (contentType) { + case 'application/Elysia': + return request.text() + } + }) + .post('/', ({ body: { username } }) => `Hi ${username}`, { + body: t.Object({ + id: t.Number(), + username: t.String() + }) + }) + // Increase id by 1 from body before main handler + .post('/transform', ({ body }) => body, { + transform: ({ body }) => { + body.id = body.id + 1 + }, + body: t.Object({ + id: t.Number(), + username: t.String() + }), + detail: { + summary: 'A' + } + }) + .post('/mirror', ({ body }) => body) + .listen(3000) + +console.log('🦊 Elysia is running at :8080') diff --git a/.agents/skills/elysiajs/examples/complex.ts b/.agents/skills/elysiajs/examples/complex.ts new file mode 100644 index 00000000..436eda0f --- /dev/null +++ b/.agents/skills/elysiajs/examples/complex.ts @@ -0,0 +1,112 @@ +import { Elysia, t, file } from 'elysia' + +const loggerPlugin = new Elysia() + .get('/hi', () => 'Hi') + .decorate('log', () => 'A') + .decorate('date', () => new Date()) + .state('fromPlugin', 'From Logger') + .use((app) => app.state('abc', 'abc')) + +const app = new Elysia() + .onRequest(({ set }) => { + set.headers = { + 'Access-Control-Allow-Origin': '*' + } + }) + .onError(({ code }) => { + if (code === 'NOT_FOUND') + return 'Not Found :(' + }) + .use(loggerPlugin) + .state('build', Date.now()) + .get('/', 'Elysia') + .get('/tako', file('./example/takodachi.png')) + .get('/json', () => ({ + hi: 'world' + })) + .get('/root/plugin/log', ({ log, store: { build } }) => { + log() + + return build + }) + .get('/wildcard/*', () => 'Hi Wildcard') + .get('/query', () => 'Elysia', { + beforeHandle: ({ query }) => { + console.log('Name:', query?.name) + + if (query?.name === 'aom') return 'Hi saltyaom' + }, + query: t.Object({ + name: t.String() + }) + }) + .post('/json', async ({ body }) => body, { + body: t.Object({ + name: t.String(), + additional: t.String() + }) + }) + .post('/transform-body', async ({ body }) => body, { + beforeHandle: (ctx) => { + ctx.body = { + ...ctx.body, + additional: 'Elysia' + } + }, + body: t.Object({ + name: t.String(), + additional: t.String() + }) + }) + .get('/id/:id', ({ params: { id } }) => id, { + transform({ params }) { + params.id = +params.id + }, + params: t.Object({ + id: t.Number() + }) + }) + .post('/new/:id', async ({ body, params }) => body, { + params: t.Object({ + id: t.Number() + }), + body: t.Object({ + username: t.String() + }) + }) + .get('/trailing-slash', () => 'A') + .group('/group', (app) => + app + .onBeforeHandle(({ query }) => { + if (query?.name === 'aom') return 'Hi saltyaom' + }) + .get('/', () => 'From Group') + .get('/hi', () => 'HI GROUP') + .get('/elysia', () => 'Welcome to Elysian Realm') + .get('/fbk', () => 'FuBuKing') + ) + .get('/response-header', ({ set }) => { + set.status = 404 + set.headers['a'] = 'b' + + return 'A' + }) + .get('/this/is/my/deep/nested/root', () => 'Hi') + .get('/build', ({ store: { build } }) => build) + .get('/ref', ({ date }) => date()) + .get('/response', () => new Response('Hi')) + .get('/error', () => new Error('Something went wrong')) + .get('/401', ({ set }) => { + set.status = 401 + + return 'Status should be 401' + }) + .get('/timeout', async () => { + await new Promise((resolve) => setTimeout(resolve, 2000)) + + return 'A' + }) + .all('/all', () => 'hi') + .listen(8080, ({ hostname, port }) => { + console.log(`🦊 Elysia is running at http://${hostname}:${port}`) + }) diff --git a/.agents/skills/elysiajs/examples/cookie.ts b/.agents/skills/elysiajs/examples/cookie.ts new file mode 100644 index 00000000..9a427203 --- /dev/null +++ b/.agents/skills/elysiajs/examples/cookie.ts @@ -0,0 +1,45 @@ +import { Elysia, t } from 'elysia' + +const app = new Elysia({ + cookie: { + secrets: 'Fischl von Luftschloss Narfidort', + sign: ['name'] + } +}) + .get( + '/council', + ({ cookie: { council } }) => + (council.value = [ + { + name: 'Rin', + affilation: 'Administration' + } + ]), + { + cookie: t.Cookie({ + council: t.Array( + t.Object({ + name: t.String(), + affilation: t.String() + }) + ) + }) + } + ) + .get('/create', ({ cookie: { name } }) => (name.value = 'Himari')) + .get( + '/update', + ({ cookie: { name } }) => { + name.value = 'seminar: Rio' + name.value = 'seminar: Himari' + name.maxAge = 86400 + + return name.value + }, + { + cookie: t.Cookie({ + name: t.Optional(t.String()) + }) + } + ) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/error.ts b/.agents/skills/elysiajs/examples/error.ts new file mode 100644 index 00000000..2c2f126a --- /dev/null +++ b/.agents/skills/elysiajs/examples/error.ts @@ -0,0 +1,38 @@ +import { Elysia, t } from 'elysia' + +class CustomError extends Error { + constructor(public name: string) { + super(name) + } +} + +new Elysia() + .error({ + CUSTOM_ERROR: CustomError + }) + // global handler + .onError(({ code, error, status }) => { + switch (code) { + case "CUSTOM_ERROR": + return status(401, { message: error.message }) + + case "NOT_FOUND": + return "Not found :(" + } + }) + .post('/', ({ body }) => body, { + body: t.Object({ + username: t.String(), + password: t.String(), + nested: t.Optional( + t.Object({ + hi: t.String() + }) + ) + }), + // local handler + error({ error }) { + console.log(error) + } + }) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/file.ts b/.agents/skills/elysiajs/examples/file.ts new file mode 100644 index 00000000..504cad7e --- /dev/null +++ b/.agents/skills/elysiajs/examples/file.ts @@ -0,0 +1,10 @@ +import { Elysia, file } from 'elysia' + +/** + * Example of handle single static file + * + * @see https://github.com/elysiajs/elysia-static + */ +new Elysia() + .get('/tako', file('./example/takodachi.png')) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/guard.ts b/.agents/skills/elysiajs/examples/guard.ts new file mode 100644 index 00000000..2fe158f2 --- /dev/null +++ b/.agents/skills/elysiajs/examples/guard.ts @@ -0,0 +1,34 @@ +import { Elysia, t } from 'elysia' + +new Elysia() + .state('name', 'salt') + .get('/', ({ store: { name } }) => `Hi ${name}`, { + query: t.Object({ + name: t.String() + }) + }) + // If query 'name' is not preset, skip the whole handler + .guard( + { + query: t.Object({ + name: t.String() + }) + }, + (app) => + app + // Query type is inherited from guard + .get('/profile', ({ query }) => `Hi`) + // Store is inherited + .post('/name', ({ store: { name }, body, query }) => name, { + body: t.Object({ + id: t.Number({ + minimum: 5 + }), + username: t.String(), + profile: t.Object({ + name: t.String() + }) + }) + }) + ) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/map-response.ts b/.agents/skills/elysiajs/examples/map-response.ts new file mode 100644 index 00000000..8cd4be40 --- /dev/null +++ b/.agents/skills/elysiajs/examples/map-response.ts @@ -0,0 +1,15 @@ +import { Elysia } from 'elysia' + +const prettyJson = new Elysia() + .mapResponse(({ response }) => { + if (response instanceof Object) + return new Response(JSON.stringify(response, null, 4)) + }) + .as('scoped') + +new Elysia() + .use(prettyJson) + .get('/', () => ({ + hello: 'world' + })) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/redirect.ts b/.agents/skills/elysiajs/examples/redirect.ts new file mode 100644 index 00000000..28171b00 --- /dev/null +++ b/.agents/skills/elysiajs/examples/redirect.ts @@ -0,0 +1,6 @@ +import { Elysia } from 'elysia' + +new Elysia() + .get('/', () => 'Hi') + .get('/redirect', ({ redirect }) => redirect('/')) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/rename.ts b/.agents/skills/elysiajs/examples/rename.ts new file mode 100644 index 00000000..361f06fd --- /dev/null +++ b/.agents/skills/elysiajs/examples/rename.ts @@ -0,0 +1,32 @@ +import { Elysia, t } from 'elysia' + +// ? Elysia#83 | Proposal: Standardized way of renaming third party plugin-scoped stuff +// this would be a plugin provided by a third party +const myPlugin = new Elysia() + .decorate('myProperty', 42) + .model('salt', t.String()) + +new Elysia() + .use( + myPlugin + // map decorator, rename "myProperty" to "renamedProperty" + .decorate(({ myProperty, ...decorators }) => ({ + renamedProperty: myProperty, + ...decorators + })) + // map model, rename "salt" to "pepper" + .model(({ salt, ...models }) => ({ + ...models, + pepper: t.String() + })) + // Add prefix + .prefix('decorator', 'unstable') + ) + .get( + '/mapped', + ({ unstableRenamedProperty }) => unstableRenamedProperty + ) + .post('/pepper', ({ body }) => body, { + body: 'pepper', + // response: t.String() + }) diff --git a/.agents/skills/elysiajs/examples/schema.ts b/.agents/skills/elysiajs/examples/schema.ts new file mode 100644 index 00000000..db79300c --- /dev/null +++ b/.agents/skills/elysiajs/examples/schema.ts @@ -0,0 +1,61 @@ +import { Elysia, t } from 'elysia' + +const app = new Elysia() + .model({ + name: t.Object({ + name: t.String() + }), + b: t.Object({ + response: t.Number() + }), + authorization: t.Object({ + authorization: t.String() + }) + }) + // Strictly validate response + .get('/', () => 'hi') + // Strictly validate body and response + .post('/', ({ body, query }) => body.id, { + body: t.Object({ + id: t.Number(), + username: t.String(), + profile: t.Object({ + name: t.String() + }) + }) + }) + // Strictly validate query, params, and body + .get('/query/:id', ({ query: { name }, params }) => name, { + query: t.Object({ + name: t.String() + }), + params: t.Object({ + id: t.String() + }), + response: { + 200: t.String(), + 300: t.Object({ + error: t.String() + }) + } + }) + .guard( + { + headers: 'authorization' + }, + (app) => + app + .derive(({ headers }) => ({ + userId: headers.authorization + })) + .get('/', ({ userId }) => 'A') + .post('/id/:id', ({ query, body, params, userId }) => body, { + params: t.Object({ + id: t.Number() + }), + transform({ params }) { + params.id = +params.id + } + }) + ) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/state.ts b/.agents/skills/elysiajs/examples/state.ts new file mode 100644 index 00000000..8bcc993e --- /dev/null +++ b/.agents/skills/elysiajs/examples/state.ts @@ -0,0 +1,6 @@ +import { Elysia } from 'elysia' + +new Elysia() + .state('counter', 0) + .get('/', ({ store }) => store.counter++) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/upload-file.ts b/.agents/skills/elysiajs/examples/upload-file.ts new file mode 100644 index 00000000..4af5a198 --- /dev/null +++ b/.agents/skills/elysiajs/examples/upload-file.ts @@ -0,0 +1,20 @@ +import { Elysia, t } from 'elysia' + +const app = new Elysia() + .post('/single', ({ body: { file } }) => file, { + body: t.Object({ + file: t.File({ + maxSize: '1m' + }) + }) + }) + .post( + '/multiple', + ({ body: { files } }) => files.reduce((a, b) => a + b.size, 0), + { + body: t.Object({ + files: t.Files() + }) + } + ) + .listen(3000) diff --git a/.agents/skills/elysiajs/examples/websocket.ts b/.agents/skills/elysiajs/examples/websocket.ts new file mode 100644 index 00000000..f97e47bf --- /dev/null +++ b/.agents/skills/elysiajs/examples/websocket.ts @@ -0,0 +1,25 @@ +import { Elysia } from 'elysia' + +const app = new Elysia() + .state('start', 'here') + .ws('/ws', { + open(ws) { + ws.subscribe('asdf') + console.log('Open Connection:', ws.id) + }, + close(ws) { + console.log('Closed Connection:', ws.id) + }, + message(ws, message) { + ws.publish('asdf', message) + ws.send(message) + } + }) + .get('/publish/:publish', ({ params: { publish: text } }) => { + app.server!.publish('asdf', text) + + return text + }) + .listen(3000, (server) => { + console.log(`http://${server.hostname}:${server.port}`) + }) diff --git a/.agents/skills/elysiajs/integrations/ai-sdk.md b/.agents/skills/elysiajs/integrations/ai-sdk.md new file mode 100644 index 00000000..99f54091 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/ai-sdk.md @@ -0,0 +1,92 @@ +# AI SDK Integration + +## What It Is +Seamless integration with Vercel AI SDK via response streaming. + +## Response Streaming +Return `ReadableStream` or `Response` directly: +```typescript +import { streamText } from 'ai' +import { openai } from '@ai-sdk/openai' + +new Elysia().get('/', () => { + const stream = streamText({ + model: openai('gpt-5'), + system: 'You are Yae Miko from Genshin Impact', + prompt: 'Hi! How are you doing?' + }) + + return stream.textStream // ReadableStream + // or + return stream.toUIMessageStream() // UI Message Stream +}) +``` + +Elysia auto-handles stream. + +## Server-Sent Events +Wrap `ReadableStream` with `sse`: +```typescript +import { sse } from 'elysia' + +.get('/', () => { + const stream = streamText({ /* ... */ }) + + return sse(stream.textStream) + // or + return sse(stream.toUIMessageStream()) +}) +``` + +Each chunk → SSE. + +## As Response +Return stream directly (no Eden type safety): +```typescript +.get('/', () => { + const stream = streamText({ /* ... */ }) + + return stream.toTextStreamResponse() + // or + return stream.toUIMessageStreamResponse() // Uses SSE +}) +``` + +## Manual Streaming +Generator function for control: +```typescript +import { sse } from 'elysia' + +.get('/', async function* () { + const stream = streamText({ /* ... */ }) + + for await (const data of stream.textStream) + yield sse({ data, event: 'message' }) + + yield sse({ event: 'done' }) +}) +``` + +## Fetch for Unsupported Models +Direct fetch with streaming proxy: +```typescript +.get('/', () => { + return fetch('https://api.openai.com/v1/chat/completions', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${process.env.OPENAI_API_KEY}` + }, + body: JSON.stringify({ + model: 'gpt-5', + stream: true, + messages: [ + { role: 'system', content: 'You are Yae Miko' }, + { role: 'user', content: 'Hi! How are you doing?' } + ] + }) + }) +}) +``` + +Elysia auto-proxies fetch response with streaming. diff --git a/.agents/skills/elysiajs/integrations/astro.md b/.agents/skills/elysiajs/integrations/astro.md new file mode 100644 index 00000000..41cd4512 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/astro.md @@ -0,0 +1,59 @@ +# Astro Integration - SKILLS.md + +## What It Is +Run Elysia on Astro via Astro Endpoint. + +## Setup +1. Set output to server: +```javascript +// astro.config.mjs +export default defineConfig({ + output: 'server' +}) +``` + +2. Create `pages/[...slugs].ts` +3. Define Elysia server + export handlers: +```typescript +// pages/[...slugs].ts +import { Elysia, t } from 'elysia' + +const app = new Elysia() + .get('/api', () => 'hi') + .post('/api', ({ body }) => body, { + body: t.Object({ name: t.String() }) + }) + +const handle = ({ request }: { request: Request }) => app.handle(request) + +export const GET = handle +export const POST = handle +``` + +WinterCG compliance - works normally. + +Recommended: Run Astro on Bun (Elysia designed for Bun). + +## Prefix for Non-Root +If placed in `pages/api/[...slugs].ts`, set prefix: +```typescript +// pages/api/[...slugs].ts +const app = new Elysia({ prefix: '/api' }) + .get('/', () => 'hi') + +const handle = ({ request }: { request: Request }) => app.handle(request) + +export const GET = handle +export const POST = handle +``` + +Ensures routing works in any location. + +## Benefits +Co-location of frontend + backend. End-to-end type safety with Eden. + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/better-auth.md b/.agents/skills/elysiajs/integrations/better-auth.md new file mode 100644 index 00000000..0dfa3aff --- /dev/null +++ b/.agents/skills/elysiajs/integrations/better-auth.md @@ -0,0 +1,117 @@ +# Better Auth Integration +Elysia + Better Auth integration guide + +## What It Is +Framework-agnostic TypeScript auth/authz. Comprehensive features + plugin ecosystem. + +## Setup +```typescript +import { betterAuth } from 'better-auth' +import { Pool } from 'pg' + +export const auth = betterAuth({ + database: new Pool() +}) +``` + +## Handler Mounting +```typescript +import { auth } from './auth' + +new Elysia() + .mount(auth.handler) // http://localhost:3000/api/auth + .listen(3000) +``` + +### Custom Endpoint +```typescript +// Mount with prefix +.mount('/auth', auth.handler) // http://localhost:3000/auth/api/auth + +// Customize basePath +export const auth = betterAuth({ + basePath: '/api' // http://localhost:3000/auth/api +}) +``` + +Cannot set `basePath` to empty or `/`. + +## OpenAPI Integration +Extract docs from Better Auth: +```typescript +import { openAPI } from 'better-auth/plugins' + +let _schema: ReturnType +const getSchema = async () => (_schema ??= auth.api.generateOpenAPISchema()) + +export const OpenAPI = { + getPaths: (prefix = '/auth/api') => + getSchema().then(({ paths }) => { + const reference: typeof paths = Object.create(null) + + for (const path of Object.keys(paths)) { + const key = prefix + path + reference[key] = paths[path] + + for (const method of Object.keys(paths[path])) { + const operation = (reference[key] as any)[method] + operation.tags = ['Better Auth'] + } + } + + return reference + }) as Promise, + components: getSchema().then(({ components }) => components) as Promise +} as const +``` + +Apply to Elysia: +```typescript +new Elysia().use(openapi({ + documentation: { + components: await OpenAPI.components, + paths: await OpenAPI.getPaths() + } +})) +``` + +## CORS +```typescript +import { cors } from '@elysiajs/cors' + +new Elysia() + .use(cors({ + origin: 'http://localhost:3001', + methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + credentials: true, + allowedHeaders: ['Content-Type', 'Authorization'] + })) + .mount(auth.handler) +``` + +## Macro for Auth +Use macro + resolve for session/user: +```typescript +const betterAuth = new Elysia({ name: 'better-auth' }) + .mount(auth.handler) + .macro({ + auth: { + async resolve({ status, request: { headers } }) { + const session = await auth.api.getSession({ headers }) + + if (!session) return status(401) + + return { + user: session.user, + session: session.session + } + } + } + }) + +new Elysia() + .use(betterAuth) + .get('/user', ({ user }) => user, { auth: true }) +``` + +Access `user` and `session` in all routes. diff --git a/.agents/skills/elysiajs/integrations/cloudflare-worker.md b/.agents/skills/elysiajs/integrations/cloudflare-worker.md new file mode 100644 index 00000000..4245c1aa --- /dev/null +++ b/.agents/skills/elysiajs/integrations/cloudflare-worker.md @@ -0,0 +1,95 @@ + +# Cloudflare Worker Integration + +## What It Is +**Experimental** Cloudflare Worker adapter for Elysia. + +## Setup +1. Install Wrangler: +```bash +wrangler init elysia-on-cloudflare +``` + +2. Apply adapter + compile: +```typescript +import { Elysia } from 'elysia' +import { CloudflareAdapter } from 'elysia/adapter/cloudflare-worker' + +export default new Elysia({ + adapter: CloudflareAdapter +}) + .get('/', () => 'Hello Cloudflare Worker!') + .compile() // Required +``` + +3. Set compatibility date (min `2025-06-01`): +```json +// wrangler.json +{ + "name": "elysia-on-cloudflare", + "main": "src/index.ts", + "compatibility_date": "2025-06-01" +} +``` + +4. Dev server: +```bash +wrangler dev +# http://localhost:8787 +``` + +No `nodejs_compat` flag needed. + +## Limitations +1. `Elysia.file` + Static Plugin don't work (no `fs` module) +2. OpenAPI Type Gen doesn't work (no `fs` module) +3. Cannot define Response before server start +4. Cannot inline values: +```typescript +// ❌ Throws error +.get('/', 'Hello Elysia') + +// ✅ Works +.get('/', () => 'Hello Elysia') +``` + +## Static Files +Use Cloudflare's built-in static serving: +```json +// wrangler.json +{ + "assets": { "directory": "public" } +} +``` + +Structure: +``` +├─ public +│ ├─ kyuukurarin.mp4 +│ └─ static/mika.webp +``` + +Access: +- `http://localhost:8787/kyuukurarin.mp4` +- `http://localhost:8787/static/mika.webp` + +## Binding +Import env from `cloudflare:workers`: +```typescript +import { env } from 'cloudflare:workers' + +export default new Elysia({ adapter: CloudflareAdapter }) + .get('/', () => `Hello ${await env.KV.get('my-key')}`) + .compile() +``` + +## AoT Compilation +As of Elysia 1.4.7, AoT works with Cloudflare Worker. Drop `aot: false` flag. + +Cloudflare now supports Function compilation during startup. + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/deno.md b/.agents/skills/elysiajs/integrations/deno.md new file mode 100644 index 00000000..28687d57 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/deno.md @@ -0,0 +1,34 @@ +# Deno Integration +Run Elysia on Deno + +## What It Is +Run Elysia on Deno via Web Standard Request/Response. + +## Setup +Wrap `Elysia.fetch` in `Deno.serve`: +```typescript +import { Elysia } from 'elysia' + +const app = new Elysia() + .get('/', () => 'Hello Elysia') + .listen(3000) + +Deno.serve(app.fetch) +``` + +Run: +```bash +deno serve --watch src/index.ts +``` + +## Port Config +```typescript +Deno.serve(app.fetch) // Default +Deno.serve({ port: 8787 }, app.fetch) // Custom port +``` + +## pnpm +[Inference] pnpm doesn't auto-install peer deps. Manual install required: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/drizzle.md b/.agents/skills/elysiajs/integrations/drizzle.md new file mode 100644 index 00000000..779db4e0 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/drizzle.md @@ -0,0 +1,258 @@ +# Drizzle Integration +Elysia + Drizzle integration guide + +## What It Is +Headless TypeScript ORM. Convert Drizzle schema → Elysia validation models via `drizzle-typebox`. + +## Flow +``` +Drizzle → drizzle-typebox → Elysia validation → OpenAPI + Eden Treaty +``` + +## Installation +```bash +bun add drizzle-orm drizzle-typebox +``` + +### Pin TypeBox Version +Prevent Symbol conflicts: +```bash +grep "@sinclair/typebox" node_modules/elysia/package.json +``` + +Add to `package.json`: +```json +{ + "overrides": { + "@sinclair/typebox": "0.32.4" + } +} +``` + +## Drizzle Schema +```typescript +// src/database/schema.ts +import { pgTable, varchar, timestamp } from 'drizzle-orm/pg-core' +import { createId } from '@paralleldrive/cuid2' + +export const user = pgTable('user', { + id: varchar('id').$defaultFn(() => createId()).primaryKey(), + username: varchar('username').notNull().unique(), + password: varchar('password').notNull(), + email: varchar('email').notNull().unique(), + salt: varchar('salt', { length: 64 }).notNull(), + createdAt: timestamp('created_at').defaultNow().notNull() +}) + +export const table = { user } as const +export type Table = typeof table +``` + +## drizzle-typebox +```typescript +import { t } from 'elysia' +import { createInsertSchema } from 'drizzle-typebox' +import { table } from './database/schema' + +const _createUser = createInsertSchema(table.user, { + email: t.String({ format: 'email' }) // Replace with Elysia type +}) + +new Elysia() + .post('/sign-up', ({ body }) => {}, { + body: t.Omit(_createUser, ['id', 'salt', 'createdAt']) + }) +``` + +## Type Instantiation Error +**Error**: "Type instantiation is possibly infinite" + +**Cause**: Circular reference when nesting drizzle-typebox into Elysia schema. + +**Fix**: Explicitly define type between them: +```typescript +// ✅ Works +const _createUser = createInsertSchema(table.user, { + email: t.String({ format: 'email' }) +}) +const createUser = t.Omit(_createUser, ['id', 'salt', 'createdAt']) + +// ❌ Infinite loop +const createUser = t.Omit( + createInsertSchema(table.user, { email: t.String({ format: 'email' }) }), + ['id', 'salt', 'createdAt'] +) +``` + +Always declare variable for drizzle-typebox then reference it. + +## Utility Functions +Copy as-is for simplified usage: +```typescript +// src/database/utils.ts +/** + * @lastModified 2025-02-04 + * @see https://elysiajs.com/recipe/drizzle.html#utility + */ + +import { Kind, type TObject } from '@sinclair/typebox' +import { + createInsertSchema, + createSelectSchema, + BuildSchema, +} from 'drizzle-typebox' + +import { table } from './schema' +import type { Table } from 'drizzle-orm' + +type Spread< + T extends TObject | Table, + Mode extends 'select' | 'insert' | undefined, +> = + T extends TObject + ? { + [K in keyof Fields]: Fields[K] + } + : T extends Table + ? Mode extends 'select' + ? BuildSchema< + 'select', + T['_']['columns'], + undefined + >['properties'] + : Mode extends 'insert' + ? BuildSchema< + 'insert', + T['_']['columns'], + undefined + >['properties'] + : {} + : {} + +/** + * Spread a Drizzle schema into a plain object + */ +export const spread = < + T extends TObject | Table, + Mode extends 'select' | 'insert' | undefined, +>( + schema: T, + mode?: Mode, +): Spread => { + const newSchema: Record = {} + let table + + switch (mode) { + case 'insert': + case 'select': + if (Kind in schema) { + table = schema + break + } + + table = + mode === 'insert' + ? createInsertSchema(schema) + : createSelectSchema(schema) + + break + + default: + if (!(Kind in schema)) throw new Error('Expect a schema') + table = schema + } + + for (const key of Object.keys(table.properties)) + newSchema[key] = table.properties[key] + + return newSchema as any +} + +/** + * Spread a Drizzle Table into a plain object + * + * If `mode` is 'insert', the schema will be refined for insert + * If `mode` is 'select', the schema will be refined for select + * If `mode` is undefined, the schema will be spread as is, models will need to be refined manually + */ +export const spreads = < + T extends Record, + Mode extends 'select' | 'insert' | undefined, +>( + models: T, + mode?: Mode, +): { + [K in keyof T]: Spread +} => { + const newSchema: Record = {} + const keys = Object.keys(models) + + for (const key of keys) newSchema[key] = spread(models[key], mode) + + return newSchema as any +} +``` + +Usage: +```typescript +// ✅ Using spread +const user = spread(table.user, 'insert') +const createUser = t.Object({ + id: user.id, + username: user.username, + password: user.password +}) + +// ⚠️ Using t.Pick +const _createUser = createInsertSchema(table.user) +const createUser = t.Pick(_createUser, ['id', 'username', 'password']) +``` + +## Table Singleton Pattern +```typescript +// src/database/model.ts +import { table } from './schema' +import { spreads } from './utils' + +export const db = { + insert: spreads({ user: table.user }, 'insert'), + select: spreads({ user: table.user }, 'select') +} as const +``` + +Usage: +```typescript +// src/index.ts +import { db } from './database/model' +const { user } = db.insert + +new Elysia() + .post('/sign-up', ({ body }) => {}, { + body: t.Object({ + id: user.username, + username: user.username, + password: user.password + }) + }) +``` + +## Refinement +```typescript +// src/database/model.ts +import { createInsertSchema, createSelectSchema } from 'drizzle-typebox' + +export const db = { + insert: spreads({ + user: createInsertSchema(table.user, { + email: t.String({ format: 'email' }) + }) + }, 'insert'), + select: spreads({ + user: createSelectSchema(table.user, { + email: t.String({ format: 'email' }) + }) + }, 'select') +} as const +``` + +`spread` skips refined schemas. diff --git a/.agents/skills/elysiajs/integrations/expo.md b/.agents/skills/elysiajs/integrations/expo.md new file mode 100644 index 00000000..fad14719 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/expo.md @@ -0,0 +1,95 @@ +# Expo Integration +Run Elysia on Expo (React Native) + +## What It Is +Create API routes in Expo app (SDK 50+, App Router v3). + +## Setup +1. Create `app/[...slugs]+api.ts` +2. Define Elysia server +3. Export `Elysia.fetch` as HTTP methods + +```typescript +// app/[...slugs]+api.ts +import { Elysia, t } from 'elysia' + +const app = new Elysia() + .get('/', 'hello Expo') + .post('/', ({ body }) => body, { + body: t.Object({ name: t.String() }) + }) + +export const GET = app.fetch +export const POST = app.fetch +``` + +## Prefix for Non-Root +If placed in `app/api/[...slugs]+api.ts`, set prefix: +```typescript +const app = new Elysia({ prefix: '/api' }) + .get('/', 'Hello Expo') + +export const GET = app.fetch +export const POST = app.fetch +``` + +Ensures routing works in any location. + +## Eden (End-to-End Type Safety) +1. Export type: +```typescript +// app/[...slugs]+api.ts +const app = new Elysia() + .get('/', 'Hello Nextjs') + .post('/user', ({ body }) => body, { + body: treaty.schema('User', { name: 'string' }) + }) + +export type app = typeof app + +export const GET = app.fetch +export const POST = app.fetch +``` + +2. Create client: +```typescript +// lib/eden.ts +import { treaty } from '@elysiajs/eden' +import type { app } from '../app/[...slugs]+api' + +export const api = treaty('localhost:3000/api') +``` + +3. Use in components: +```tsx +// app/page.tsx +import { api } from '../lib/eden' + +export default async function Page() { + const message = await api.get() + return

Hello, {message}

+} +``` + +## Deployment +- Deploy as normal Elysia app OR +- Use experimental Expo server runtime + +With Expo runtime: +```bash +expo export +# Creates dist/server/_expo/functions/[...slugs]+api.js +``` + +Edge function, not normal server (no port allocation). + +### Adapters +- Express +- Netlify +- Vercel + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/nextjs.md b/.agents/skills/elysiajs/integrations/nextjs.md new file mode 100644 index 00000000..ddbc8499 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/nextjs.md @@ -0,0 +1,103 @@ + +# Next.js Integration + +## What It Is +Run Elysia on Next.js App Router. + +## Setup +1. Create `app/api/[[...slugs]]/route.ts` +2. Define Elysia + export handlers: +```typescript +// app/api/[[...slugs]]/route.ts +import { Elysia, t } from 'elysia' + +const app = new Elysia({ prefix: '/api' }) + .get('/', 'Hello Nextjs') + .post('/', ({ body }) => body, { + body: t.Object({ name: t.String() }) + }) + +export const GET = app.fetch +export const POST = app.fetch +``` + +WinterCG compliance - works as normal Next.js API route. + +## Prefix for Non-Root +If placed in `app/user/[[...slugs]]/route.ts`, set prefix: +```typescript +const app = new Elysia({ prefix: '/user' }) + .get('/', 'Hello Nextjs') + +export const GET = app.fetch +export const POST = app.fetch +``` + +## Eden (End-to-End Type Safety) +Isomorphic fetch pattern: +- Server: Direct calls (no network) +- Client: Network calls + +1. Export type: +```typescript +// app/api/[[...slugs]]/route.ts +export const app = new Elysia({ prefix: '/api' }) + .get('/', 'Hello Nextjs') + .post('/user', ({ body }) => body, { + body: treaty.schema('User', { name: 'string' }) + }) + +export type app = typeof app + +export const GET = app.fetch +export const POST = app.fetch +``` + +2. Create client: +```typescript +// lib/eden.ts +import { treaty } from '@elysiajs/eden' +import type { app } from '../app/api/[[...slugs]]/route' + +export const api = + typeof process !== 'undefined' + ? treaty(app).api + : treaty('localhost:3000').api +``` + +Use `typeof process` not `typeof window` (window undefined at build time → hydration error). + +3. Use in components: +```tsx +// app/page.tsx +import { api } from '../lib/eden' + +export default async function Page() { + const message = await api.get() + return

Hello, {message}

+} +``` + +Works with server/client components + ISR. + +## React Query +```tsx +import { useQuery } from '@tanstack/react-query' + +function App() { + const { data: response } = useQuery({ + queryKey: ['get'], + queryFn: () => getTreaty().get() + }) + + return response?.data +} +``` + +Works with all React Query features. + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/nodejs.md b/.agents/skills/elysiajs/integrations/nodejs.md new file mode 100644 index 00000000..ce2edfa5 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/nodejs.md @@ -0,0 +1,64 @@ +# Node.js Integration +Run Elysia on Node.js + +## What It Is +Runtime adapter to run Elysia on Node.js. + +## Installation +```bash +bun add elysia @elysiajs/node +``` + +## Setup +Apply node adapter: +```typescript +import { Elysia } from 'elysia' +import { node } from '@elysiajs/node' + +const app = new Elysia({ adapter: node() }) + .get('/', () => 'Hello Elysia') + .listen(3000) +``` + +## Additional Setup (Recommended) +Install `tsx` for hot-reload: +```bash +bun add -d tsx @types/node typescript +``` + +Scripts in `package.json`: +```json +{ + "scripts": { + "dev": "tsx watch src/index.ts", + "build": "tsc src/index.ts --outDir dist", + "start": "NODE_ENV=production node dist/index.js" + } +} +``` + +- **dev**: Hot-reload dev mode +- **build**: Production build +- **start**: Production server + +Create `tsconfig.json`: +```bash +tsc --init +``` + +Update strict mode: +```json +{ + "compilerOptions": { + "strict": true + } +} +``` + +Provides hot-reload + JSX support similar to `bun dev`. + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/nuxt.md b/.agents/skills/elysiajs/integrations/nuxt.md new file mode 100644 index 00000000..0b4d13d3 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/nuxt.md @@ -0,0 +1,67 @@ +# Nuxt Integration + +## What It Is +Community plugin `nuxt-elysia` for Nuxt API routes with Eden Treaty. + +## Installation +```bash +bun add elysia @elysiajs/eden +bun add -d nuxt-elysia +``` + +## Setup +1. Add to Nuxt config: +```typescript +export default defineNuxtConfig({ + modules: ['nuxt-elysia'] +}) +``` + +2. Create `api.ts` at project root: +```typescript +// api.ts +export default () => new Elysia() + .get('/hello', () => ({ message: 'Hello world!' })) +``` + +3. Use Eden Treaty: +```vue + + +``` + +Auto-setup on Nuxt API route. + +## Prefix +Default: `/_api`. Customize: +```typescript +export default defineNuxtConfig({ + nuxtElysia: { + path: '/api' + } +}) +``` + +Mounts on `/api` instead of `/_api`. + +See [nuxt-elysia](https://github.com/tkesgar/nuxt-elysia) for more config. + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/prisma.md b/.agents/skills/elysiajs/integrations/prisma.md new file mode 100644 index 00000000..f0684f1c --- /dev/null +++ b/.agents/skills/elysiajs/integrations/prisma.md @@ -0,0 +1,93 @@ + +# Prisma Integration +Elysia + Prisma integration guide + +## What It Is +Type-safe ORM. Generate Elysia validation models from Prisma schema via `prismabox`. + +## Flow +``` +Prisma → prismabox → Elysia validation → OpenAPI + Eden Treaty +``` + +## Installation +```bash +bun add @prisma/client prismabox && \ +bun add -d prisma +``` + +## Prisma Schema +Add `prismabox` generator: +```prisma +// prisma/schema.prisma +generator client { + provider = "prisma-client" + output = "../generated/prisma" +} + +datasource db { + provider = "sqlite" + url = env("DATABASE_URL") +} + +generator prismabox { + provider = "prismabox" + typeboxImportDependencyName = "elysia" + typeboxImportVariableName = "t" + inputModel = true + output = "../generated/prismabox" +} + +model User { + id String @id @default(cuid()) + email String @unique + name String? + posts Post[] +} + +model Post { + id String @id @default(cuid()) + title String + content String? + published Boolean @default(false) + author User @relation(fields: [authorId], references: [id]) + authorId String +} +``` + +Generates: +- `User` → `generated/prismabox/User.ts` +- `Post` → `generated/prismabox/Post.ts` + +## Using Generated Models +```typescript +// src/index.ts +import { Elysia, t } from 'elysia' +import { PrismaClient } from '../generated/prisma' +import { UserPlain, UserPlainInputCreate } from '../generated/prismabox/User' + +const prisma = new PrismaClient() + +new Elysia() + .put('/', async ({ body }) => + prisma.user.create({ data: body }), { + body: UserPlainInputCreate, + response: UserPlain + } + ) + .get('/id/:id', async ({ params: { id }, status }) => { + const user = await prisma.user.findUnique({ where: { id } }) + + if (!user) return status(404, 'User not found') + + return user + }, { + response: { + 200: UserPlain, + 404: t.String() + } + }) + .listen(3000) +``` + +Reuses DB schema in Elysia validation models. diff --git a/.agents/skills/elysiajs/integrations/react-email.md b/.agents/skills/elysiajs/integrations/react-email.md new file mode 100644 index 00000000..1cb636f4 --- /dev/null +++ b/.agents/skills/elysiajs/integrations/react-email.md @@ -0,0 +1,134 @@ +# React Email Integration + +## What It Is +Use React components to create emails. Direct JSX import via Bun. + +## Installation +```bash +bun add -d react-email +bun add @react-email/components react react-dom +``` + +Script in `package.json`: +```json +{ + "scripts": { + "email": "email dev --dir src/emails" + } +} +``` + +Email templates → `src/emails` directory. + +### TypeScript +Add to `tsconfig.json`: +```json +{ + "compilerOptions": { + "jsx": "react" + } +} +``` + +## Email Template +```tsx +// src/emails/otp.tsx +import * as React from 'react' +import { Tailwind, Section, Text } from '@react-email/components' + +export default function OTPEmail({ otp }: { otp: number }) { + return ( + +
+
+ + Verify your Email Address + + + Use the following code to verify your email address + + {otp} + + This code is valid for 10 minutes + + + Thank you for joining us + +
+
+
+ ) +} + +OTPEmail.PreviewProps = { otp: 123456 } +``` + +`@react-email/components` → email-client compatible (Gmail, Outlook). Tailwind support. + +`PreviewProps` → playground only. + +## Preview +```bash +bun email +``` + +Opens browser with preview. + +## Send Email +Render with `react-dom/server`, submit via provider: + +### Nodemailer +```typescript +import { renderToStaticMarkup } from 'react-dom/server' +import OTPEmail from './emails/otp' +import nodemailer from 'nodemailer' + +const transporter = nodemailer.createTransport({ + host: 'smtp.gehenna.sh', + port: 465, + auth: { user: 'makoto', pass: '12345678' } +}) + +.get('/otp', async ({ body }) => { + const otp = ~~(Math.random() * 900_000) + 100_000 + const html = renderToStaticMarkup() + + await transporter.sendMail({ + from: '[email protected]', + to: body, + subject: 'Verify your email address', + html + }) + + return { success: true } +}, { + body: t.String({ format: 'email' }) +}) +``` + +### Resend +```typescript +import OTPEmail from './emails/otp' +import Resend from 'resend' + +const resend = new Resend('re_123456789') + +.get('/otp', ({ body }) => { + const otp = ~~(Math.random() * 900_000) + 100_000 + + await resend.emails.send({ + from: '[email protected]', + to: body, + subject: 'Verify your email address', + html: // Direct JSX + }) + + return { success: true } +}) +``` + +Direct JSX import thanks to Bun. + +Other providers: AWS SES, SendGrid. + +See [React Email Integrations](https://react.email/docs/integrations/overview). diff --git a/.agents/skills/elysiajs/integrations/sveltekit.md b/.agents/skills/elysiajs/integrations/sveltekit.md new file mode 100644 index 00000000..4ad306ac --- /dev/null +++ b/.agents/skills/elysiajs/integrations/sveltekit.md @@ -0,0 +1,53 @@ + +# SvelteKit Integration + +## What It Is +Run Elysia on SvelteKit server routes. + +## Setup +1. Create `src/routes/[...slugs]/+server.ts` +2. Define Elysia server +3. Export fallback handler: +```typescript +// src/routes/[...slugs]/+server.ts +import { Elysia, t } from 'elysia' + +const app = new Elysia() + .get('/', 'hello SvelteKit') + .post('/', ({ body }) => body, { + body: t.Object({ name: t.String() }) + }) + +interface WithRequest { + request: Request +} + +export const fallback = ({ request }: WithRequest) => app.handle(request) +``` + +Treat as normal SvelteKit server route. + +## Prefix for Non-Root +If placed in `src/routes/api/[...slugs]/+server.ts`, set prefix: +```typescript +// src/routes/api/[...slugs]/+server.ts +import { Elysia, t } from 'elysia' + +const app = new Elysia({ prefix: '/api' }) + .get('/', () => 'hi') + .post('/', ({ body }) => body, { + body: t.Object({ name: t.String() }) + }) + +type RequestHandler = (v: { request: Request }) => Response | Promise + +export const fallback: RequestHandler = ({ request }) => app.handle(request) +``` + +Ensures routing works in any location. + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/tanstack-start.md b/.agents/skills/elysiajs/integrations/tanstack-start.md new file mode 100644 index 00000000..2a1e642c --- /dev/null +++ b/.agents/skills/elysiajs/integrations/tanstack-start.md @@ -0,0 +1,87 @@ +# Tanstack Start Integration + +## What It Is +Elysia runs inside Tanstack Start server routes. + +## Setup +1. Create `src/routes/api.$.ts` +2. Define Elysia server +3. Export handlers in `server.handlers`: +```typescript +// src/routes/api.$.ts +import { Elysia } from 'elysia' +import { createFileRoute } from '@tanstack/react-router' +import { createIsomorphicFn } from '@tanstack/react-start' + +const app = new Elysia({ + prefix: '/api' +}).get('/', 'Hello Elysia!') + +const handle = ({ request }: { request: Request }) => app.fetch(request) + +export const Route = createFileRoute('/api/$')({ + server: { + handlers: { + GET: handle, + POST: handle + } + } +}) +``` + +Runs on `/api`. Add methods to `server.handlers` as needed. + +## Eden (End-to-End Type Safety) +Isomorphic pattern with `createIsomorphicFn`: +```typescript +// src/routes/api.$.ts +export const getTreaty = createIsomorphicFn() + .server(() => treaty(app).api) + .client(() => treaty('localhost:3000').api) +``` + +- Server: Direct call (no HTTP overhead) +- Client: HTTP call + +## Loader Data +Fetch before render: +```tsx +// src/routes/index.tsx +import { createFileRoute } from '@tanstack/react-router' +import { getTreaty } from './api.$' + +export const Route = createFileRoute('/a')({ + component: App, + loader: () => getTreaty().get().then((res) => res.data) +}) + +function App() { + const data = Route.useLoaderData() + return data +} +``` + +Executed server-side during SSR. No HTTP overhead. Type-safe. + +## React Query +```tsx +import { useQuery } from '@tanstack/react-query' +import { getTreaty } from './api.$' + +function App() { + const { data: response } = useQuery({ + queryKey: ['get'], + queryFn: () => getTreaty().get() + }) + + return response?.data +} +``` + +Works with all React Query features. + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` diff --git a/.agents/skills/elysiajs/integrations/vercel.md b/.agents/skills/elysiajs/integrations/vercel.md new file mode 100644 index 00000000..555ec8ee --- /dev/null +++ b/.agents/skills/elysiajs/integrations/vercel.md @@ -0,0 +1,55 @@ +# Vercel Integration +Deploy Elysia on Vercel + +## What It Is +Zero-config deployment on Vercel (Bun or Node runtime). + +## Setup +1. Create/import Elysia server in `src/index.ts` +2. Export as default: +```typescript +import { Elysia, t } from 'elysia' + +export default new Elysia() + .get('/', () => 'Hello Vercel Function') + .post('/', ({ body }) => body, { + body: t.Object({ name: t.String() }) + }) +``` + +3. Develop locally: +```bash +vc dev +``` + +4. Deploy: +```bash +vc deploy +``` + +## Node.js Runtime +Set in `package.json`: +```json +{ + "name": "elysia-app", + "type": "module" +} +``` + +## Bun Runtime +Set in `vercel.json`: +```json +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "bunVersion": "1.x" +} +``` + +## pnpm +Manual install: +```bash +pnpm add @sinclair/typebox openapi-types +``` + +## Troubleshooting +Vercel has zero config for Elysia. For additional config, see [Vercel docs](https://vercel.com/docs/frameworks/backend/elysia). diff --git a/.agents/skills/elysiajs/patterns/mvc.md b/.agents/skills/elysiajs/patterns/mvc.md new file mode 100644 index 00000000..dc227c63 --- /dev/null +++ b/.agents/skills/elysiajs/patterns/mvc.md @@ -0,0 +1,380 @@ +# MVC pattern +This file contains a guideline for using Elysia with MVC or Model View Controller patterns + +- Controller: + - Prefers Elysia as a controller for HTTP dependant + - For non HTTP dependent, prefers service instead unless explicitly asked + - Use `onError` to handle local custom errors + - Register Model to Elysia instance via `Elysia.models({ ...models })` and prefix model by namespace `Elysia.prefix('model', 'Namespace.') + - Prefers Reference Model by name provided by Elysia instead of using an actual `Model.name` +- Service: + - Prefers class (or abstract class if possible) + - Prefers interface/type derive from `Model` + - Return `status` (`import { status } from 'elysia'`) for error + - Prefers `return Error` instead of `throw Error` +- Models: + - Always export validation model and type of validation model + - Custom Error should be in contains in Model + +## Controller +Due to type soundness of Elysia, it's not recommended to use a traditional controller class that is tightly coupled with Elysia's `Context` because: + +1. **Elysia type is complex** and heavily depends on plugin and multiple level of chaining. +2. **Hard to type**, Elysia type could change at anytime, especially with decorators, and store +3. **Loss of type integrity**, and inconsistency between types and runtime code. + +We recommended one of the following approach to implement a controller in Elysia. +1. Use Elysia instance as a controller itself +2. Create a controller that is not tied with HTTP request or Elysia. + +--- + +### 1. Elysia instance as a controller +> 1 Elysia instance = 1 controller + +Treat an Elysia instance as a controller, and define your routes directly on the Elysia instance. + +```typescript +// Do +import { Elysia } from 'elysia' +import { Service } from './service' + +new Elysia() + .get('/', ({ stuff }) => { + Service.doStuff(stuff) + }) +``` + +This approach allows Elysia to infer the `Context` type automatically, ensuring type integrity and consistency between types and runtime code. + +```typescript +// Don't +import { Elysia, t, type Context } from 'elysia' + +abstract class Controller { + static root(context: Context) { + return Service.doStuff(context.stuff) + } +} + +new Elysia() + .get('/', Controller.root) +``` + +This approach makes it hard to type `Context` properly, and may lead to loss of type integrity. + +### 2. Controller without HTTP request +If you want to create a controller class, we recommend creating a class that is not tied to HTTP request or Elysia at all. + +This approach allows you to decouple the controller from Elysia, making it easier to test, reuse, and even swap a framework while still follows the MVC pattern. + +```typescript +import { Elysia } from 'elysia' + +abstract class Controller { + static doStuff(stuff: string) { + return Service.doStuff(stuff) + } +} + +new Elysia() + .get('/', ({ stuff }) => Controller.doStuff(stuff)) +``` + +Tying the controller to Elysia Context may lead to: +1. Loss of type integrity +2. Make it harder to test and reuse +3. Lead to vendor lock-in + +We recommended to keep the controller decoupled from Elysia as much as possible. + +### Don't: Pass entire `Context` to a controller +**Context is a highly dynamic type** that can be inferred from Elysia instance. + +Do not pass an entire `Context` to a controller, instead use object destructuring to extract what you need and pass it to the controller. + +```typescript +import type { Context } from 'elysia' + +abstract class Controller { + constructor() {} + + // Don't do this + static root(context: Context) { + return Service.doStuff(context.stuff) + } +} +``` + +This approach makes it hard to type `Context` properly, and may lead to loss of type integrity. + +### Testing +If you're using Elysia as a controller, you can test your controller using `handle` to directly call a function (and it's lifecycle) + +```typescript +import { Elysia } from 'elysia' +import { Service } from './service' + +import { describe, it, expect } from 'bun:test' + +const app = new Elysia() + .get('/', ({ stuff }) => { + Service.doStuff(stuff) + + return 'ok' + }) + +describe('Controller', () => { + it('should work', async () => { + const response = await app + .handle(new Request('http://localhost/')) + .then((x) => x.text()) + + expect(response).toBe('ok') + }) +}) +``` + +You may find more information about testing in [Unit Test](/patterns/unit-test.html). + +## Service +Service is a set of utility/helper functions decoupled as a business logic to use in a module/controller, in our case, an Elysia instance. + +Any technical logic that can be decoupled from controller may live inside a **Service**. + +There are 2 types of service in Elysia: +1. Non-request dependent service +2. Request dependent service + +### 1. Abstract away Non-request dependent service + +We recommend abstracting a service class/function away from Elysia. + +If the service or function isn't tied to an HTTP request or doesn't access a `Context`, it's recommended to implement it as a static class or function. + +```typescript +import { Elysia, t } from 'elysia' + +abstract class Service { + static fibo(number: number): number { + if(number < 2) + return number + + return Service.fibo(number - 1) + Service.fibo(number - 2) + } +} + +new Elysia() + .get('/fibo', ({ body }) => { + return Service.fibo(body) + }, { + body: t.Numeric() + }) +``` + +If your service doesn't need to store a property, you may use `abstract class` and `static` instead to avoid allocating class instance. + +### 2. Request dependent service as Elysia instance + +**If the service is a request-dependent service** or needs to process HTTP requests, we recommend abstracting it as an Elysia instance to ensure type integrity and inference: + +```typescript +import { Elysia } from 'elysia' + +// Do +const AuthService = new Elysia({ name: 'Auth.Service' }) + .macro({ + isSignIn: { + resolve({ cookie, status }) { + if (!cookie.session.value) return status(401) + + return { + session: cookie.session.value, + } + } + } + }) + +const UserController = new Elysia() + .use(AuthService) + .get('/profile', ({ Auth: { user } }) => user, { + isSignIn: true + }) +``` + +### Do: Decorate only request dependent property + +It's recommended to `decorate` only request-dependent properties, such as `requestIP`, `requestTime`, or `session`. + +Overusing decorators may tie your code to Elysia, making it harder to test and reuse. + +```typescript +import { Elysia } from 'elysia' + +new Elysia() + .decorate('requestIP', ({ request }) => request.headers.get('x-forwarded-for') || request.ip) + .decorate('requestTime', () => Date.now()) + .decorate('session', ({ cookie }) => cookie.session.value) + .get('/', ({ requestIP, requestTime, session }) => { + return { requestIP, requestTime, session } + }) +``` + +### Don't: Pass entire `Context` to a service +**Context is a highly dynamic type** that can be inferred from Elysia instance. + +Do not pass an entire `Context` to a service, instead use object destructuring to extract what you need and pass it to the service. +```typescript +import type { Context } from 'elysia' + +class AuthService { + constructor() {} + + // Don't do this + isSignIn({ status, cookie: { session } }: Context) { + if (session.value) + return status(401) + } +} +``` + +As Elysia type is complex, and heavily depends on plugin and multiple level of chaining, it can be challenging to manually type as it's highly dynamic. + +## Model +Model or [DTO (Data Transfer Object)](https://en.wikipedia.org/wiki/Data_transfer_object) is handle by [Elysia.t (Validation)](/essential/validation.html#elysia-type). + +Elysia has a validation system built-in which can infers type from your code and validate it at runtime. + +### Do: Use Elysia's validation system + +Elysia strength is prioritizing a single source of truth for both type and runtime validation. + +Instead of declaring an interface, reuse validation's model instead: +```typescript twoslash +// Do +import { Elysia, t } from 'elysia' + +const customBody = t.Object({ + username: t.String(), + password: t.String() +}) + +// Optional if you want to get the type of the model +// Usually if we didn't use the type, as it's already inferred by Elysia +type CustomBody = typeof customBody.static + +export { customBody } +``` + +We can get type of model by using `typeof` with `.static` property from the model. + +Then you can use the `CustomBody` type to infer the type of the request body. + +```typescript twoslash +// Do +new Elysia() + .post('/login', ({ body }) => { + return body + }, { + body: customBody + }) +``` + +### Don't: Declare a class instance as a model + +Do not declare a class instance as a model: +```typescript +// Don't +class CustomBody { + username: string + password: string + + constructor(username: string, password: string) { + this.username = username + this.password = password + } +} + +// Don't +interface ICustomBody { + username: string + password: string +} +``` + +### Don't: Declare type separate from the model +Do not declare a type separate from the model, instead use `typeof` with `.static` property to get the type of the model. + +```typescript +// Don't +import { Elysia, t } from 'elysia' + +const customBody = t.Object({ + username: t.String(), + password: t.String() +}) + +type CustomBody = { + username: string + password: string +} + +// Do +const customBody = t.Object({ + username: t.String(), + password: t.String() +}) + +type CustomBody = typeof customBody.static +``` + +### Group +You can group multiple models into a single object to make it more organized. + +```typescript +import { Elysia, t } from 'elysia' + +export const AuthModel = { + sign: t.Object({ + username: t.String(), + password: t.String() + }) +} + +const models = AuthModel.models +``` + +### Model Injection +Though this is optional, if you are strictly following MVC pattern, you may want to inject like a service into a controller. We recommended using Elysia reference model + +Using Elysia's model reference +```typescript twoslash +import { Elysia, t } from 'elysia' + +const customBody = t.Object({ + username: t.String(), + password: t.String() +}) + +const AuthModel = new Elysia() + .model({ + sign: customBody + }) + +const models = AuthModel.models + +const UserController = new Elysia({ prefix: '/auth' }) + .use(AuthModel) + .prefix('model', 'auth.') + .post('/sign-in', async ({ body, cookie: { session } }) => { + return true + }, { + body: 'auth.Sign' + }) +``` + +This approach provide several benefits: +1. Allow us to name a model and provide auto-completion. +2. Modify schema for later usage, or perform a [remap](/essential/handler.html#remap). +3. Show up as "models" in OpenAPI compliance client, eg. OpenAPI. +4. Improve TypeScript inference speed as model type will be cached during registration. diff --git a/.agents/skills/elysiajs/plugins/bearer.md b/.agents/skills/elysiajs/plugins/bearer.md new file mode 100644 index 00000000..df529e5a --- /dev/null +++ b/.agents/skills/elysiajs/plugins/bearer.md @@ -0,0 +1,30 @@ +# Bearer +Plugin for Elysia for retrieving the Bearer token. + +## Installation +```bash +bun add @elysiajs/bearer +``` + +## Basic Usage +```typescript twoslash +import { Elysia } from 'elysia' +import { bearer } from '@elysiajs/bearer' + +const app = new Elysia() + .use(bearer()) + .get('/sign', ({ bearer }) => bearer, { + beforeHandle({ bearer, set, status }) { + if (!bearer) { + set.headers[ + 'WWW-Authenticate' + ] = `Bearer realm='sign', error="invalid_request"` + + return status(400, 'Unauthorized') + } + } + }) + .listen(3000) +``` + +This plugin is for retrieving a Bearer token specified in RFC6750 diff --git a/.agents/skills/elysiajs/plugins/cors.md b/.agents/skills/elysiajs/plugins/cors.md new file mode 100644 index 00000000..2d8db2a5 --- /dev/null +++ b/.agents/skills/elysiajs/plugins/cors.md @@ -0,0 +1,141 @@ +# CORS + +Plugin for Elysia that adds support for customizing Cross-Origin Resource Sharing behavior. + +## Installation +```bash +bun add @elysiajs/cors +``` + +## Basic Usage +```typescript twoslash +import { Elysia } from 'elysia' +import { cors } from '@elysiajs/cors' + +new Elysia().use(cors()).listen(3000) +``` + +This will set Elysia to accept requests from any origin. + +## Config + +Below is a config which is accepted by the plugin + +### origin + +@default `true` + +Indicates whether the response can be shared with the requesting code from the given origins. + +Value can be one of the following: + +- **string** - Name of origin which will directly assign to Access-Control-Allow-Origin header. +- **boolean** - If set to true, Access-Control-Allow-Origin will be set to `*` (any origins) +- **RegExp** - Pattern to match request's URL, allowed if matched. +- **Function** - Custom logic to allow resource sharing, allow if `true` is returned. + - Expected to have the type of: + ```typescript + cors(context: Context) => boolean | void + ``` +- **Array** - iterate through all cases above in order, allowed if any of the values are `true`. + +--- + +### methods + +@default `*` + +Allowed methods for cross-origin requests by assign `Access-Control-Allow-Methods` header. + +Value can be one of the following: +- **undefined | null | ''** - Ignore all methods. +- **\*** - Allows all methods. +- **string** - Expects either a single method or a comma-delimited string + - (eg: `'GET, PUT, POST'`) +- **string[]** - Allow multiple HTTP methods. + - eg: `['GET', 'PUT', 'POST']` + +--- + +### allowedHeaders + +@default `*` + +Allowed headers for an incoming request by assign `Access-Control-Allow-Headers` header. + +Value can be one of the following: +- **string** - Expects either a single header or a comma-delimited string + - eg: `'Content-Type, Authorization'`. +- **string[]** - Allow multiple HTTP headers. + - eg: `['Content-Type', 'Authorization']` + +--- + +### exposeHeaders + +@default `*` + +Response CORS with specified headers by sssign Access-Control-Expose-Headers header. + +Value can be one of the following: +- **string** - Expects either a single header or a comma-delimited string. + - eg: `'Content-Type, X-Powered-By'`. +- **string[]** - Allow multiple HTTP headers. + - eg: `['Content-Type', 'X-Powered-By']` + +--- + +### credentials + +@default `true` + +The Access-Control-Allow-Credentials response header tells browsers whether to expose the response to the frontend JavaScript code when the request's credentials mode Request.credentials is `include`. + +Credentials are cookies, authorization headers, or TLS client certificates by assign `Access-Control-Allow-Credentials` header. + +--- + +### maxAge + +@default `5` + +Indicates how long the results of a preflight request that is the information contained in the `Access-Control-Allow-Methods` and `Access-Control-Allow-Headers` headers) can be cached. + +Assign `Access-Control-Max-Age` header. + +--- + +### preflight + +The preflight request is a request sent to check if the CORS protocol is understood and if a server is aware of using specific methods and headers. + +Response with **OPTIONS** request with 3 HTTP request headers: +- **Access-Control-Request-Method** +- **Access-Control-Request-Headers** +- **Origin** + +This config indicates if the server should respond to preflight requests. + +--- + +## Pattern + +Below you can find the common patterns to use the plugin. + +## Allow CORS by top-level domain + +```typescript twoslash +import { Elysia } from 'elysia' +import { cors } from '@elysiajs/cors' + +const app = new Elysia() + .use( + cors({ + origin: /.*\.saltyaom\.com$/ + }) + ) + .get('/', () => 'Hi') + .listen(3000) +``` + +This will allow requests from top-level domains with `saltyaom.com` diff --git a/.agents/skills/elysiajs/plugins/cron.md b/.agents/skills/elysiajs/plugins/cron.md new file mode 100644 index 00000000..3905ad5b --- /dev/null +++ b/.agents/skills/elysiajs/plugins/cron.md @@ -0,0 +1,265 @@ +# Cron Plugin + +This plugin adds support for running cronjob to Elysia server. + +## Installation + +```bash +bun add @elysiajs/cron +``` + +## Basic Usage +```typescript twoslash +import { Elysia } from 'elysia' +import { cron } from '@elysiajs/cron' + +new Elysia() + .use( + cron({ + name: 'heartbeat', + pattern: '*/10 * * * * *', + run() { + console.log('Heartbeat') + } + }) + ) + .listen(3000) +``` + +The above code will log `heartbeat` every 10 seconds. + +## Config +Below is a config which is accepted by the plugin + +### cron + +Create a cronjob for the Elysia server. + +``` +cron(config: CronConfig, callback: (Instance['store']) => void): this +``` + +`CronConfig` accepts the parameters specified below: + +--- + +### CronConfig.name + +Job name to register to `store`. + +This will register the cron instance to `store` with a specified name, which can be used to reference in later processes eg. stop the job. + +--- + +### CronConfig.pattern + +Time to run the job as specified by cron syntax. + +``` +┌────────────── second (optional) +│ ┌──────────── minute +│ │ ┌────────── hour +│ │ │ ┌──────── day of the month +│ │ │ │ ┌────── month +│ │ │ │ │ ┌──── day of week +│ │ │ │ │ │ +* * * * * * +``` + +--- + +### CronConfig.timezone +Time zone in Europe/Stockholm format + +--- + +### CronConfig.startAt +Schedule start time for the job + +--- + +### CronConfig.stopAt +Schedule stop time for the job + +--- + +### CronConfig.maxRuns +Maximum number of executions + +--- + +### CronConfig.catch +Continue execution even if an unhandled error is thrown by a triggered function. + +### CronConfig.interval +The minimum interval between executions, in seconds. + +--- + +## CronConfig.Pattern +Below you can find the common patterns to use the plugin. + +--- + +## Pattern + +Below you can find the common patterns to use the plugin. + +## Stop cronjob + +You can stop cronjob manually by accessing the cronjob name registered to `store`. + +```typescript +import { Elysia } from 'elysia' +import { cron } from '@elysiajs/cron' + +const app = new Elysia() + .use( + cron({ + name: 'heartbeat', + pattern: '*/1 * * * * *', + run() { + console.log('Heartbeat') + } + }) + ) + .get( + '/stop', + ({ + store: { + cron: { heartbeat } + } + }) => { + heartbeat.stop() + + return 'Stop heartbeat' + } + ) + .listen(3000) +``` + +--- + +## Predefined patterns + +You can use predefined patterns from `@elysiajs/cron/schedule` + +```typescript +import { Elysia } from 'elysia' +import { cron, Patterns } from '@elysiajs/cron' + +const app = new Elysia() + .use( + cron({ + name: 'heartbeat', + pattern: Patterns.everySecond(), + run() { + console.log('Heartbeat') + } + }) + ) + .get( + '/stop', + ({ + store: { + cron: { heartbeat } + } + }) => { + heartbeat.stop() + + return 'Stop heartbeat' + } + ) + .listen(3000) +``` + +### Functions + +| Function | Description | +| ---------------------------------------- | ----------------------------------------------------- | +| `.everySeconds(2)` | Run the task every 2 seconds | +| `.everyMinutes(5)` | Run the task every 5 minutes | +| `.everyHours(3)` | Run the task every 3 hours | +| `.everyHoursAt(3, 15)` | Run the task every 3 hours at 15 minutes | +| `.everyDayAt('04:19')` | Run the task every day at 04:19 | +| `.everyWeekOn(Patterns.MONDAY, '19:30')` | Run the task every Monday at 19:30 | +| `.everyWeekdayAt('17:00')` | Run the task every day from Monday to Friday at 17:00 | +| `.everyWeekendAt('11:00')` | Run the task on Saturday and Sunday at 11:00 | + +### Function aliases to constants + +| Function | Constant | +| ----------------- | ---------------------------------- | +| `.everySecond()` | EVERY_SECOND | +| `.everyMinute()` | EVERY_MINUTE | +| `.hourly()` | EVERY_HOUR | +| `.daily()` | EVERY_DAY_AT_MIDNIGHT | +| `.everyWeekday()` | EVERY_WEEKDAY | +| `.everyWeekend()` | EVERY_WEEKEND | +| `.weekly()` | EVERY_WEEK | +| `.monthly()` | EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT | +| `.everyQuarter()` | EVERY_QUARTER | +| `.yearly()` | EVERY_YEAR | + +### Constants + +| Constant | Pattern | +| ---------------------------------------- | -------------------- | +| `.EVERY_SECOND` | `* * * * * *` | +| `.EVERY_5_SECONDS` | `*/5 * * * * *` | +| `.EVERY_10_SECONDS` | `*/10 * * * * *` | +| `.EVERY_30_SECONDS` | `*/30 * * * * *` | +| `.EVERY_MINUTE` | `*/1 * * * *` | +| `.EVERY_5_MINUTES` | `0 */5 * * * *` | +| `.EVERY_10_MINUTES` | `0 */10 * * * *` | +| `.EVERY_30_MINUTES` | `0 */30 * * * *` | +| `.EVERY_HOUR` | `0 0-23/1 * * *` | +| `.EVERY_2_HOURS` | `0 0-23/2 * * *` | +| `.EVERY_3_HOURS` | `0 0-23/3 * * *` | +| `.EVERY_4_HOURS` | `0 0-23/4 * * *` | +| `.EVERY_5_HOURS` | `0 0-23/5 * * *` | +| `.EVERY_6_HOURS` | `0 0-23/6 * * *` | +| `.EVERY_7_HOURS` | `0 0-23/7 * * *` | +| `.EVERY_8_HOURS` | `0 0-23/8 * * *` | +| `.EVERY_9_HOURS` | `0 0-23/9 * * *` | +| `.EVERY_10_HOURS` | `0 0-23/10 * * *` | +| `.EVERY_11_HOURS` | `0 0-23/11 * * *` | +| `.EVERY_12_HOURS` | `0 0-23/12 * * *` | +| `.EVERY_DAY_AT_1AM` | `0 01 * * *` | +| `.EVERY_DAY_AT_2AM` | `0 02 * * *` | +| `.EVERY_DAY_AT_3AM` | `0 03 * * *` | +| `.EVERY_DAY_AT_4AM` | `0 04 * * *` | +| `.EVERY_DAY_AT_5AM` | `0 05 * * *` | +| `.EVERY_DAY_AT_6AM` | `0 06 * * *` | +| `.EVERY_DAY_AT_7AM` | `0 07 * * *` | +| `.EVERY_DAY_AT_8AM` | `0 08 * * *` | +| `.EVERY_DAY_AT_9AM` | `0 09 * * *` | +| `.EVERY_DAY_AT_10AM` | `0 10 * * *` | +| `.EVERY_DAY_AT_11AM` | `0 11 * * *` | +| `.EVERY_DAY_AT_NOON` | `0 12 * * *` | +| `.EVERY_DAY_AT_1PM` | `0 13 * * *` | +| `.EVERY_DAY_AT_2PM` | `0 14 * * *` | +| `.EVERY_DAY_AT_3PM` | `0 15 * * *` | +| `.EVERY_DAY_AT_4PM` | `0 16 * * *` | +| `.EVERY_DAY_AT_5PM` | `0 17 * * *` | +| `.EVERY_DAY_AT_6PM` | `0 18 * * *` | +| `.EVERY_DAY_AT_7PM` | `0 19 * * *` | +| `.EVERY_DAY_AT_8PM` | `0 20 * * *` | +| `.EVERY_DAY_AT_9PM` | `0 21 * * *` | +| `.EVERY_DAY_AT_10PM` | `0 22 * * *` | +| `.EVERY_DAY_AT_11PM` | `0 23 * * *` | +| `.EVERY_DAY_AT_MIDNIGHT` | `0 0 * * *` | +| `.EVERY_WEEK` | `0 0 * * 0` | +| `.EVERY_WEEKDAY` | `0 0 * * 1-5` | +| `.EVERY_WEEKEND` | `0 0 * * 6,0` | +| `.EVERY_1ST_DAY_OF_MONTH_AT_MIDNIGHT` | `0 0 1 * *` | +| `.EVERY_1ST_DAY_OF_MONTH_AT_NOON` | `0 12 1 * *` | +| `.EVERY_2ND_HOUR` | `0 */2 * * *` | +| `.EVERY_2ND_HOUR_FROM_1AM_THROUGH_11PM` | `0 1-23/2 * * *` | +| `.EVERY_2ND_MONTH` | `0 0 1 */2 *` | +| `.EVERY_QUARTER` | `0 0 1 */3 *` | +| `.EVERY_6_MONTHS` | `0 0 1 */6 *` | +| `.EVERY_YEAR` | `0 0 1 1 *` | +| `.EVERY_30_MINUTES_BETWEEN_9AM_AND_5PM` | `0 */30 9-17 * * *` | +| `.EVERY_30_MINUTES_BETWEEN_9AM_AND_6PM` | `0 */30 9-18 * * *` | +| `.EVERY_30_MINUTES_BETWEEN_10AM_AND_7PM` | `0 */30 10-19 * * *` | diff --git a/.agents/skills/elysiajs/plugins/graphql-apollo.md b/.agents/skills/elysiajs/plugins/graphql-apollo.md new file mode 100644 index 00000000..655f258b --- /dev/null +++ b/.agents/skills/elysiajs/plugins/graphql-apollo.md @@ -0,0 +1,90 @@ +# GraphQL Apollo + +Plugin for Elysia to use GraphQL Apollo. + +## Installation +```bash +bun add graphql @elysiajs/apollo @apollo/server +``` + +## Basic Usage + +```typescript +import { Elysia } from 'elysia' +import { apollo, gql } from '@elysiajs/apollo' + +const app = new Elysia() + .use( + apollo({ + typeDefs: gql` + type Book { + title: String + author: String + } + + type Query { + books: [Book] + } + `, + resolvers: { + Query: { + books: () => { + return [ + { + title: 'Elysia', + author: 'saltyAom' + } + ] + } + } + } + }) + ) + .listen(3000) +``` + +Accessing `/graphql` should show Apollo GraphQL playground work with. + +## Context + +Because Elysia is based on Web Standard Request and Response which is different from Node's `HttpRequest` and `HttpResponse` that Express uses, results in `req, res` being undefined in context. + +Because of this, Elysia replaces both with `context` like route parameters. + +```typescript +const app = new Elysia() + .use( + apollo({ + typeDefs, + resolvers, + context: async ({ request }) => { + const authorization = request.headers.get('Authorization') + + return { + authorization + } + } + }) + ) + .listen(3000) +``` + +## Config + +This plugin extends Apollo's [ServerRegistration](https://www.apollographql.com/docs/apollo-server/api/apollo-server/#options) (which is `ApolloServer`'s' constructor parameter). + +Below are the extended parameters for configuring Apollo Server with Elysia. + +### path + +@default `"/graphql"` + +Path to expose Apollo Server. + +--- + +### enablePlayground + +@default `process.env.ENV !== 'production'` + +Determine whether should Apollo should provide Apollo Playground. diff --git a/.agents/skills/elysiajs/plugins/graphql-yoga.md b/.agents/skills/elysiajs/plugins/graphql-yoga.md new file mode 100644 index 00000000..3203d028 --- /dev/null +++ b/.agents/skills/elysiajs/plugins/graphql-yoga.md @@ -0,0 +1,87 @@ +# GraphQL Yoga + +This plugin integrates GraphQL yoga with Elysia + +## Installation +```bash +bun add @elysiajs/graphql-yoga +``` + +## Basic Usage +```typescript +import { Elysia } from 'elysia' +import { yoga } from '@elysiajs/graphql-yoga' + +const app = new Elysia() + .use( + yoga({ + typeDefs: /* GraphQL */ ` + type Query { + hi: String + } + `, + resolvers: { + Query: { + hi: () => 'Hello from Elysia' + } + } + }) + ) + .listen(3000) +``` + +Accessing `/graphql` in the browser (GET request) would show you a GraphiQL instance for the GraphQL-enabled Elysia server. + +optional: you can install a custom version of optional peer dependencies as well: + +```bash +bun add graphql graphql-yoga +``` + +## Resolver + +Elysia uses Mobius to infer type from **typeDefs** field automatically, allowing you to get full type-safety and auto-complete when typing **resolver** types. + +## Context + +You can add custom context to the resolver function by adding **context** + +```ts +import { Elysia } from 'elysia' +import { yoga } from '@elysiajs/graphql-yoga' + +const app = new Elysia() + .use( + yoga({ + typeDefs: /* GraphQL */ ` + type Query { + hi: String + } + `, + context: { + name: 'Mobius' + }, + // If context is a function on this doesn't present + // for some reason it won't infer context type + useContext(_) {}, + resolvers: { + Query: { + hi: async (parent, args, context) => context.name + } + } + }) + ) + .listen(3000) +``` + +## Config + +This plugin extends [GraphQL Yoga's createYoga options, please refer to the GraphQL Yoga documentation](https://the-guild.dev/graphql/yoga-server/docs) with inlining `schema` config to root. + +Below is a config which is accepted by the plugin + +### path + +@default `/graphql` + +Endpoint to expose GraphQL handler diff --git a/.agents/skills/elysiajs/plugins/html.md b/.agents/skills/elysiajs/plugins/html.md new file mode 100644 index 00000000..777a536e --- /dev/null +++ b/.agents/skills/elysiajs/plugins/html.md @@ -0,0 +1,188 @@ +# HTML + +Allows you to use JSX and HTML with proper headers and support. + +## Installation + +```bash +bun add @elysiajs/html +``` + +## Basic Usage +```tsx twoslash +import React from 'react' +import { Elysia } from 'elysia' +import { html, Html } from '@elysiajs/html' + +new Elysia() + .use(html()) + .get( + '/html', + () => ` + + + Hello World + + +

Hello World

+ + ` + ) + .get('/jsx', () => ( + + + Hello World + + +

Hello World

+ + + )) + .listen(3000) +``` + +This plugin will automatically add `Content-Type: text/html; charset=utf8` header to the response, add ``, and convert it into a Response object. + +## JSX +Elysia can use JSX + +1. Replace your file that needs to use JSX to end with affix **"x"**: +- .js -> .jsx +- .ts -> .tsx + +2. Register the TypeScript type by append the following to **tsconfig.json**: +```jsonc +// tsconfig.json +{ + "compilerOptions": { + "jsx": "react", + "jsxFactory": "Html.createElement", + "jsxFragmentFactory": "Html.Fragment" + } +} +``` + +3. Starts using JSX in your file +```tsx twoslash +import React from 'react' +import { Elysia } from 'elysia' +import { html, Html } from '@elysiajs/html' + +new Elysia() + .use(html()) + .get('/', () => ( + + + Hello World + + +

Hello World

+ + + )) + .listen(3000) +``` + +If the error `Cannot find name 'Html'. Did you mean 'html'?` occurs, this import must be added to the JSX template: + +```tsx +import { Html } from '@elysiajs/html' +``` + +It is important that it is written in uppercase. + +## XSS + +Elysia HTML is based use of the Kita HTML plugin to detect possible XSS attacks in compile time. + +You can use a dedicated `safe` attribute to sanitize user value to prevent XSS vulnerability. + +```tsx +import { Elysia, t } from 'elysia' +import { html, Html } from '@elysiajs/html' + +new Elysia() + .use(html()) + .post( + '/', + ({ body }) => ( + + + Hello World + + +

{body}

+ + + ), + { + body: t.String() + } + ) + .listen(3000) +``` + +However, when are building a large-scale app, it's best to have a type reminder to detect possible XSS vulnerabilities in your codebase. + +To add a type-safe reminder, please install: + +```sh +bun add @kitajs/ts-html-plugin +``` + +Then appends the following **tsconfig.json** + +```jsonc +// tsconfig.json +{ + "compilerOptions": { + "jsx": "react", + "jsxFactory": "Html.createElement", + "jsxFragmentFactory": "Html.Fragment", + "plugins": [{ "name": "@kitajs/ts-html-plugin" }] + } +} +``` + +## Config +Below is a config which is accepted by the plugin + +### contentType + +- Type: `string` +- Default: `'text/html; charset=utf8'` + +The content-type of the response. + +### autoDetect + +- Type: `boolean` +- Default: `true` + +Whether to automatically detect HTML content and set the content-type. + +### autoDoctype + +- Type: `boolean | 'full'` +- Default: `true` + +Whether to automatically add `` to a response starting with ``, if not found. + +Use `full` to also automatically add doctypes on responses returned without this plugin + +```ts +// without the plugin +app.get('/', () => '') + +// With the plugin +app.get('/', ({ html }) => html('')) +``` + +### isHtml + +- Type: `(value: string) => boolean` +- Default: `isHtml` (exported function) + +The function is used to detect if a string is a html or not. Default implementation if length is greater than 7, starts with `<` and ends with `>`. + +Keep in mind there's no real way to validate HTML, so the default implementation is a best guess. diff --git a/.agents/skills/elysiajs/plugins/jwt.md b/.agents/skills/elysiajs/plugins/jwt.md new file mode 100644 index 00000000..b5767bf2 --- /dev/null +++ b/.agents/skills/elysiajs/plugins/jwt.md @@ -0,0 +1,197 @@ +# JWT Plugin +This plugin adds support for using JWT in Elysia handlers. + +## Installation +```bash +bun add @elysiajs/jwt +``` + +## Basic Usage +```typescript [cookie] +import { Elysia } from 'elysia' +import { jwt } from '@elysiajs/jwt' + +const app = new Elysia() + .use( + jwt({ + name: 'jwt', + secret: 'Fischl von Luftschloss Narfidort' + }) + ) + .get('/sign/:name', async ({ jwt, params: { name }, cookie: { auth } }) => { + const value = await jwt.sign({ name }) + + auth.set({ + value, + httpOnly: true, + maxAge: 7 * 86400, + path: '/profile', + }) + + return `Sign in as ${value}` + }) + .get('/profile', async ({ jwt, status, cookie: { auth } }) => { + const profile = await jwt.verify(auth.value) + + if (!profile) + return status(401, 'Unauthorized') + + return `Hello ${profile.name}` + }) + .listen(3000) +``` + +## Config +This plugin extends config from [jose](https://github.com/panva/jose). + +Below is a config that is accepted by the plugin. + +### name +Name to register `jwt` function as. + +For example, `jwt` function will be registered with a custom name. +```typescript +new Elysia() + .use( + jwt({ + name: 'myJWTNamespace', + secret: process.env.JWT_SECRETS! + }) + ) + .get('/sign/:name', ({ myJWTNamespace, params }) => { + return myJWTNamespace.sign(params) + }) +``` + +Because some might need to use multiple `jwt` with different configs in a single server, explicitly registering the JWT function with a different name is needed. + +### secret +The private key to sign JWT payload with. + +### schema +Type strict validation for JWT payload. + +### alg +@default `HS256` + +Signing Algorithm to sign JWT payload with. + +Possible properties for jose are: +HS256 +HS384 +HS512 +PS256 +PS384 +PS512 +RS256 +RS384 +RS512 +ES256 +ES256K +ES384 +ES512 +EdDSA + +### iss +The issuer claim identifies the principal that issued the JWT as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.1) + +TLDR; is usually (the domain) name of the signer. + +### sub +The subject claim identifies the principal that is the subject of the JWT. + +The claims in a JWT are normally statements about the subject as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.2) + +### aud +The audience claim identifies the recipients that the JWT is intended for. + +Each principal intended to process the JWT MUST identify itself with a value in the audience claim as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.3) + +### jti +JWT ID claim provides a unique identifier for the JWT as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.7) + +### nbf +The "not before" claim identifies the time before which the JWT must not be accepted for processing as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.5) + +### exp +The expiration time claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4) + +### iat +The "issued at" claim identifies the time at which the JWT was issued. + +This claim can be used to determine the age of the JWT as per [RFC7519](https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6) + +### b64 +This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing input computation as per [RFC7797](https://www.rfc-editor.org/rfc/rfc7797). + +### kid +A hint indicating which key was used to secure the JWS. + +This parameter allows originators to explicitly signal a change of key to recipients as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.4) + +### x5t +(X.509 certificate SHA-1 thumbprint) header parameter is a base64url-encoded SHA-1 digest of the DER encoding of the X.509 certificate [RFC5280](https://www.rfc-editor.org/rfc/rfc5280) corresponding to the key used to digitally sign the JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.7) + +### x5c +(X.509 certificate chain) header parameter contains the X.509 public key certificate or certificate chain [RFC5280](https://www.rfc-editor.org/rfc/rfc5280) corresponding to the key used to digitally sign the JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.6) + +### x5u +(X.509 URL) header parameter is a URI [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) that refers to a resource for the X.509 public key certificate or certificate chain [RFC5280] corresponding to the key used to digitally sign the JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.5) + +### jwk +The "jku" (JWK Set URL) Header Parameter is a URI [RFC3986] that refers to a resource for a set of JSON-encoded public keys, one of which corresponds to the key used to digitally sign the JWS. + +The keys MUST be encoded as a JWK Set [JWK] as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.2) + +### typ +The `typ` (type) Header Parameter is used by JWS applications to declare the media type [IANA.MediaTypes] of this complete JWS. + +This is intended for use by the application when more than one kind of object could be present in an application data structure that can contain a JWS as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.9) + +### ctr +Content-Type parameter is used by JWS applications to declare the media type [IANA.MediaTypes] of the secured content (the payload). + +This is intended for use by the application when more than one kind of object could be present in the JWS Payload as per [RFC7515](https://www.rfc-editor.org/rfc/rfc7515#section-4.1.9) + +## Handler +Below are the value added to the handler. + +### jwt.sign +A dynamic object of collection related to use with JWT registered by the JWT plugin. + +Type: +```typescript +sign: (payload: JWTPayloadSpec): Promise +``` + +`JWTPayloadSpec` accepts the same value as [JWT config](#config) + +### jwt.verify +Verify payload with the provided JWT config + +Type: +```typescript +verify(payload: string) => Promise +``` + +`JWTPayloadSpec` accepts the same value as [JWT config](#config) + +## Pattern +Below you can find the common patterns to use the plugin. + +## Set JWT expiration date +By default, the config is passed to `setCookie` and inherits its value. + +```typescript +const app = new Elysia() + .use( + jwt({ + name: 'jwt', + secret: 'kunikuzushi', + exp: '7d' + }) + ) + .get('/sign/:name', async ({ jwt, params }) => jwt.sign(params)) +``` + +This will sign JWT with an expiration date of the next 7 days. diff --git a/.agents/skills/elysiajs/plugins/openapi.md b/.agents/skills/elysiajs/plugins/openapi.md new file mode 100644 index 00000000..c69150d8 --- /dev/null +++ b/.agents/skills/elysiajs/plugins/openapi.md @@ -0,0 +1,246 @@ +# OpenAPI Plugin + +## Installation +```bash +bun add @elysiajs/openapi +``` + +## Basic Usage +```typescript +import { openapi } from '@elysiajs/openapi' + +new Elysia() + .use(openapi()) + .get('/', () => 'hello') +``` + +Docs at `/openapi`, spec at `/openapi/json`. + +## Detail Object +Extends OpenAPI Operation Object: +```typescript +.get('/', () => 'hello', { + detail: { + title: 'Hello', + description: 'An example route', + summary: 'Short summary', + deprecated: false, + hide: true, // Hide from docs + tags: ['App'] + } +}) +``` + +### Documentation Config +```typescript +openapi({ + documentation: { + info: { + title: 'API', + version: '1.0.0' + }, + tags: [ + { name: 'App', description: 'General' } + ], + components: { + securitySchemes: { + bearerAuth: { type: 'http', scheme: 'bearer' } + } + } + } +}) +``` + +### Standard Schema Mapping +```typescript +mapJsonSchema: { + zod: z.toJSONSchema, // Zod 4 + valibot: toJsonSchema, + effect: JSONSchema.make +} +``` + +Zod 3: `zodToJsonSchema` from `zod-to-json-schema` + +## OpenAPI Type Gen +Generate docs from types: +```typescript +import { fromTypes } from '@elysiajs/openapi' + +export const app = new Elysia() + .use(openapi({ + references: fromTypes() + })) +``` + +### Production +Recommended to generate `.d.ts` file for production when using OpenAPI Type Gen +```typescript +references: fromTypes( + process.env.NODE_ENV === 'production' + ? 'dist/index.d.ts' + : 'src/index.ts' +) +``` + +### Options +```typescript +fromTypes('src/index.ts', { + projectRoot: path.join('..', import.meta.dir), + tsconfigPath: 'tsconfig.dts.json' +}) +``` + +### Caveat: Explicit Types +Use `Prettify` helper to inline when type is not showing: +```typescript +type Prettify = { [K in keyof T]: T[K] } & {} + +function getUser(): Prettify { } +``` + +## Schema Description +```typescript +body: t.Object({ + username: t.String(), + password: t.String({ + minLength: 8, + description: 'Password (8+ chars)' + }) +}, { + description: 'Expected username and password' +}), +detail: { + summary: 'Sign in user', + tags: ['auth'] +} +``` + +## Response Headers +```typescript +import { withHeader } from '@elysiajs/openapi' + +response: withHeader( + t.Literal('Hi'), + { 'x-powered-by': t.Literal('Elysia') } +) +``` + +Annotation only - doesn't enforce. Set headers manually. + +## Tags +Define + assign: +```typescript +.use(openapi({ + documentation: { + tags: [ + { name: 'App', description: 'General' }, + { name: 'Auth', description: 'Auth' } + ] + } +})) +.get('/', () => 'hello', { + detail: { tags: ['App'] } +}) +``` + +### Instance Tags +```typescript +new Elysia({ tags: ['user'] }) + .get('/user', 'user') +``` + +## Reference Models +Auto-generates schemas: +```typescript +.model({ + User: t.Object({ + id: t.Number(), + username: t.String() + }) +}) +.get('/user', () => ({ id: 1, username: 'x' }), { + response: { 200: 'User' }, + detail: { tags: ['User'] } +}) +``` + +## Guard +Apply to instance/group: +```typescript +.guard({ + detail: { + description: 'Requires auth' + } +}) +.get('/user', 'user') +``` + +## Security +```typescript +.use(openapi({ + documentation: { + components: { + securitySchemes: { + bearerAuth: { + type: 'http', + scheme: 'bearer', + bearerFormat: 'JWT' + } + } + } + } +})) + +new Elysia({ + prefix: '/address', + detail: { + security: [{ bearerAuth: [] }] + } +}) +``` + +Secures all routes under prefix. + +## Config +Below is a config which is accepted by the `openapi({})` + +### enabled +@default true +Enable/Disable the plugin + +### documentation +OpenAPI documentation information +@see https://spec.openapis.org/oas/v3.0.3.html + +### exclude +Configuration to exclude paths or methods from documentation + +### exclude.methods +List of methods to exclude from documentation + +### exclude.paths +List of paths to exclude from documentation + +### exclude.staticFile +@default true + +Exclude static file routes from documentation + +### exclude.tags +List of tags to exclude from documentation + +### mapJsonSchema +A custom mapping function from Standard schema to OpenAPI schema + +### path +@default '/openapi' +The endpoint to expose OpenAPI documentation frontend + +### provider +@default 'scalar' + +OpenAPI documentation frontend between: +- Scalar +- SwaggerUI +- null: disable frontend diff --git a/.agents/skills/elysiajs/plugins/opentelemetry.md b/.agents/skills/elysiajs/plugins/opentelemetry.md new file mode 100644 index 00000000..0ca95c31 --- /dev/null +++ b/.agents/skills/elysiajs/plugins/opentelemetry.md @@ -0,0 +1,167 @@ +# OpenTelemetry Plugin - SKILLS.md + +## Installation +```bash +bun add @elysiajs/opentelemetry +``` + +## Basic Usage +```typescript +import { opentelemetry } from '@elysiajs/opentelemetry' +import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-node' +import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto' + +new Elysia() + .use(opentelemetry({ + spanProcessors: [ + new BatchSpanProcessor(new OTLPTraceExporter()) + ] + })) +``` + +Auto-collects spans from OpenTelemetry-compatible libraries. Parent/child spans applied automatically. + +## Config +Extends OpenTelemetry SDK params: + +- `autoDetectResources` (true) - Auto-detect from env +- `contextManager` (AsyncHooksContextManager) - Custom context +- `textMapPropagator` (CompositePropagator) - W3C Trace + Baggage +- `metricReader` - For MeterProvider +- `views` - Histogram bucket config +- `instrumentations` (getNodeAutoInstrumentations()) - Metapackage or individual +- `resource` - Custom resource +- `resourceDetectors` ([envDetector, processDetector, hostDetector]) - Auto-detect needs `autoDetectResources: true` +- `sampler` - Custom sampler (default: sample all) +- `serviceName` - Namespace identifier +- `spanProcessors` - Array for tracer provider +- `traceExporter` - Auto-setup OTLP/http/protobuf with BatchSpanProcessor if not set +- `spanLimits` - Tracing params + +### Resource Detectors via Env +```bash +export OTEL_NODE_RESOURCE_DETECTORS="env,host" +# Options: env, host, os, process, serviceinstance, all, none +``` + +## Export to Backends +Example - Axiom: +```typescript +.use(opentelemetry({ + spanProcessors: [ + new BatchSpanProcessor( + new OTLPTraceExporter({ + url: 'https://api.axiom.co/v1/traces', + headers: { + Authorization: `Bearer ${Bun.env.AXIOM_TOKEN}`, + 'X-Axiom-Dataset': Bun.env.AXIOM_DATASET + } + }) + ) + ] +})) +``` + +## OpenTelemetry SDK +Use SDK normally - runs under Elysia's request span, auto-appears in trace. + +## Record Utility +Equivalent to `startActiveSpan` - auto-closes + captures exceptions: +```typescript +import { record } from '@elysiajs/opentelemetry' + +.get('', () => { + return record('database.query', () => { + return db.query('SELECT * FROM users') + }) +}) +``` + +Label for code shown in trace. + +## Function Naming +Elysia reads function names as span names: +```typescript +// ⚠️ Anonymous span +.derive(async ({ cookie: { session } }) => { + return { user: await getProfile(session) } +}) + +// ✅ Named span: "getProfile" +.derive(async function getProfile({ cookie: { session } }) { + return { user: await getProfile(session) } +}) +``` + +## getCurrentSpan +Get current span outside handler (via AsyncLocalStorage): +```typescript +import { getCurrentSpan } from '@elysiajs/opentelemetry' + +function utility() { + const span = getCurrentSpan() + span.setAttributes({ 'custom.attribute': 'value' }) +} +``` + +## setAttributes +Sugar for `getCurrentSpan().setAttributes`: +```typescript +import { setAttributes } from '@elysiajs/opentelemetry' + +function utility() { + setAttributes({ 'custom.attribute': 'value' }) +} +``` + +## Instrumentations (Advanced) +SDK must run before importing instrumented module. + +### Setup +1. Separate file: +```typescript +// src/instrumentation.ts +import { opentelemetry } from '@elysiajs/opentelemetry' +import { PgInstrumentation } from '@opentelemetry/instrumentation-pg' + +export const instrumentation = opentelemetry({ + instrumentations: [new PgInstrumentation()] +}) +``` + +2. Apply: +```typescript +// src/index.ts +import { instrumentation } from './instrumentation' +new Elysia().use(instrumentation).listen(3000) +``` + +3. Preload: +```toml +# bunfig.toml +preload = ["./src/instrumentation.ts"] +``` + +### Production Deployment (Advanced) +OpenTelemetry monkey-patches `node_modules`. Exclude instrumented libs from bundling: +```bash +bun build --compile --external pg --outfile server src/index.ts +``` + +Package.json: +```json +{ + "dependencies": { "pg": "^8.15.6" }, + "devDependencies": { + "@elysiajs/opentelemetry": "^1.2.0", + "@opentelemetry/instrumentation-pg": "^0.52.0" + } +} +``` + +Production install: +```bash +bun install --production +``` + +Keeps `node_modules` with instrumented libs at runtime. diff --git a/.agents/skills/elysiajs/plugins/server-timing.md b/.agents/skills/elysiajs/plugins/server-timing.md new file mode 100644 index 00000000..00214245 --- /dev/null +++ b/.agents/skills/elysiajs/plugins/server-timing.md @@ -0,0 +1,71 @@ +# Server Timing Plugin +This plugin adds support for auditing performance bottlenecks with Server Timing API + +## Installation +```bash +bun add @elysiajs/server-timing +``` + +## Basic Usage +```typescript twoslash +import { Elysia } from 'elysia' +import { serverTiming } from '@elysiajs/server-timing' + +new Elysia() + .use(serverTiming()) + .get('/', () => 'hello') + .listen(3000) +``` + +Server Timing then will append header 'Server-Timing' with log duration, function name, and detail for each life-cycle function. + +To inspect, open browser developer tools > Network > [Request made through Elysia server] > Timing. + +Now you can effortlessly audit the performance bottleneck of your server. + +## Config +Below is a config which is accepted by the plugin + +### enabled +@default `NODE_ENV !== 'production'` + +Determine whether or not Server Timing should be enabled + +### allow +@default `undefined` + +A condition whether server timing should be log + +### trace +@default `undefined` + +Allow Server Timing to log specified life-cycle events: + +Trace accepts objects of the following: +- request: capture duration from request +- parse: capture duration from parse +- transform: capture duration from transform +- beforeHandle: capture duration from beforeHandle +- handle: capture duration from the handle +- afterHandle: capture duration from afterHandle +- total: capture total duration from start to finish + +## Pattern +Below you can find the common patterns to use the plugin. + +## Allow Condition +You may disable Server Timing on specific routes via `allow` property + +```ts twoslash +import { Elysia } from 'elysia' +import { serverTiming } from '@elysiajs/server-timing' + +new Elysia() + .use( + serverTiming({ + allow: ({ request }) => { + return new URL(request.url).pathname !== '/no-trace' + } + }) + ) +``` diff --git a/.agents/skills/elysiajs/plugins/static.md b/.agents/skills/elysiajs/plugins/static.md new file mode 100644 index 00000000..82fa1dab --- /dev/null +++ b/.agents/skills/elysiajs/plugins/static.md @@ -0,0 +1,84 @@ +# Static Plugin +This plugin can serve static files/folders for Elysia Server + +## Installation +```bash +bun add @elysiajs/static +``` + +## Basic Usage +```typescript twoslash +import { Elysia } from 'elysia' +import { staticPlugin } from '@elysiajs/static' + +new Elysia() + .use(staticPlugin()) + .listen(3000) +``` + +By default, the static plugin default folder is `public`, and registered with `/public` prefix. + +Suppose your project structure is: +``` +| - src + | - index.ts +| - public + | - takodachi.png + | - nested + | - takodachi.png +``` + +The available path will become: +- /public/takodachi.png +- /public/nested/takodachi.png + +## Config +Below is a config which is accepted by the plugin + +### assets +@default `"public"` + +Path to the folder to expose as static + +### prefix +@default `"/public"` + +Path prefix to register public files + +### ignorePatterns +@default `[]` + +List of files to ignore from serving as static files + +### staticLimit +@default `1024` + +By default, the static plugin will register paths to the Router with a static name, if the limits are exceeded, paths will be lazily added to the Router to reduce memory usage. +Tradeoff memory with performance. + +### alwaysStatic +@default `false` + +If set to true, static files path will be registered to Router skipping the `staticLimits`. + +### headers +@default `{}` + +Set response headers of files + +### indexHTML +@default `false` + +If set to true, the `index.html` file from the static directory will be served for any request that is matching neither a route nor any existing static file. + +## Pattern +Below you can find the common patterns to use the plugin. + +## Single file +Suppose you want to return just a single file, you can use `file` instead of using the static plugin +```typescript +import { Elysia, file } from 'elysia' + +new Elysia() + .get('/file', file('public/takodachi.png')) +``` diff --git a/.agents/skills/elysiajs/references/bun-fullstack-dev-server.md b/.agents/skills/elysiajs/references/bun-fullstack-dev-server.md new file mode 100644 index 00000000..70d721bb --- /dev/null +++ b/.agents/skills/elysiajs/references/bun-fullstack-dev-server.md @@ -0,0 +1,129 @@ +# Fullstack Dev Server + +## What It Is +Bun 1.3 Fullstack Dev Server with HMR. React without bundler (no Vite/Webpack). + +Example: [elysia-fullstack-example](https://github.com/saltyaom/elysia-fullstack-example) + +## Setup +1. Install + use Elysia Static: +```typescript +import { Elysia } from 'elysia' +import { staticPlugin } from '@elysiajs/static' + +new Elysia() + .use(await staticPlugin()) // await required for HMR hooks + .listen(3000) +``` + +2. Create `public/index.html` + `public/index.tsx`: +```html + + + + + + Elysia React App + + + +
+ + + +``` + +```tsx +// public/index.tsx +import { useState } from 'react' +import { createRoot } from 'react-dom/client' + +function App() { + const [count, setCount] = useState(0) + const increase = () => setCount((c) => c + 1) + + return ( +
+

{count}

+ +
+ ) +} + +const root = createRoot(document.getElementById('root')!) +root.render() +``` + +3. Enable JSX in `tsconfig.json`: +```json +{ + "compilerOptions": { + "jsx": "react-jsx" + } +} +``` + +4. Navigate to `http://localhost:3000/public`. + +Frontend + backend in single project. No bundler. Works with HMR, Tailwind, Tanstack Query, Eden Treaty, path alias. + +## Custom Prefix +```typescript +.use(await staticPlugin({ prefix: '/' })) +``` + +Serves at `/` instead of `/public`. + +## Tailwind CSS +1. Install: +```bash +bun add tailwindcss@4 +bun add -d bun-plugin-tailwind +``` + +2. Create `bunfig.toml`: +```toml +[serve.static] +plugins = ["bun-plugin-tailwind"] +``` + +3. Create `public/global.css`: +```css +@tailwind base; +``` + +4. Add to HTML or TS: +```html + +``` +Or: +```tsx +import './global.css' +``` + +## Path Alias +1. Add to `tsconfig.json`: +```json +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@public/*": ["public/*"] + } + } +} +``` + +2. Use: +```tsx +import '@public/global.css' +``` + +Works out of box. + +## Production Build +```bash +bun build --compile --target bun --outfile server src/index.ts +``` + +Creates single executable `server`. Include `public` folder when running. diff --git a/.agents/skills/elysiajs/references/cookie.md b/.agents/skills/elysiajs/references/cookie.md new file mode 100644 index 00000000..9e1aa1ce --- /dev/null +++ b/.agents/skills/elysiajs/references/cookie.md @@ -0,0 +1,187 @@ +# Cookie + +## What It Is +Reactive mutable signal for cookie interaction. Auto-encodes/decodes objects. + +## Basic Usage +No get/set - direct value access: +```typescript +import { Elysia } from 'elysia' + +new Elysia() + .get('/', ({ cookie: { name } }) => { + // Get + name.value + + // Set + name.value = "New Value" + }) +``` + +Auto-encodes/decodes objects. Just works. + +## Reactivity +Signal-like approach. Single source of truth. Auto-sets headers, syncs values. + +Cookie jar = Proxy object. Extract value always `Cookie`, never `undefined`. Access via `.value`. + +Iterate over cookie jar → only existing cookies. + +## Cookie Attributes + +### Direct Property Assignment +```typescript +.get('/', ({ cookie: { name } }) => { + // Get + name.domain + + // Set + name.domain = 'millennium.sh' + name.httpOnly = true +}) +``` + +### set - Reset All Properties +```typescript +.get('/', ({ cookie: { name } }) => { + name.set({ + domain: 'millennium.sh', + httpOnly: true + }) +}) +``` + +Overwrites all properties. + +### add - Update Specific Properties +Like `set` but only overwrites defined properties. + +## Remove Cookie +```typescript +.get('/', ({ cookie, cookie: { name } }) => { + name.remove() + // or + delete cookie.name +}) +``` + +## Cookie Schema +Strict validation + type inference with `t.Cookie`: +```typescript +import { Elysia, t } from 'elysia' + +new Elysia() + .get('/', ({ cookie: { name } }) => { + name.value = { + id: 617, + name: 'Summoning 101' + } + }, { + cookie: t.Cookie({ + name: t.Object({ + id: t.Numeric(), + name: t.String() + }) + }) + }) +``` + +### Nullable Cookie +```typescript +cookie: t.Cookie({ + name: t.Optional( + t.Object({ + id: t.Numeric(), + name: t.String() + }) + ) +}) +``` + +## Cookie Signature +Cryptographic hash for verification. Prevents malicious modification. + +```typescript +new Elysia() + .get('/', ({ cookie: { profile } }) => { + profile.value = { id: 617, name: 'Summoning 101' } + }, { + cookie: t.Cookie({ + profile: t.Object({ + id: t.Numeric(), + name: t.String() + }) + }, { + secrets: 'Fischl von Luftschloss Narfidort', + sign: ['profile'] + }) + }) +``` + +Auto-signs/unsigns. + +### Global Config +```typescript +new Elysia({ + cookie: { + secrets: 'Fischl von Luftschloss Narfidort', + sign: ['profile'] + } +}) +``` + +## Cookie Rotation +Auto-handles secret rotation. Old signature verification + new signature signing. + +```typescript +new Elysia({ + cookie: { + secrets: ['Vengeance will be mine', 'Fischl von Luftschloss Narfidort'] + } +}) +``` + +Array = key rotation (retire old, replace with new). + +## Config + +### secrets +Secret key for signing/unsigning. Array = key rotation. + +### domain +Domain Set-Cookie attribute. Default: none (current domain only). + +### encode +Function to encode value. Default: `encodeURIComponent`. + +### expires +Date for Expires attribute. Default: none (non-persistent, deleted on browser exit). + +If both `expires` and `maxAge` set, `maxAge` takes precedence (spec-compliant clients). + +### httpOnly (false) +HttpOnly attribute. If true, JS can't access via `document.cookie`. + +### maxAge (undefined) +Seconds for Max-Age attribute. Rounded down to integer. + +If both `expires` and `maxAge` set, `maxAge` takes precedence (spec-compliant clients). + +### path +Path attribute. Default: handler path. + +### priority +Priority attribute: `low` | `medium` | `high`. Not fully standardized. + +### sameSite +SameSite attribute: +- `true` = Strict +- `false` = not set +- `'lax'` = Lax +- `'none'` = None (explicit cross-site) +- `'strict'` = Strict + +Not fully standardized. + +### secure +Secure attribute. If true, only HTTPS. Clients won't send over HTTP. diff --git a/.agents/skills/elysiajs/references/deployment.md b/.agents/skills/elysiajs/references/deployment.md new file mode 100644 index 00000000..3c4cca85 --- /dev/null +++ b/.agents/skills/elysiajs/references/deployment.md @@ -0,0 +1,413 @@ +# Deployment + +## Production Build + +### Compile to Binary (Recommended) +```bash +bun build \ + --compile \ + --minify-whitespace \ + --minify-syntax \ + --target bun \ + --outfile server \ + src/index.ts +``` + +**Benefits:** +- No runtime needed on deployment server +- Smaller memory footprint (2-3x reduction) +- Faster startup +- Single portable executable + +**Run the binary:** +```bash +./server +``` + +### Compile to JavaScript +```bash +bun build \ + --minify-whitespace \ + --minify-syntax \ + --outfile ./dist/index.js \ + src/index.ts +``` + +**Run:** +```bash +NODE_ENV=production bun ./dist/index.js +``` + +## Docker + +### Basic Dockerfile +```dockerfile +FROM oven/bun:1 AS build + +WORKDIR /app + +# Cache dependencies +COPY package.json bun.lock ./ +RUN bun install + +COPY ./src ./src + +ENV NODE_ENV=production + +RUN bun build \ + --compile \ + --minify-whitespace \ + --minify-syntax \ + --outfile server \ + src/index.ts + +FROM gcr.io/distroless/base + +WORKDIR /app + +COPY --from=build /app/server server + +ENV NODE_ENV=production + +CMD ["./server"] + +EXPOSE 3000 +``` + +### Build and Run +```bash +docker build -t my-elysia-app . +docker run -p 3000:3000 my-elysia-app +``` + +### With Environment Variables +```dockerfile +FROM gcr.io/distroless/base + +WORKDIR /app + +COPY --from=build /app/server server + +ENV NODE_ENV=production +ENV PORT=3000 +ENV DATABASE_URL="" +ENV JWT_SECRET="" + +CMD ["./server"] + +EXPOSE 3000 +``` + +## Cluster Mode (Multiple CPU Cores) + +```typescript +// src/index.ts +import cluster from 'node:cluster' +import os from 'node:os' +import process from 'node:process' + +if (cluster.isPrimary) { + for (let i = 0; i < os.availableParallelism(); i++) { + cluster.fork() + } +} else { + await import('./server') + console.log(`Worker ${process.pid} started`) +} +``` + +```typescript +// src/server.ts +import { Elysia } from 'elysia' + +new Elysia() + .get('/', () => 'Hello World!') + .listen(3000) +``` + +## Environment Variables + +### .env File +```env +NODE_ENV=production +PORT=3000 +DATABASE_URL=postgresql://user:password@localhost:5432/db +JWT_SECRET=your-secret-key +CORS_ORIGIN=https://example.com +``` + +### Load in App +```typescript +import { Elysia } from 'elysia' + +const app = new Elysia() + .get('/env', () => ({ + env: process.env.NODE_ENV, + port: process.env.PORT + })) + .listen(parseInt(process.env.PORT || '3000')) +``` + +## Platform-Specific Deployments + +### Railway +```typescript +// Railway assigns random PORT via env variable +new Elysia() + .get('/', () => 'Hello Railway') + .listen(process.env.PORT ?? 3000) +``` + +### Vercel +```typescript +// src/index.ts +import { Elysia } from 'elysia' + +export default new Elysia() + .get('/', () => 'Hello Vercel') + +export const GET = app.fetch +export const POST = app.fetch +``` + +```json +// vercel.json +{ + "$schema": "https://openapi.vercel.sh/vercel.json", + "bunVersion": "1.x" +} +``` + +### Cloudflare Workers +```typescript +import { Elysia } from 'elysia' +import { CloudflareAdapter } from 'elysia/adapter/cloudflare-worker' + +export default new Elysia({ + adapter: CloudflareAdapter +}) + .get('/', () => 'Hello Cloudflare!') + .compile() +``` + +```toml +# wrangler.toml +name = "elysia-app" +main = "src/index.ts" +compatibility_date = "2025-06-01" +``` + +### Node.js Adapter +```typescript +import { Elysia } from 'elysia' +import { node } from '@elysiajs/node' + +const app = new Elysia({ adapter: node() }) + .get('/', () => 'Hello Node.js') + .listen(3000) +``` + +## Performance Optimization + +### Enable AoT Compilation +```typescript +new Elysia({ + aot: true // Ahead-of-time compilation +}) +``` + +### Use Native Static Response +```typescript +new Elysia({ + nativeStaticResponse: true +}) + .get('/version', 1) // Optimized for Bun.serve.static +``` + +### Precompile Routes +```typescript +new Elysia({ + precompile: true // Compile all routes ahead of time +}) +``` + +## Health Checks + +```typescript +new Elysia() + .get('/health', () => ({ + status: 'ok', + timestamp: Date.now() + })) + .get('/ready', ({ db }) => { + // Check database connection + const isDbReady = checkDbConnection() + + if (!isDbReady) { + return status(503, { status: 'not ready' }) + } + + return { status: 'ready' } + }) +``` + +## Graceful Shutdown + +```typescript +import { Elysia } from 'elysia' + +const app = new Elysia() + .get('/', () => 'Hello') + .listen(3000) + +process.on('SIGTERM', () => { + console.log('SIGTERM received, shutting down gracefully') + app.stop() + process.exit(0) +}) + +process.on('SIGINT', () => { + console.log('SIGINT received, shutting down gracefully') + app.stop() + process.exit(0) +}) +``` + +## Monitoring + +### OpenTelemetry +```typescript +import { opentelemetry } from '@elysiajs/opentelemetry' + +new Elysia() + .use(opentelemetry({ + serviceName: 'my-service', + endpoint: 'http://localhost:4318' + })) +``` + +### Custom Logging +```typescript +.onRequest(({ request }) => { + console.log(`[${new Date().toISOString()}] ${request.method} ${request.url}`) +}) +.onAfterResponse(({ request, set }) => { + console.log(`[${new Date().toISOString()}] ${request.method} ${request.url} - ${set.status}`) +}) +``` + +## SSL/TLS (HTTPS) + +```typescript +import { Elysia, file } from 'elysia' + +new Elysia({ + serve: { + tls: { + cert: file('cert.pem'), + key: file('key.pem') + } + } +}) + .get('/', () => 'Hello HTTPS') + .listen(3000) +``` + +## Best Practices + +1. **Always compile to binary for production** + - Reduces memory usage + - Smaller deployment size + - No runtime needed + +2. **Use environment variables** + - Never hardcode secrets + - Use different configs per environment + +3. **Enable health checks** + - Essential for load balancers + - K8s/Docker orchestration + +4. **Implement graceful shutdown** + - Handle SIGTERM/SIGINT + - Close connections properly + +5. **Use cluster mode** + - Utilize all CPU cores + - Better performance under load + +6. **Monitor your app** + - Use OpenTelemetry + - Log requests/responses + - Track errors + +## Example Production Setup + +```typescript +// src/server.ts +import { Elysia } from 'elysia' +import { cors } from '@elysiajs/cors' +import { opentelemetry } from '@elysiajs/opentelemetry' + +export const app = new Elysia({ + aot: true, + nativeStaticResponse: true +}) + .use(cors({ + origin: process.env.CORS_ORIGIN || 'http://localhost:3000' + })) + .use(opentelemetry({ + serviceName: 'my-service' + })) + .get('/health', () => ({ status: 'ok' })) + .get('/', () => 'Hello Production') + .listen(parseInt(process.env.PORT || '3000')) + +// Graceful shutdown +process.on('SIGTERM', () => { + app.stop() + process.exit(0) +}) +``` + +```typescript +// src/index.ts (cluster) +import cluster from 'node:cluster' +import os from 'node:os' + +if (cluster.isPrimary) { + for (let i = 0; i < os.availableParallelism(); i++) { + cluster.fork() + } +} else { + await import('./server') +} +``` + +```dockerfile +# Dockerfile +FROM oven/bun:1 AS build + +WORKDIR /app + +COPY package.json bun.lock ./ +RUN bun install + +COPY ./src ./src + +ENV NODE_ENV=production + +RUN bun build --compile --outfile server src/index.ts + +FROM gcr.io/distroless/base + +WORKDIR /app + +COPY --from=build /app/server server + +ENV NODE_ENV=production + +CMD ["./server"] + +EXPOSE 3000 +``` diff --git a/.agents/skills/elysiajs/references/eden.md b/.agents/skills/elysiajs/references/eden.md new file mode 100644 index 00000000..7d9165d7 --- /dev/null +++ b/.agents/skills/elysiajs/references/eden.md @@ -0,0 +1,158 @@ +# Eden Treaty +e2e type safe RPC client for share type from backend to frontend. + +## What It Is +Type-safe object representation for Elysia server. Auto-completion + error handling. + +## Installation +```bash +bun add @elysiajs/eden +bun add -d elysia +``` + +Export Elysia server type: +```typescript +const app = new Elysia() + .get('/', () => 'Hi Elysia') + .get('/id/:id', ({ params: { id } }) => id) + .post('/mirror', ({ body }) => body, { + body: t.Object({ + id: t.Number(), + name: t.String() + }) + }) + .listen(3000) + +export type App = typeof app +``` + +Consume on client side: +```typescript +import { treaty } from '@elysiajs/eden' +import type { App } from './server' + +const client = treaty('localhost:3000') + +// response: Hi Elysia +const { data: index } = await client.get() + +// response: 1895 +const { data: id } = await client.id({ id: 1895 }).get() + +// response: { id: 1895, name: 'Skadi' } +const { data: nendoroid } = await client.mirror.post({ + id: 1895, + name: 'Skadi' +}) +``` + +## Common Errors & Fixes +- **Strict mode**: Enable in tsconfig +- **Version mismatch**: `npm why elysia` - must match server/client +- **TypeScript**: Min 5.0 +- **Method chaining**: Required on server +- **Bun types**: `bun add -d @types/bun` if using Bun APIs +- **Path alias**: Must resolve same on frontend/backend + +### Monorepo Path Alias +Must resolve to same file on frontend/backend + +```json +// tsconfig.json at root +{ + "compilerOptions": { + "baseUrl": ".", + "paths": { + "@frontend/*": ["./apps/frontend/src/*"], + "@backend/*": ["./apps/backend/src/*"] + } + } +} +``` + +## Syntax Mapping +| Path | Method | Treaty | +|----------------|--------|-------------------------------| +| / | GET | `.get()` | +| /hi | GET | `.hi.get()` | +| /deep/nested | POST | `.deep.nested.post()` | +| /item/:name | GET | `.item({ name: 'x' }).get()` | + +## Parameters + +### With body (POST/PUT/PATCH/DELETE): +```typescript +.user.post( + { name: 'Elysia' }, // body + { headers: {}, query: {}, fetch: {} } // optional +) +``` + +### No body (GET/HEAD): +```typescript +.hello.get({ headers: {}, query: {}, fetch: {} }) +``` + +### Empty body with query/headers: +```typescript +.user.post(null, { query: { name: 'Ely' } }) +``` + +### Fetch options: +```typescript +.hello.get({ fetch: { signal: controller.signal } }) +``` + +### File upload: +```typescript +// Accepts: File | File[] | FileList | Blob +.image.post({ + title: 'Title', + image: fileInput.files! +}) +``` + +## Response +```typescript +const { data, error, response, status, headers } = await api.user.post({ name: 'x' }) + +if (error) { + switch (error.status) { + case 400: throw error.value + default: throw error.value + } +} +// data unwrapped after error handling +return data +``` + +status >= 300 → `data = null`, `error` has value + +## Stream/SSE +Interpreted as `AsyncGenerator`: +```typescript +const { data, error } = await treaty(app).ok.get() +if (error) throw error + +for await (const chunk of data) console.log(chunk) +``` + +## Utility Types +```typescript +import { Treaty } from '@elysiajs/eden' + +type UserData = Treaty.Data +type UserError = Treaty.Error +``` + +## WebSocket +```typescript +const chat = api.chat.subscribe() + +chat.subscribe((message) => console.log('got', message)) +chat.on('open', () => chat.send('hello')) + +// Native access: chat.raw +``` + +`.subscribe()` accepts same params as `get`/`head` diff --git a/.agents/skills/elysiajs/references/lifecycle.md b/.agents/skills/elysiajs/references/lifecycle.md new file mode 100644 index 00000000..645584e2 --- /dev/null +++ b/.agents/skills/elysiajs/references/lifecycle.md @@ -0,0 +1,198 @@ +# Lifecycle + +Instead of a sequential process, Elysia's request handling is divided into multiple stages called lifecycle events. + +It's designed to separate the process into distinct phases based on their responsibility without interfering with each others. + +### List of events in order + +1. **request** - early, global +2. **parse** - body parsing +3. **transform** / **derive** - mutate context pre validation +4. **beforeHandle** / **resolve** - auth/guard logic +5. **handler** - your business code +6. **afterHandle** - tweak response, set headers +7. **mapResponse** - turn anything into a proper `Response` +8. **onError** - centralized error handling +9. **onAfterResponse** - post response/cleanup tasks + +## Request (`onRequest`) + +Runs first for every incoming request. + +- Ideal for **caching, rate limiting, CORS, adding global headers**. +- If the hook returns a value, the whole lifecycle stops and that value becomes the response. + +```ts +new Elysia().onRequest(({ ip, set }) => { + if (blocked(ip)) return (set.status = 429) +}) +``` + +--- + +## Parse (`onParse`) + +_Body parsing stage._ + +- Handles `text/plain`, `application/json`, `multipart/form-data`, `application/x www-form-urlencoded` by default. +- Use to add **custom parsers** or support extra `Content Type`s. + +```ts +new Elysia().onParse(({ request, contentType }) => { + if (contentType === 'application/custom') return request.text() +}) +``` + +--- + +## Transform (`onTransform`) + +_Runs **just before validation**; can mutate the request context._ + +- Perfect for **type coercion**, trimming strings, or adding temporary fields that validation will use. + +```ts +new Elysia().onTransform(({ params }) => { + params.id = Number(params.id) +}) +``` + +--- + +## Derive + +_Runs along with `onTransform` **but before validation**; adds per request values to the context._ + +- Useful for extracting info from headers, cookies, query, etc., that you want to reuse in handlers. + +```ts +new Elysia().derive(({ headers }) => ({ + bearer: headers.authorization?.replace(/^Bearer /, '') +})) +``` + +--- + +## Before Handle (`onBeforeHandle`) + +_Executed after validation, right before the route handler._ + +- Great for **auth checks, permission gating, custom pre validation logic**. +- Returning a value skips the handler. + +```ts +new Elysia().get('/', () => 'hi', { + beforeHandle({ cookie, status }) { + if (!cookie.session) return status(401) + } +}) +``` + +--- + +## Resolve + +_Like `derive` but runs **after validation** along "Before Handle" (so you can rely on validated data)._ + +- Usually placed inside a `guard` because it isn't available as a local hook. + +```ts +new Elysia().guard( + { headers: t.Object({ authorization: t.String() }) }, + (app) => + app + .resolve(({ headers }) => ({ + bearer: headers.authorization.split(' ')[1] + })) + .get('/', ({ bearer }) => bearer) +) +``` + +--- + +## After Handle (`onAfterHandle`) + +_Runs after the handler finishes._ + +- Can **modify response headers**, wrap the result in a `Response`, or transform the payload. +- Returning a value **replaces** the handler’s result, but the next `afterHandle` hooks still run. + +```ts +new Elysia().get('/', () => '

Hello

', { + afterHandle({ response, set }) { + if (isHtml(response)) { + set.headers['content-type'] = 'text/html; charset=utf-8' + return new Response(response) + } + } +}) +``` + +--- + +## Map Response (`mapResponse`) + +_Runs right after all `afterHandle` hooks; maps **any** value to a Web standard `Response`._ + +- Ideal for **compression, custom content type mapping, streaming**. + +```ts +new Elysia().mapResponse(({ responseValue, set }) => { + const body = + typeof responseValue === 'object' + ? JSON.stringify(responseValue) + : String(responseValue ?? '') + + set.headers['content-encoding'] = 'gzip' + return new Response(Bun.gzipSync(new TextEncoder().encode(body)), { + headers: { + 'Content-Type': + typeof responseValue === 'object' + ? 'application/json' + : 'text/plain' + } + }) +}) +``` + +--- + +## On Error (`onError`) + +_Caught whenever an error bubbles up from any lifecycle stage._ + +- Use to **customize error messages**, **handle 404**, **log**, or **retry**. +- Must be registered **before** the routes it should protect. + +```ts +new Elysia().onError(({ code, status }) => { + if (code === 'NOT_FOUND') return status(404, '❓ Not found') + return new Response('Oops', { status: 500 }) +}) +``` + +--- + +## After Response (`onAfterResponse`) + +_Runs **after** the response has been sent to the client._ + +- Perfect for **logging, metrics, cleanup**. + +```ts +new Elysia().onAfterResponse(() => + console.log('✅ response sent at', Date.now()) +) +``` + +--- + +## Hook Types + +| Type | Scope | How to add | +| -------------------- | --------------------------------- | --------------------------------------------------------- | +| **Local Hook** | Single route | Inside route options (`afterHandle`, `beforeHandle`, …) | +| **Interceptor Hook** | Whole instance (and later routes) | `.onXxx(cb)` or `.use(plugin)` | + +> **Remember:** Hooks only affect routes **defined after** they are registered, except `onRequest` which is global because it runs before route matching. diff --git a/.agents/skills/elysiajs/references/macro.md b/.agents/skills/elysiajs/references/macro.md new file mode 100644 index 00000000..f89ee75c --- /dev/null +++ b/.agents/skills/elysiajs/references/macro.md @@ -0,0 +1,83 @@ +# Macro + +Composable Elysia function for controlling lifecycle/schema/context with full type safety. Available in hook after definition control by key-value label. + +## Basic Pattern +```typescript +.macro({ + hi: (word: string) => ({ + beforeHandle() { console.log(word) } + }) +}) +.get('/', () => 'hi', { hi: 'Elysia' }) +``` + +## Property Shorthand +Object → function accepting boolean: +```typescript +.macro({ + // These equivalent: + isAuth: { resolve: () => ({ user: 'saltyaom' }) }, + isAuth(enabled: boolean) { if(enabled) return { resolve() {...} } } +}) +``` + +## Error Handling +Return `status`, don't throw: +```typescript +.macro({ + auth: { + resolve({ headers }) { + if(!headers.authorization) return status(401, 'Unauthorized') + return { user: 'SaltyAom' } + } + } +}) +``` + +## Resolve - Add Context Props +```typescript +.macro({ + user: (enabled: true) => ({ + resolve: () => ({ user: 'Pardofelis' }) + }) +}) +.get('/', ({ user }) => user, { user: true }) +``` + +### Named Macro for Type Inference +TypeScript limitation workaround: +```typescript +.macro('user', { resolve: () => ({ user: 'lilith' }) }) +.macro('user2', { user: true, resolve: ({ user }) => {} }) +``` + +## Schema +Auto-validates, infers types, stacks with other schemas: +```typescript +.macro({ + withFriends: { + body: t.Object({ friends: t.Tuple([...]) }) + } +}) +``` + +Use named single macro for lifecycle type inference within same macro. + +## Extension +Stack macros: +```typescript +.macro({ + sartre: { body: t.Object({...}) }, + fouco: { body: t.Object({...}) }, + lilith: { fouco: true, sartre: true, body: t.Object({...}) } +}) +``` + +## Deduplication +Auto-dedupes by property value. Custom seed: +```typescript +.macro({ sartre: (role: string) => ({ seed: role, ... }) }) +``` + +Max stack: 16 (prevents infinite loops) diff --git a/.agents/skills/elysiajs/references/plugin.md b/.agents/skills/elysiajs/references/plugin.md new file mode 100644 index 00000000..cd10e64b --- /dev/null +++ b/.agents/skills/elysiajs/references/plugin.md @@ -0,0 +1,207 @@ +# Plugins + +## Plugin = Decoupled Elysia Instance + +```ts +const plugin = new Elysia() + .decorate('plugin', 'hi') + .get('/plugin', ({ plugin }) => plugin) + +const app = new Elysia() + .use(plugin) // inherit properties + .get('/', ({ plugin }) => plugin) +``` + +**Inherits**: state, decorate +**Does NOT inherit**: lifecycle (isolated by default) + +## Dependency + +Each instance runs independently like microservice. **Must explicitly declare dependencies**. + +```ts +const auth = new Elysia() + .decorate('Auth', Auth) + +// ❌ Missing dependency +const main = new Elysia() + .get('/', ({ Auth }) => Auth.getProfile()) + +// ✅ Declare dependency +const main = new Elysia() + .use(auth) // required for Auth + .get('/', ({ Auth }) => Auth.getProfile()) +``` + +## Deduplication + +**Every plugin re-executes by default**. Use `name` + optional `seed` to deduplicate: + +```ts +const ip = new Elysia({ name: 'ip' }) // unique identifier + .derive({ as: 'global' }, ({ server, request }) => ({ + ip: server?.requestIP(request) + })) + +const router1 = new Elysia().use(ip) +const router2 = new Elysia().use(ip) +const server = new Elysia().use(router1).use(router2) +// `ip` only executes once due to deduplication +``` + +## Global vs Explicit Dependency + +**Global plugin** (rare, apply everywhere): +- Doesn't add types - cors, compress, helmet +- Global lifecycle no instance controls - tracing, logging +- Examples: OpenAPI docs, OpenTelemetry, logging + +**Explicit dependency** (default, recommended): +- Adds types - macro, state, model +- Business logic instances interact with - Auth, DB +- Examples: state management, ORM, auth, features + +## Scope + +**Lifecycle isolated by default**. Must specify scope to export. + +```ts +// ❌ NOT inherited by app +const profile = new Elysia() + .onBeforeHandle(({ cookie }) => throwIfNotSignIn(cookie)) + .get('/profile', () => 'Hi') + +const app = new Elysia() + .use(profile) + .patch('/rename', ({ body }) => updateProfile(body)) // No sign-in check + +// ✅ Exported to app +const profile = new Elysia() + .onBeforeHandle({ as: 'global' }, ({ cookie }) => throwIfNotSignIn(cookie)) + .get('/profile', () => 'Hi') +``` + +## Scope Levels + +1. **local** (default) - current + descendants only +2. **scoped** - parent + current + descendants +3. **global** - all instances (all parents, current, descendants) + +Example with `.onBeforeHandle({ as: 'local' }, ...)`: + +| type | child | current | parent | main | +|------|-------|---------|--------|------| +| local | ✅ | ✅ | ❌ | ❌ | +| scoped | ✅ | ✅ | ✅ | ❌ | +| global | ✅ | ✅ | ✅ | ✅ | + +## Config + +```ts +// Instance factory with config +const version = (v = 1) => new Elysia() + .get('/version', v) + +const app = new Elysia() + .use(version(1)) +``` + +## Functional Callback (not recommended) + +```ts +// Harder to handle scope/encapsulation +const plugin = (app: Elysia) => app + .state('counter', 0) + .get('/plugin', () => 'Hi') + +// Prefer new instance (better type inference, no perf diff) +``` + +## Guard (Apply to Multiple Routes) + +```ts +.guard( + { body: t.Object({ username: t.String(), password: t.String() }) }, + (app) => + app.post('/sign-up', ({ body }) => signUp(body)) + .post('/sign-in', ({ body }) => signIn(body)) +) +``` + +**Grouped guard** (merge group + guard): + +```ts +.group( + '/v1', + { body: t.Literal('Rikuhachima Aru') }, // guard here + (app) => app.post('/student', ({ body }) => body) +) +``` + +## Scope Casting + +**3 methods to apply hook to parent**: + +1. **Inline as** (single hook): +```ts +.derive({ as: 'scoped' }, () => ({ hi: 'ok' })) +``` + +2. **Guard as** (multiple hooks, no derive/resolve): +```ts +.guard({ + as: 'scoped', + response: t.String(), + beforeHandle() { console.log('ok') } +}) +``` + +3. **Instance as** (all hooks + schema): +```ts +const plugin = new Elysia() + .derive(() => ({ hi: 'ok' })) + .get('/child', ({ hi }) => hi) + .as('scoped') // lift scope up +``` + +`.as()` lifts scope: local → scoped → global + +## Lazy Load + +**Deferred module** (async plugin, non-blocking startup): + +```ts +// plugin.ts +export const loadStatic = async (app: Elysia) => { + const files = await loadAllFiles() + files.forEach((asset) => app.get(asset, file(asset))) + return app +} + +// main.ts +const app = new Elysia().use(loadStatic) +``` + +**Lazy-load module** (dynamic import): + +```ts +const app = new Elysia() + .use(import('./plugin')) // loaded after startup +``` + +**Testing** (wait for modules): + +```ts +await app.modules // ensure all deferred/lazy modules loaded +``` + +## Notes +[Inference] Based on docs patterns: +- Use inline values for static resources (performance optimization) +- Group routes by prefix for organization +- Extend context minimally (separation of concerns) +- Use `status()` over `set.status` for type safety +- Prefer `resolve()` over `derive()` when type integrity matters +- Plugins isolated by default (must declare scope explicitly) +- Use `name` for deduplication when plugin used multiple times +- Prefer explicit dependency over global (better modularity/tracking) diff --git a/.agents/skills/elysiajs/references/route.md b/.agents/skills/elysiajs/references/route.md new file mode 100644 index 00000000..c767283b --- /dev/null +++ b/.agents/skills/elysiajs/references/route.md @@ -0,0 +1,331 @@ +# ElysiaJS: Routing, Handlers & Context + +## Routing + +### Path Types + +```ts +new Elysia() + .get('/static', 'static path') // exact match + .get('/id/:id', 'dynamic path') // captures segment + .get('/id/*', 'wildcard path') // captures rest +``` + +**Path Priority**: static > dynamic > wildcard + +### Dynamic Paths + +```ts +new Elysia() + .get('/id/:id', ({ params: { id } }) => id) + .get('/id/:id/:name', ({ params: { id, name } }) => id + ' ' + name) +``` + +**Optional params**: `.get('/id/:id?', ...)` + +### HTTP Verbs + +- `.get()` - retrieve data +- `.post()` - submit/create +- `.put()` - replace +- `.patch()` - partial update +- `.delete()` - remove +- `.all()` - any method +- `.route(method, path, handler)` - custom verb + +### Grouping Routes + +```ts +new Elysia() + .group('/user', { body: t.Literal('auth') }, (app) => + app.post('/sign-in', ...) + .post('/sign-up', ...) +) + +// Or use prefix in constructor +new Elysia({ prefix: '/user' }) + .post('/sign-in', ...) +``` + +## Handlers + +### Handler = function accepting HTTP request, returning response + +```ts +// Inline value (compiled ahead, optimized) +.get('/', 'Hello Elysia') +.get('/video', file('video.mp4')) + +// Function handler +.get('/', () => 'hello') +.get('/', ({ params, query, body }) => {...}) +``` + +### Context Properties + +- `body` - HTTP message/form/file +- `query` - query string as object +- `params` - path parameters +- `headers` - HTTP headers +- `cookie` - mutable signal for cookies +- `store` - global mutable state +- `request` - Web Standard Request +- `server` - Bun server instance +- `path` - request pathname + +### Context Utilities + +```ts +import { redirect, form } from 'elysia' + +new Elysia().get('/', ({ status, set, form }) => { + // Status code (type-safe) + status(418, "I'm a teapot") + + // Set response props + set.headers['x-custom'] = 'value' + set.status = 418 // legacy, no type inference + + // Redirect + return redirect('https://...', 302) + + // Cookies (mutable signal, no get/set) + cookie.name.value // get + cookie.name.value = 'new' // set + + // FormData response + return form({ name: 'Party', images: [file('a.jpg')] }) + + // Single file + return file('document.pdf') +}) +``` + +### Streaming + +```ts +new Elysia() + .get('/stream', function* () { + yield 1 + yield 2 + yield 3 + }) + // Server-Sent Events + .get('/sse', function* () { + yield sse('hello') + yield sse({ event: 'msg', data: {...} }) + }) +``` + +**Note**: Headers only settable before first yield + +**Conditional stream**: returning without yield converts to normal response + +## Context Extension + +[Inference] Extend when property is: + +- Global mutable (use `state`) +- Request/response related (use `decorate`) +- Derived from existing props (use `derive`/`resolve`) + +### state() - Global Mutable + +```ts +new Elysia() + `.state('version', 1) + .get('/', ({ store: { version } }) => version) + // Multiple + .state({ counter: 0, visits: 0 }) + + // Remap (create new from existing) + .state(({ version, ...store }) => ({ + ...store, + apiVersion: version + })) +```` + +**Gotcha**: Use reference not value + +```ts +new Elysia() + // ✅ Correct + .get('/', ({ store }) => store.counter++) + + // ❌ Wrong - loses reference + .get('/', ({ store: { counter } }) => counter++) +``` + +### decorate() - Additional Context Props + +```ts +new Elysia() + .decorate('logger', new Logger()) + .get('/', ({ logger }) => logger.log('hi')) + + // Multiple + .decorate({ logger: new Logger(), db: connection }) +``` + +**When**: constant/readonly values, classes with internal state, singletons + +### derive() - Create from Existing (Transform Lifecycle) + +```ts +new Elysia() + .derive(({ headers }) => ({ + bearer: headers.authorization?.startsWith('Bearer ') + ? headers.authorization.slice(7) + : null + })) + .get('/', ({ bearer }) => bearer) +``` + +**Timing**: runs at transform (before validation) +**Type safety**: request props typed as `unknown` + +### resolve() - Type-Safe Derive (beforeHandle Lifecycle) + +```ts +new Elysia() + .guard({ + headers: t.Object({ + bearer: t.String({ pattern: '^Bearer .+$' }) + }) + }) + .resolve(({ headers }) => ({ + bearer: headers.bearer.slice(7) // typed correctly + })) +``` + +**Timing**: runs at beforeHandle (after validation) +**Type safety**: request props fully typed + +### Error from derive/resolve + +```ts +new Elysia() + .derive(({ headers, status }) => { + if (!headers.authorization) return status(400) + return { bearer: ... } + }) +``` + +Returns early if error returned + +## Patterns + +### Affix (Bulk Remap) + +```ts +const plugin = new Elysia({ name: 'setup' }).decorate({ + argon: 'a', + boron: 'b' +}) + +new Elysia() + .use(plugin) + .prefix('decorator', 'setup') // setupArgon, setupBoron + .prefix('all', 'setup') // remap everything +``` + +### Assignment Patterns + +1. **key-value**: `.state('key', value)` +2. **object**: `.state({ k1: v1, k2: v2 })` +3. **remap**: `.state(({old}) => ({new}))` + +## Testing + +```ts +const app = new Elysia().get('/', 'hi') + +// Programmatic test +app.handle(new Request('http://localhost/')) +``` + +## To Throw or Return + +Most of an error handling in Elysia can be done by throwing an error and will be handle in `onError`. + +But for `status` it can be a little bit confusing, since it can be used both as a return value or throw an error. + +It could either be **return** or **throw** based on your specific needs. + +- If an `status` is **throw**, it will be caught by `onError` middleware. +- If an `status` is **return**, it will be **NOT** caught by `onError` middleware. + +See the following code: + +```typescript +import { Elysia, file } from 'elysia' + +new Elysia() + .onError(({ code, error, path }) => { + if (code === 418) return 'caught' + }) + .get('/throw', ({ status }) => { + // This will be caught by onError + throw status(418) + }) + .get('/return', ({ status }) => { + // This will NOT be caught by onError + return status(418) + }) +``` + +## To Throw or Return + +Elysia provide a `status` function for returning HTTP status code, prefers over `set.status`. + +`status` can be import from Elysia but preferably extract from route handler Context for type safety. + +```ts +import { Elysia, status } from 'elysia' + +function doThing() { + if (Math.random() > 0.33) return status(418, "I'm a teapot") +} + +new Elysia().get('/', ({ status }) => { + if (Math.random() > 0.33) return status(418) + + return 'ok' +}) +``` + +Error Handling in Elysia can be done by throwing an error and will be handle in `onError`. + +Status could either be **return** or **throw** based on your specific needs. + +- If an `status` is **throw**, it will be caught by `onError` middleware. +- If an `status` is **return**, it will be **NOT** caught by `onError` middleware. + +See the following code: + +```typescript +import { Elysia, file } from 'elysia' + +new Elysia() + .onError(({ code, error, path }) => { + if (code === 418) return 'caught' + }) + .get('/throw', ({ status }) => { + // This will be caught by onError + throw status(418) + }) + .get('/return', ({ status }) => { + // This will NOT be caught by onError + return status(418) + }) +``` + +## Notes + +[Inference] Based on docs patterns: + +- Use inline values for static resources (performance optimization) +- Group routes by prefix for organization +- Extend context minimally (separation of concerns) +- Use `status()` over `set.status` for type safety +- Prefer `resolve()` over `derive()` when type integrity matters diff --git a/.agents/skills/elysiajs/references/testing.md b/.agents/skills/elysiajs/references/testing.md new file mode 100644 index 00000000..ffcdff3f --- /dev/null +++ b/.agents/skills/elysiajs/references/testing.md @@ -0,0 +1,385 @@ +# Unit Testing + +## Basic Test Setup + +### Installation +```bash +bun add -d @elysiajs/eden +``` + +### Basic Test +```typescript +// test/app.test.ts +import { describe, expect, it } from 'bun:test' +import { Elysia } from 'elysia' + +describe('Elysia App', () => { + it('should return hello world', async () => { + const app = new Elysia() + .get('/', () => 'Hello World') + + const res = await app.handle( + new Request('http://localhost/') + ) + + expect(res.status).toBe(200) + expect(await res.text()).toBe('Hello World') + }) +}) +``` + +## Testing Routes + +### GET Request +```typescript +it('should get user by id', async () => { + const app = new Elysia() + .get('/user/:id', ({ params: { id } }) => ({ + id, + name: 'John Doe' + })) + + const res = await app.handle( + new Request('http://localhost/user/123') + ) + + const data = await res.json() + + expect(res.status).toBe(200) + expect(data).toEqual({ + id: '123', + name: 'John Doe' + }) +}) +``` + +### POST Request +```typescript +it('should create user', async () => { + const app = new Elysia() + .post('/user', ({ body }) => body) + + const res = await app.handle( + new Request('http://localhost/user', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + name: 'Jane Doe', + email: 'jane@example.com' + }) + }) + ) + + const data = await res.json() + + expect(res.status).toBe(200) + expect(data.name).toBe('Jane Doe') +}) +``` + +## Testing Module/Plugin + +### Module Structure +``` +src/ +├── modules/ +│ └── auth/ +│ ├── index.ts # Elysia instance +│ ├── service.ts +│ └── model.ts +└── index.ts +``` + +### Auth Module +```typescript +// src/modules/auth/index.ts +import { Elysia, t } from 'elysia' + +export const authModule = new Elysia({ prefix: '/auth' }) + .post('/login', ({ body, cookie: { session } }) => { + if (body.username === 'admin' && body.password === 'password') { + session.value = 'valid-session' + return { success: true } + } + return { success: false } + }, { + body: t.Object({ + username: t.String(), + password: t.String() + }) + }) + .get('/profile', ({ cookie: { session }, status }) => { + if (!session.value) { + return status(401, { error: 'Unauthorized' }) + } + return { username: 'admin' } + }) +``` + +### Auth Module Test +```typescript +// test/auth.test.ts +import { describe, expect, it } from 'bun:test' +import { authModule } from '../src/modules/auth' + +describe('Auth Module', () => { + it('should login successfully', async () => { + const res = await authModule.handle( + new Request('http://localhost/auth/login', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + username: 'admin', + password: 'password' + }) + }) + ) + + const data = await res.json() + expect(res.status).toBe(200) + expect(data.success).toBe(true) + }) + + it('should reject invalid credentials', async () => { + const res = await authModule.handle( + new Request('http://localhost/auth/login', { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + username: 'wrong', + password: 'wrong' + }) + }) + ) + + const data = await res.json() + expect(data.success).toBe(false) + }) + + it('should return 401 for unauthenticated profile request', async () => { + const res = await authModule.handle( + new Request('http://localhost/auth/profile') + ) + + expect(res.status).toBe(401) + }) +}) +``` + +## Eden Treaty Testing + +### Setup +```typescript +import { treaty } from '@elysiajs/eden' +import { app } from '../src/modules/auth' + +const api = treaty(app) +``` + +### Eden Tests +```typescript +describe('Auth Module with Eden', () => { + it('should login with Eden', async () => { + const { data, error } = await api.auth.login.post({ + username: 'admin', + password: 'password' + }) + + expect(error).toBeNull() + expect(data?.success).toBe(true) + }) + + it('should get profile with Eden', async () => { + // First login + await api.auth.login.post({ + username: 'admin', + password: 'password' + }) + + // Then get profile + const { data, error } = await api.auth.profile.get() + + expect(error).toBeNull() + expect(data?.username).toBe('admin') + }) +}) +``` + +## Mocking Dependencies + +### With Decorators +```typescript +// app.ts +export const app = new Elysia() + .decorate('db', realDatabase) + .get('/users', ({ db }) => db.getUsers()) + +// test +import { app } from '../src/app' + +describe('App with mocked DB', () => { + it('should use mock database', async () => { + const mockDb = { + getUsers: () => [{ id: 1, name: 'Test User' }] + } + + const testApp = app.decorate('db', mockDb) + + const res = await testApp.handle( + new Request('http://localhost/users') + ) + + const data = await res.json() + expect(data).toEqual([{ id: 1, name: 'Test User' }]) + }) +}) +``` + +## Testing with Headers + +```typescript +it('should require authorization', async () => { + const app = new Elysia() + .get('/protected', ({ headers, status }) => { + if (!headers.authorization) { + return status(401) + } + return { data: 'secret' } + }) + + const res = await app.handle( + new Request('http://localhost/protected', { + headers: { + 'Authorization': 'Bearer token123' + } + }) + ) + + expect(res.status).toBe(200) +}) +``` + +## Testing Validation + +```typescript +import { Elysia, t } from 'elysia' + +it('should validate request body', async () => { + const app = new Elysia() + .post('/user', ({ body }) => body, { + body: t.Object({ + name: t.String(), + age: t.Number({ minimum: 0 }) + }) + }) + + // Valid request + const validRes = await app.handle( + new Request('http://localhost/user', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'John', + age: 25 + }) + }) + ) + expect(validRes.status).toBe(200) + + // Invalid request (negative age) + const invalidRes = await app.handle( + new Request('http://localhost/user', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'John', + age: -5 + }) + }) + ) + expect(invalidRes.status).toBe(400) +}) +``` + +## Testing WebSocket + +```typescript +it('should handle websocket connection', (done) => { + const app = new Elysia() + .ws('/chat', { + message(ws, message) { + ws.send('Echo: ' + message) + } + }) + + const ws = new WebSocket('ws://localhost:3000/chat') + + ws.onopen = () => { + ws.send('Hello') + } + + ws.onmessage = (event) => { + expect(event.data).toBe('Echo: Hello') + ws.close() + done() + } +}) +``` + +## Complete Example + +```typescript +// src/modules/auth/index.ts +import { Elysia, t } from 'elysia' + +export const authModule = new Elysia({ prefix: '/auth' }) + .post('/login', ({ body, cookie: { session } }) => { + if (body.username === 'admin' && body.password === 'password') { + session.value = 'valid-session' + return { success: true } + } + return { success: false } + }, { + body: t.Object({ + username: t.String(), + password: t.String() + }) + }) + .get('/profile', ({ cookie: { session }, status }) => { + if (!session.value) { + return status(401) + } + return { username: 'admin' } + }) + +// test/auth.test.ts +import { describe, expect, it } from 'bun:test' +import { treaty } from '@elysiajs/eden' +import { authModule } from '../src/modules/auth' + +const api = treaty(authModule) + +describe('Auth Module', () => { + it('should login successfully', async () => { + const { data, error } = await api.auth.login.post({ + username: 'admin', + password: 'password' + }) + + expect(error).toBeNull() + expect(data?.success).toBe(true) + }) + + it('should return 401 for unauthorized access', async () => { + const { error } = await api.auth.profile.get() + + expect(error?.status).toBe(401) + }) +}) +``` diff --git a/.agents/skills/elysiajs/references/validation.md b/.agents/skills/elysiajs/references/validation.md new file mode 100644 index 00000000..ba723e0c --- /dev/null +++ b/.agents/skills/elysiajs/references/validation.md @@ -0,0 +1,491 @@ +# Validation Schema - SKILLS.md + +## What It Is +Runtime validation + type inference + OpenAPI schema from single source. TypeBox-based with Standard Schema support. + +## Basic Usage +```typescript +import { Elysia, t } from 'elysia' + +new Elysia() + .get('/id/:id', ({ params: { id } }) => id, { + params: t.Object({ id: t.Number({ minimum: 1 }) }), + response: { + 200: t.Number(), + 404: t.Literal('Not Found') + } + }) +``` + +## Schema Types +Third parameter of HTTP method: +- **body** - HTTP message +- **query** - URL query params +- **params** - Path params +- **headers** - Request headers +- **cookie** - Request cookies +- **response** - Response (per status) + +## Standard Schema Support +Use Zod, Valibot, ArkType, Effect, Yup, Joi: +```typescript +import { z } from 'zod' +import * as v from 'valibot' + +.get('/', ({ params, query }) => params.id, { + params: z.object({ id: z.coerce.number() }), + query: v.object({ name: v.literal('Lilith') }) +}) +``` + +Mix validators in same handler. + +## Body +```typescript +body: t.Object({ name: t.String() }) +``` + +GET/HEAD: body-parser disabled by default (RFC2616). + +### File Upload +```typescript +body: t.Object({ + file: t.File({ format: 'image/*' }), + multipleFiles: t.Files() +}) +// Auto-assumes multipart/form-data +``` + +### File (Standard Schema) +```typescript +import { fileType } from 'elysia' + +body: z.object({ + file: z.file().refine((file) => fileType(file, 'image/jpeg')) +}) +``` + +Use `fileType` for security (validates magic number, not just MIME). + +## Query +```typescript +query: t.Object({ name: t.String() }) +// /?name=Elysia +``` + +Auto-coerces to specified type. + +### Arrays +```typescript +query: t.Object({ name: t.Array(t.String()) }) +``` + +Formats supported: +- **nuqs**: `?name=a,b,c` (comma delimiter) +- **HTML form**: `?name=a&name=b&name=c` (multiple keys) + +## Params +```typescript +params: t.Object({ id: t.Number() }) +// /id/1 +``` + +Auto-inferred as string if schema not provided. + +## Headers +```typescript +headers: t.Object({ authorization: t.String() }) +``` + +`additionalProperties: true` by default. Always lowercase keys. + +## Cookie +```typescript +cookie: t.Cookie({ + name: t.String() +}, { + secure: true, + httpOnly: true +}) +``` + +Or use `t.Object`. `additionalProperties: true` by default. + +## Response +```typescript +response: t.Object({ name: t.String() }) +``` + +### Per Status +```typescript +response: { + 200: t.Object({ name: t.String() }), + 400: t.Object({ error: t.String() }) +} +``` + +## Error Handling + +### Inline Error Property +```typescript +body: t.Object({ + x: t.Number({ error: 'x must be number' }) +}) +``` + +Or function: +```typescript +x: t.Number({ + error({ errors, type, validation, value }) { + return 'Expected x to be number' + } +}) +``` + +### onError Hook +```typescript +.onError(({ code, error }) => { + if (code === 'VALIDATION') + return error.message // or error.all[0].message +}) +``` + +`error.all` - list all error causes. `error.all.find(x => x.path === '/name')` - find specific field. + +## Reference Models +Name + reuse models: +```typescript +.model({ + sign: t.Object({ + username: t.String(), + password: t.String() + }) +}) +.post('/sign-in', ({ body }) => body, { + body: 'sign', + response: 'sign' +}) +``` + +Extract to plugin: +```typescript +// auth.model.ts +export const authModel = new Elysia().model({ sign: t.Object({...}) }) + +// main.ts +new Elysia().use(authModel).post('/', ..., { body: 'sign' }) +``` + +### Naming Convention +Prevent duplicates with namespaces: +```typescript +.model({ + 'auth.admin': t.Object({...}), + 'auth.user': t.Object({...}) +}) +``` + +Or use `prefix` / `suffix` to rename models in current instance +```typescript +.model({ sign: t.Object({...}) }) +.prefix('model', 'auth') +.post('/', () => '', { + body: 'auth.User' +}) +``` + +Models with `prefix` will be capitalized. + +## TypeScript Types +```typescript +const MyType = t.Object({ hello: t.Literal('Elysia') }) +type MyType = typeof MyType.static +``` + +Single schema → runtime validation + coercion + TypeScript type + OpenAPI. + +## Guard +Apply schema to multiple handlers. Affects all handlers after definition. + +### Basic Usage +```typescript +import { Elysia, t } from 'elysia' + +new Elysia() + .get('/none', ({ query }) => 'hi') + .guard({ + query: t.Object({ + name: t.String() + }) + }) + .get('/query', ({ query }) => query) + .listen(3000) +``` + +Ensures `query.name` string required for all handlers after guard. + +### Behavior +| Path | Response | +|---------------|----------| +| /none | hi | +| /none?name=a | hi | +| /query | error | +| /query?name=a | a | + +### Precedence +- Multiple global schemas: latest wins +- Global vs local: local wins + +### Schema Types + +1. override (default) +Latest schema overrides collided schema. +```typescript +.guard({ query: t.Object({ name: t.String() }) }) +.guard({ query: t.Object({ id: t.Number() }) }) +// Only id required, name overridden +``` + +2. standalone +Both schemas run independently. Both validated. +```typescript +.guard({ query: t.Object({ name: t.String() }) }, { type: 'standalone' }) +.guard({ query: t.Object({ id: t.Number() }) }, { type: 'standalone' }) +// Both name AND id required +``` + +# Typebox Validation (Elysia.t) + +Elysia.t = TypeBox with server-side pre-configuration + HTTP-specific types + +**TypeBox API mirrors TypeScript syntax** but provides runtime validation + +## Basic Types + +| TypeBox | TypeScript | Example Value | +|---------|------------|---------------| +| `t.String()` | `string` | `"hello"` | +| `t.Number()` | `number` | `42` | +| `t.Boolean()` | `boolean` | `true` | +| `t.Array(t.Number())` | `number[]` | `[1, 2, 3]` | +| `t.Object({ x: t.Number() })` | `{ x: number }` | `{ x: 10 }` | +| `t.Null()` | `null` | `null` | +| `t.Literal(42)` | `42` | `42` | + +## Attributes (JSON Schema 7) + +```ts +// Email format +t.String({ format: 'email' }) + +// Number constraints +t.Number({ minimum: 10, maximum: 100 }) + +// Array constraints +t.Array(t.Number(), { + minItems: 1, // min items + maxItems: 5 // max items +}) + +// Object - allow extra properties +t.Object( + { x: t.Number() }, + { additionalProperties: true } // default: false +) +``` + +## Common Patterns + +### Union (Multiple Types) +```ts +t.Union([t.String(), t.Number()]) +// type: string | number +// values: "Hello" or 123 +``` + +### Optional (Field Optional) +```ts +t.Object({ + x: t.Number(), + y: t.Optional(t.Number()) // can be undefined +}) +// type: { x: number, y?: number } +// value: { x: 123 } or { x: 123, y: 456 } +``` + +### Partial (All Fields Optional) +```ts +t.Partial(t.Object({ + x: t.Number(), + y: t.Number() +})) +// type: { x?: number, y?: number } +// value: {} or { y: 123 } or { x: 1, y: 2 } +``` + +## Elysia-Specific Types + +### UnionEnum (One of Values) +```ts +t.UnionEnum(['rapi', 'anis', 1, true, false]) +``` + +### File (Single File Upload) +```ts +t.File({ + type: 'image', // or ['image', 'video'] + minSize: '1k', // 1024 bytes + maxSize: '5m' // 5242880 bytes +}) +``` + +**File unit suffixes**: +- `m` = MegaByte (1048576 bytes) +- `k` = KiloByte (1024 bytes) + +### Files (Multiple Files) +```ts +t.Files() // extends File + array +``` + +### Cookie (Cookie Jar) +```ts +t.Cookie({ + name: t.String() +}, { + secrets: 'secret-key' // or ['key1', 'key2'] for rotation +}) +``` + +### Nullable (Allow null) +```ts +t.Nullable(t.String()) +// type: string | null +``` + +### MaybeEmpty (Allow null + undefined) +```ts +t.MaybeEmpty(t.String()) +// type: string | null | undefined +``` + +### Form (FormData Validation) +```ts +t.Form({ + someValue: t.File() +}) +// Syntax sugar for t.Object with FormData support +``` + +### UInt8Array (Buffer → Uint8Array) +```ts +t.UInt8Array() +// For binary file uploads with arrayBuffer parser +``` + +### ArrayBuffer (Buffer → ArrayBuffer) +```ts +t.ArrayBuffer() +// For binary file uploads with arrayBuffer parser +``` + +### ObjectString (String → Object) +```ts +t.ObjectString() +// Accepts: '{"x":1}' → parses to { x: 1 } +// Use in: query string, headers, FormData +``` + +### BooleanString (String → Boolean) +```ts +t.BooleanString() +// Accepts: 'true'/'false' → parses to boolean +// Use in: query string, headers, FormData +``` + +### Numeric (String/Number → Number) +```ts +t.Numeric() +// Accepts: '123' or 123 → transforms to 123 +// Use in: path params, query string +``` + +## Elysia Behavior Differences from TypeBox + +### 1. Optional Behavior + +In Elysia, `t.Optional` makes **entire route parameter** optional (not object field): + +```ts +.get('/optional', ({ query }) => query, { + query: t.Optional( // makes query itself optional + t.Object({ name: t.String() }) + ) +}) +``` + +**Different from TypeBox**: TypeBox uses Optional for object fields only + +### 2. Number → Numeric Auto-Conversion + +**Route schema only** (not nested objects): + +```ts +.get('/:id', ({ id }) => id, { + params: t.Object({ + id: t.Number() // ✅ Auto-converts to t.Numeric() + }), + body: t.Object({ + id: t.Number() // ❌ NOT converted (stays t.Number()) + }) +}) + +// Outside route schema +t.Number() // ❌ NOT converted +``` + +**Why**: HTTP headers/query/params always strings. Auto-conversion parses numeric strings. + +### 3. Boolean → BooleanString Auto-Conversion + +Same as Number → Numeric: + +```ts +.get('/:active', ({ active }) => active, { + params: t.Object({ + active: t.Boolean() // ✅ Auto-converts to t.BooleanString() + }), + body: t.Object({ + active: t.Boolean() // ❌ NOT converted + }) +}) +``` + +## Usage Pattern + +```ts +import { Elysia, t } from 'elysia' + +new Elysia() + .post('/', ({ body }) => `Hello ${body}`, { + body: t.String() // validates body is string + }) + .listen(3000) +``` + +**Validation flow**: +1. Request arrives +2. Schema validates against HTTP body/params/query/headers +3. If valid → handler executes +4. If invalid → Error Life Cycle + +## Notes + +[Inference] Based on docs: +- TypeBox mirrors TypeScript but adds runtime validation +- Elysia.t extends TypeBox with HTTP-specific types +- Auto-conversion (Number→Numeric, Boolean→BooleanString) only for route schemas +- Use `t.Optional` for optional route params (different from TypeBox behavior) +- File validation supports unit suffixes ('1k', '5m') +- ObjectString/BooleanString for parsing strings in query/headers +- Cookie supports key rotation with array of secrets diff --git a/.agents/skills/elysiajs/references/websocket.md b/.agents/skills/elysiajs/references/websocket.md new file mode 100644 index 00000000..b2c86a8c --- /dev/null +++ b/.agents/skills/elysiajs/references/websocket.md @@ -0,0 +1,250 @@ +# WebSocket + +## Basic WebSocket + +```typescript +import { Elysia } from 'elysia' + +new Elysia() + .ws('/chat', { + message(ws, message) { + ws.send(message) // Echo back + } + }) + .listen(3000) +``` + +## With Validation + +```typescript +import { Elysia, t } from 'elysia' + +.ws('/chat', { + body: t.Object({ + message: t.String(), + username: t.String() + }), + response: t.Object({ + message: t.String(), + timestamp: t.Number() + }), + message(ws, body) { + ws.send({ + message: body.message, + timestamp: Date.now() + }) + } +}) +``` + +## Lifecycle Events + +```typescript +.ws('/chat', { + open(ws) { + console.log('Client connected') + }, + message(ws, message) { + console.log('Received:', message) + ws.send('Echo: ' + message) + }, + close(ws) { + console.log('Client disconnected') + }, + error(ws, error) { + console.error('Error:', error) + } +}) +``` + +## Broadcasting + +```typescript +const connections = new Set() + +.ws('/chat', { + open(ws) { + connections.add(ws) + }, + message(ws, message) { + // Broadcast to all connected clients + for (const client of connections) { + client.send(message) + } + }, + close(ws) { + connections.delete(ws) + } +}) +``` + +## With Authentication + +```typescript +.ws('/chat', { + beforeHandle({ headers, status }) { + const token = headers.authorization?.replace('Bearer ', '') + if (!verifyToken(token)) { + return status(401) + } + }, + message(ws, message) { + ws.send(message) + } +}) +``` + +## Room-Based Chat + +```typescript +const rooms = new Map>() + +.ws('/chat/:room', { + open(ws) { + const room = ws.data.params.room + if (!rooms.has(room)) { + rooms.set(room, new Set()) + } + rooms.get(room)!.add(ws) + }, + message(ws, message) { + const room = ws.data.params.room + const clients = rooms.get(room) + + if (clients) { + for (const client of clients) { + client.send(message) + } + } + }, + close(ws) { + const room = ws.data.params.room + const clients = rooms.get(room) + + if (clients) { + clients.delete(ws) + if (clients.size === 0) { + rooms.delete(room) + } + } + } +}) +``` + +## With State/Context + +```typescript +.ws('/chat', { + open(ws) { + ws.data.userId = generateUserId() + ws.data.joinedAt = Date.now() + }, + message(ws, message) { + const response = { + userId: ws.data.userId, + message, + timestamp: Date.now() + } + ws.send(response) + } +}) +``` + +## Client Usage (Browser) + +```typescript +const ws = new WebSocket('ws://localhost:3000/chat') + +ws.onopen = () => { + console.log('Connected') + ws.send('Hello Server!') +} + +ws.onmessage = (event) => { + console.log('Received:', event.data) +} + +ws.onerror = (error) => { + console.error('Error:', error) +} + +ws.onclose = () => { + console.log('Disconnected') +} +``` + +## Eden Treaty WebSocket + +```typescript +// Server +export const app = new Elysia() + .ws('/chat', { + message(ws, message) { + ws.send(message) + } + }) + +export type App = typeof app + +// Client +import { treaty } from '@elysiajs/eden' +import type { App } from './server' + +const api = treaty('localhost:3000') +const chat = api.chat.subscribe() + +chat.subscribe((message) => { + console.log('Received:', message) +}) + +chat.send('Hello!') +``` + +## Headers in WebSocket + +```typescript +.ws('/chat', { + header: t.Object({ + authorization: t.String() + }), + beforeHandle({ headers, status }) { + const token = headers.authorization?.replace('Bearer ', '') + if (!token) return status(401) + }, + message(ws, message) { + ws.send(message) + } +}) +``` + +## Query Parameters + +```typescript +.ws('/chat', { + query: t.Object({ + username: t.String() + }), + message(ws, message) { + const username = ws.data.query.username + ws.send(`${username}: ${message}`) + } +}) + +// Client +const ws = new WebSocket('ws://localhost:3000/chat?username=john') +``` + +## Compression + +```typescript +new Elysia({ + websocket: { + perMessageDeflate: true + } +}) + .ws('/chat', { + message(ws, message) { + ws.send(message) + } + }) +``` diff --git a/.agents/skills/react-router/SKILL.md b/.agents/skills/react-router/SKILL.md new file mode 100644 index 00000000..949e3aea --- /dev/null +++ b/.agents/skills/react-router/SKILL.md @@ -0,0 +1,122 @@ +--- +name: react-router +description: Build applications with React Router in Framework, Data, Declarative, and unstable RSC modes. Use when configuring routes, route modules, loaders, actions, forms, fetchers, navigation, pending UI, SSR/SPA/pre-rendering, middleware, URL params/search params, or React Router upgrades. +license: MIT +--- + +# React Router + +React Router is mode-specific. Before changing an app, identify the mode, load the matching reference, then read the installed docs for the installed package version. + +## Identify the Mode + +Do not apply Framework/Data patterns to a Declarative app unless you are intentionally migrating modes. + +### Framework Mode + +Use Framework Mode guidance when you see: + +- `@react-router/dev` in dependencies +- `react-router.config.ts` +- `app/routes.ts` +- `app/entry.server.tsx` and/or `app/entry.client.tsx` files +- route modules under `app/routes/` +- route exports like `loader`, `action`, `clientLoader`, `clientAction`, `ErrorBoundary`, `meta`, `links`, or `headers` +- imports from `./+types/...` +- the React Router Vite plugin from `@react-router/dev/vite` + +Framework examples usually use the default `app/` directory, but check `react-router.config.ts` for a custom `appDirectory` before assuming exact paths. + +Then read `references/framework-mode.md`. + +### Data Mode + +Use Data Mode guidance when you see: + +- `createBrowserRouter`, `createHashRouter`, `createMemoryRouter`, or `createStaticRouter` +- `` +- route objects with properties like `path`, `children`, `loader`, `action`, `Component`, `ErrorBoundary`, or `lazy` +- data APIs without the Framework Vite plugin + +Then read `references/data-mode.md`. + +### Declarative Mode + +Use Declarative Mode guidance when you see: + +- ``, ``, or `` +- `` and `` JSX route configuration +- route components passed with `element={}` +- no data router, no route module convention, and no loaders/actions + +Then read `references/declarative-mode.md`. + +### RSC Framework and RSC Data Modes + +React Server Components support is unstable and exists in both Framework and Data variants. Use RSC guidance when you see: + +- `unstable_reactRouterRSC` +- `@vitejs/plugin-rsc` +- `unstable_RSCRouteConfig` +- RSC entry files such as `entry.rsc` +- `ServerComponent`, `ServerErrorBoundary`, `ServerLayout`, or `ServerHydrateFallback` +- React directives or boundary packages such as `"use client"`, `"server-only"`, or `"client-only"` + +For RSC Framework, read both `references/framework-mode.md` and `references/rsc.md`. +For RSC Data, read both `references/data-mode.md` and `references/rsc.md`. + +## Use Installed Docs as Source of Truth + +React Router ships markdown docs in the package so guidance can match the installed version: + +```txt +node_modules/react-router/docs/ +``` + +Key docs paths: + +```txt +node_modules/react-router/docs/index.md +node_modules/react-router/docs/start/ +node_modules/react-router/docs/how-to/ +node_modules/react-router/docs/explanation/ +node_modules/react-router/docs/upgrading/ +``` + +When this skill references `react-router/docs/...`, read the matching file under `node_modules/react-router/docs/`. If the installed version does not include local docs, use the repo `docs/` directory when working inside the React Router repository; in a consuming app, fall back to version-matched website docs. + +Most docs include a mode marker near the top: + +```txt +[MODES: framework, data, declarative] +``` + +Only apply a doc when its mode marker matches the app mode. If a task spans modes, prefer the section or file that matches the current app. + +RSC is documented primarily in: + +```txt +node_modules/react-router/docs/how-to/react-server-components.md +``` + +## Skill References + +Load the relevant reference after identifying the mode: + +| Reference | Use When | +| -------------------------------- | --------------------------------------------- | +| `references/framework-mode.md` | Framework Mode or RSC Framework base behavior | +| `references/data-mode.md` | Data Mode or RSC Data base behavior | +| `references/declarative-mode.md` | Declarative Mode | +| `references/rsc.md` | Any unstable RSC app | + +## Mode Migration Doc Index + +If the user explicitly asks to switch modes, read the target mode reference plus the migration-relevant docs: + +| Migration | Docs to read | +| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Declarative → Data | `react-router/docs/start/modes.md`, `react-router/docs/start/data/routing.md`, `react-router/docs/start/data/data-loading.md`, `react-router/docs/start/data/actions.md` | +| Declarative/Data → Framework | `react-router/docs/start/modes.md`, `react-router/docs/start/framework/routing.md`, `react-router/docs/start/framework/route-module.md`, `react-router/docs/how-to/route-module-type-safety.md` | +| Framework SPA/SSR/pre-render changes | `react-router/docs/start/framework/rendering.md`, `react-router/docs/how-to/spa.md`, `react-router/docs/how-to/pre-rendering.md`, `react-router/docs/start/framework/data-loading.md`, `react-router/docs/start/framework/actions.md` | +| Future flags/upgrades | `react-router/docs/upgrading/future.md` and relevant files under `react-router/docs/upgrading/` | diff --git a/.agents/skills/react-router/references/data-mode.md b/.agents/skills/react-router/references/data-mode.md new file mode 100644 index 00000000..ea3480cc --- /dev/null +++ b/.agents/skills/react-router/references/data-mode.md @@ -0,0 +1,165 @@ +# Data Mode + +Data Mode uses data routers such as `createBrowserRouter` and renders with ``. It gives an app route objects, loaders, actions, pending UI, fetchers, and SSR primitives without adopting the Framework Vite plugin or route-module file conventions. + +Use this reference after the main skill identifies a Data Mode app. + +## Read the Local Docs by Mode + +Start with: + +```txt +react-router/docs/start/modes.md +react-router/docs/start/data/index.md +``` + +Then use the Data docs under: + +```txt +react-router/docs/start/data/ +``` + +Those files cover installation, route objects, routing, data loading, actions, navigation, pending UI, and testing. For task-specific details, read relevant files in: + +```txt +react-router/docs/how-to/ +react-router/docs/explanation/ +``` + +Always check the `[MODES: data, ...]` marker in a doc before applying it. + +## Data Router Shape + +Typical setup: + +```tsx +import { createBrowserRouter, RouterProvider } from "react-router"; + +const router = createBrowserRouter([ + { + path: "/", + Component: Root, + loader: rootLoader, + children: [ + { index: true, Component: Home }, + { + path: "projects/:projectId", + Component: Project, + loader: projectLoader, + }, + ], + }, +]); + +root.render(); +``` + +Look for route object arrays and APIs such as: + +- `createBrowserRouter` +- `createHashRouter` +- `createMemoryRouter` +- `RouterProvider` +- `loader` +- `action` +- `Component` +- `ErrorBoundary` +- `lazy` +- `children` + +## Route Objects and Routing + +Before editing route configuration, read: + +```txt +react-router/docs/start/data/routing.md +react-router/docs/start/data/route-object.md +``` + +Rules: + +- Keep route objects outside render when possible. +- Use nested routes for shared layouts and data boundaries. +- Use index routes for default child content. +- Use dynamic segments and splats according to route-object docs. +- Prefer `Component`/`ErrorBoundary` route object properties in Data Mode examples unless the existing app uses `element` consistently. + +## Data and Mutations + +Before working on data loading or mutations, read: + +```txt +react-router/docs/start/data/data-loading.md +react-router/docs/start/data/actions.md +``` + +Rules: + +- Load route data with route `loader` functions. +- Mutate route data with route `action` functions. +- Prefer loaders/actions over route-level `useEffect` fetching. +- Use `request`, `params`, and returned/throwable Responses as described in the docs. +- Let React Router revalidate after actions unless there is a documented reason to customize revalidation. + +Common patterns: + +- Validation failure from an action: return `data({ errors, values }, { status: 400 })`, then render errors with `useActionData()` or `fetcher.data`. +- Missing record in a loader: throw `data("Not Found", { status: 404 })` and render the route `ErrorBoundary`. +- Search/filter data: parse `new URL(request.url).searchParams` in the loader so the URL is shareable and bookmarkable. + +## Forms, Fetchers, and Pending UI + +For forms and pending UI, read: + +```txt +react-router/docs/start/data/actions.md +react-router/docs/start/data/pending-ui.md +react-router/docs/how-to/fetchers.md +react-router/docs/explanation/form-vs-fetcher.md +``` + +Rules of thumb: + +- Search/filter form that updates the URL: `
`. +- Mutation that should change URL/history or redirect after completion: ``. +- Mutation that should keep the user on the same page: `useFetcher` / ``. +- Optimistic UI: derive from `fetcher.formData` or `navigation.formData`. + +## Navigation and URL State + +Before changing navigation or search params, read: + +```txt +react-router/docs/start/data/navigating.md +react-router/docs/how-to/search-params.md +react-router/docs/explanation/location.md +``` + +Rules: + +- Use ``/`` for user-initiated internal navigation. +- Use `redirect` in loaders/actions when navigation follows data loading or mutations. +- Use `useNavigate` for imperative client-side event navigation. +- Treat URL params as strings and validate/parse them. +- Preserve unrelated search params unless intentionally resetting them. + +## SSR in Data Mode + +Data Mode SSR is manual and lower-level than Framework Mode. Before implementing or changing SSR, read the Data Mode custom/SSR docs and match existing server abstractions. + +Start with: + +```txt +react-router/docs/start/data/custom.md +``` + +Look for APIs like `createStaticHandler`, `createStaticRouter`, `StaticRouterProvider`, and hydration data handling in the current app before changing anything. + +## RSC Data + +If this Data Mode app uses `unstable_RSCRouteConfig`, RSC route config, or low-level RSC server APIs, also read: + +```txt +references/rsc.md +react-router/docs/how-to/react-server-components.md +``` diff --git a/.agents/skills/react-router/references/declarative-mode.md b/.agents/skills/react-router/references/declarative-mode.md new file mode 100644 index 00000000..982a3c4c --- /dev/null +++ b/.agents/skills/react-router/references/declarative-mode.md @@ -0,0 +1,123 @@ +# Declarative Mode + +Declarative Mode is React Router's simplest mode. It uses router components like `` and JSX routes with ``/``. It does not provide loaders, actions, fetchers, or data-router pending UI. + +Use this reference after the main skill identifies a Declarative Mode app. + +## Read the Local Docs by Mode + +Start with: + +```txt +react-router/docs/start/modes.md +react-router/docs/start/declarative/index.md +``` + +Then use the Declarative docs under: + +```txt +react-router/docs/start/declarative/ +``` + +Those files cover installation, routing, navigation, and URL values. For conceptual details, read relevant files in: + +```txt +react-router/docs/explanation/ +``` + +Always check the `[MODES: declarative, ...]` marker in a doc before applying it. + +## Declarative Router Shape + +Typical setup: + +```tsx +import { BrowserRouter, Routes, Route } from "react-router"; + +function App() { + return ( + + + } /> + } /> + }> + } /> + } /> + + + + ); +} +``` + +Look for APIs such as: + +- `` +- `` +- `` +- `` +- `` +- `element={}` +- `useRoutes` + +## Routing + +Before editing routes, read: + +```txt +react-router/docs/start/declarative/routing.md +``` + +Rules: + +- Use `` and `` for route configuration. +- Use nested routes with `` for shared layout. +- Use index routes for default child UI. +- Use route params and splats according to the declarative routing docs. +- Do not add route object loaders/actions to a Declarative router. + +## Navigation + +Before changing navigation, read: + +```txt +react-router/docs/start/declarative/navigating.md +``` + +Rules: + +- Use `` or `` for user-initiated internal navigation. +- Use `NavLink` when active styling matters. +- Use `useNavigate` for imperative navigation from event handlers or effects. +- Do not use plain `` for internal navigation unless intentionally forcing a full document navigation. + +## URL Values + +Before changing params, search params, or location state, read: + +```txt +react-router/docs/start/declarative/url-values.md +react-router/docs/explanation/location.md +``` + +Rules: + +- Use `useParams` for dynamic route params. +- Use `useSearchParams` for query string state. +- Use `useLocation` for the current location object and navigation state. +- Validate and parse URL params; they are strings and can be absent. +- Preserve unrelated search params unless intentionally resetting them. + +## Mode Boundary + +Declarative Mode does not have Data/Framework APIs such as: + +- `loader` +- `action` +- `` +- `useFetcher` +- `useNavigation` +- route module exports +- generated `./+types` route types + +If the user asks for route data loading, DB/API-backed data, CRUD, form mutations, validation returned from submissions, revalidation, pending UI, optimistic UI, or fetchers, recommend Data Mode or Framework Mode depending on how much structure they want. Ask before migrating unless they already requested it. diff --git a/.agents/skills/react-router/references/framework-mode.md b/.agents/skills/react-router/references/framework-mode.md new file mode 100644 index 00000000..5c3e096a --- /dev/null +++ b/.agents/skills/react-router/references/framework-mode.md @@ -0,0 +1,213 @@ +# Framework Mode + +Framework Mode is React Router's full-stack mode. It uses the React Router Vite plugin, route config in `app/routes.ts`, route modules, generated route types, and rendering strategies such as SSR, SPA mode, and pre-rendering. + +Use this reference after the main skill identifies a Framework Mode app. + +## Read the Local Docs by Mode + +Start with: + +```txt +react-router/docs/start/modes.md +react-router/docs/start/framework/index.md +``` + +Then use the Framework docs under: + +```txt +react-router/docs/start/framework/ +``` + +Those files cover installation, routing, route modules, data loading, actions, navigation, pending UI, rendering, deploying, and testing. For task-specific details, read relevant files in: + +```txt +react-router/docs/how-to/ +react-router/docs/explanation/ +``` + +Always check the `[MODES: framework, ...]` marker in a doc before applying it. + +## Framework Shape + +Examples usually assume the default `appDirectory` of `app`. Check `react-router.config.ts` before assuming exact paths. + +Look for these files and conventions: + +```txt +react-router.config.ts +app/root.tsx +app/routes.ts +app/routes/**/*.tsx +route modules importing from ./+types/... +``` + +Typical route module: + +```tsx +import type { Route } from "./+types/product"; + +export async function loader({ params }: Route.LoaderArgs) { + return { product: await getProduct(params.productId) }; +} + +export default function Product({ loaderData }: Route.ComponentProps) { + return

{loaderData.product.name}

; +} +``` + +## Route Configuration + +Framework apps use `app/routes.ts`. Many apps use file-system routing via `flatRoutes()`, but manual route config is also supported. + +Before editing routes, read: + +```txt +react-router/docs/start/framework/routing.md +``` + +If the app uses file-route conventions, read: + +```txt +react-router/docs/how-to/file-route-conventions.md +``` + +## Route Modules + +Route modules are the main unit of Framework Mode. Before adding or changing route exports, read: + +```txt +react-router/docs/start/framework/route-module.md +``` + +Common exports include: + +| Export | Use | +| --------------------------------- | ------------------------------------------------------------------- | +| `default` | Route component rendered for the match | +| `loader` | Server data loading for SSR/pre-rendering/server data requests | +| `clientLoader` | Browser-only data loading or supplementing server loader data | +| `action` | Server mutation called by ``, `useSubmit`, or fetchers | +| `clientAction` | Browser-only mutation or client-side wrapper around a server action | +| `ErrorBoundary` | UI for errors thrown by this route's loaders/actions/component | +| `HydrateFallback` | Initial fallback while client loader hydration runs | +| `links` / `meta` | Route document links and metadata | +| `handle` | Arbitrary route metadata consumed via `useMatches` | +| `shouldRevalidate` | Overrides default loader revalidation behavior | +| `middleware` / `clientMiddleware` | Server/client request pipeline hooks when enabled | + +Use generated `Route.*` types from `./+types/` for route module args and props. + +## Layout and Root Route Rules + +- `app/root.tsx` is the root route and should contain global document/app shell concerns. +- Put global providers, app-wide nav, app-wide footer, scripts/meta/links, and document structure in `root.tsx` when appropriate. +- Use nested routes/layout routes for section-specific layouts. +- Do not flatten routes that should share UI or data boundaries. + +Useful docs: + +```txt +react-router/docs/explanation/special-files.md +react-router/docs/start/framework/routing.md +``` + +## Data and Mutations + +Before working on route data: + +```txt +react-router/docs/start/framework/data-loading.md +react-router/docs/start/framework/actions.md +``` + +Framework rules: + +- Load route data with `loader` or `clientLoader`. +- Mutate route data with `action` or `clientAction`. +- Prefer route loaders/actions over ad hoc `useEffect` fetching for route data. +- Use `data()`/Responses and redirects according to the docs. +- Let React Router revalidate after actions unless the docs point you to `shouldRevalidate`. +- In SSR/server data routes, keep Node-only/database code in server-only modules and call it from `loader`/`action`, not from browser-rendered component code. + +Common patterns: + +- Validation failure from an action: return `data({ errors, values }, { status: 400 })`, then render errors from `Route.ComponentProps["actionData"]` or `fetcher.data`. +- Missing record in a loader: throw `data("Not Found", { status: 404 })` and render the route `ErrorBoundary`. +- Search/filter data: parse the route request URL/search params in the loader so the URL is shareable and bookmarkable. + +## Forms, Fetchers, and Pending UI + +For forms and pending UI, read: + +```txt +react-router/docs/start/framework/actions.md +react-router/docs/start/framework/pending-ui.md +react-router/docs/how-to/fetchers.md +react-router/docs/explanation/form-vs-fetcher.md +``` + +Rules of thumb: + +- Search/filter form that updates the URL: ``. +- Mutation that should change URL/history or redirect after completion: ``. +- Mutation that should keep the user on the same page: `useFetcher` / ``. +- Optimistic UI: derive from `fetcher.formData` or `navigation.formData`. + +## Type Safety + +Before changing generated route types or typed URL behavior, read: + +```txt +react-router/docs/how-to/route-module-type-safety.md +react-router/docs/explanation/type-safety.md +``` + +Rules: + +- Import types from `./+types/`. +- Use `Route.LoaderArgs`, `Route.ActionArgs`, `Route.ComponentProps`, etc. +- Use type-only imports where appropriate. +- Do not edit generated `.react-router/types` files. + +## Metadata + +Before changing `meta`, read: + +```txt +react-router/docs/how-to/meta.md +react-router/docs/start/framework/route-module.md +``` + +Important: `meta` receives `loaderData`; do not use deprecated `data` args. + +## Rendering Strategy + +Framework Mode can be SSR, SPA, pre-rendered, or mixed depending on config and route behavior. Before changing rendering behavior, read: + +```txt +react-router/docs/start/framework/rendering.md +react-router/docs/how-to/spa.md +react-router/docs/how-to/pre-rendering.md +react-router/docs/explanation/hydration.md +``` + +## Middleware, Sessions, and Auth + +Before implementing middleware or auth/session flows, read: + +```txt +react-router/docs/how-to/middleware.md +react-router/docs/explanation/sessions-and-cookies.md +``` + +Middleware and context APIs are version/config sensitive. Check the installed React Router version and the app's `react-router.config.ts` before implementing. + +## RSC Framework + +If this Framework app uses `unstable_reactRouterRSC` or `@vitejs/plugin-rsc`, also read: + +```txt +references/rsc.md +react-router/docs/how-to/react-server-components.md +``` diff --git a/.agents/skills/react-router/references/rsc.md b/.agents/skills/react-router/references/rsc.md new file mode 100644 index 00000000..b940821d --- /dev/null +++ b/.agents/skills/react-router/references/rsc.md @@ -0,0 +1,90 @@ +# React Server Components (RSC) + +React Router's RSC support is unstable and exists in two variants: + +- **RSC Framework Mode**: Framework Mode with the unstable RSC Vite plugin. +- **RSC Data Mode**: lower-level RSC runtime APIs and manual bundler/server integration. + +Use this reference in addition to `framework-mode.md` or `data-mode.md` after the main skill identifies an RSC app. + +## Read the Local RSC Docs + +Start with: + +```txt +react-router/docs/how-to/react-server-components.md +``` + +Then read the relevant base mode docs: + +```txt +react-router/docs/start/framework/ +react-router/docs/start/data/ +``` + +RSC docs may describe differences from non-RSC mode rather than repeating every Framework/Data concept, so keep both layers in mind. + +## Detect RSC Framework Mode + +Look for: + +- `unstable_reactRouterRSC` imported from `@react-router/dev/vite` +- `@vitejs/plugin-rsc` +- `vite.config.ts` with `plugins: [reactRouterRSC(), rsc()]` +- Framework route modules plus RSC route exports +- RSC entry files such as `entry.rsc` + +RSC Framework Mode uses a different Vite plugin from non-RSC Framework Mode. Do not swap it for the regular `reactRouter()` plugin. + +## Detect RSC Data Mode + +Look for: + +- `unstable_RSCRouteConfig` +- route config passed to lower-level RSC APIs +- APIs such as `unstable_matchRSCServerRequest`, `unstable_routeRSCServerRequest`, `unstable_RSCHydratedRouter`, or `unstable_RSCStaticRouter` +- custom bundler/server setup around RSC + +RSC Data Mode is more manual than RSC Framework Mode. Match the app's bundler and server abstractions before changing routes or entries. + +## RSC Route Module Differences + +In RSC Framework Mode, many normal Framework Mode concepts still apply, but routes can use server component exports. + +Important route-module concepts from the RSC docs include: + +- `ServerComponent` instead of the usual client `default` component +- `ServerErrorBoundary` paired with `ErrorBoundary` +- `ServerLayout` paired with `Layout` +- `ServerHydrateFallback` paired with `HydrateFallback` +- server-rendered React elements returned from loaders/actions + +A route module cannot export both the normal client component and its server component counterpart for the same role. Read the RSC docs before adding these exports. + +## Client/Server Boundaries + +RSC code must respect React's client/server split: + +- Use `"use client"` for components that need hooks, browser APIs, or event handlers. +- Use server-only modules for server data access and secrets. +- In RSC Framework Mode, prefer the `server-only` and `client-only` boundary imports described in the docs. +- Do not assume `.server`/`.client` file naming works the same way in RSC Framework Mode; read the RSC docs before relying on those conventions. + +## Data Loading in RSC + +RSC changes where data can be loaded: + +- Server Components can fetch data directly on the server. +- Loaders/actions may still exist and can have RSC-specific behavior. +- Client components still need client-safe data and cannot directly access server-only modules. + +When choosing between a server component fetch, a loader, and a client loader/action, follow the RSC docs and match existing app patterns. + +## Stability + +RSC APIs are explicitly unstable. Before implementing or refactoring RSC code: + +- Check the installed React Router version. +- Check the installed `@vitejs/plugin-rsc` version. +- Read the app's existing RSC entry/config files. +- Prefer minimal changes that match current patterns. diff --git a/.agents/skills/tanstack-query-best-practices/SKILL.md b/.agents/skills/tanstack-query-best-practices/SKILL.md new file mode 100644 index 00000000..374b847e --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/SKILL.md @@ -0,0 +1,114 @@ +--- +name: tanstack-query-best-practices +description: TanStack Query (React Query) best practices for data fetching, caching, mutations, and server state management. Activate when building data-driven React applications with server state. +--- + +# TanStack Query Best Practices + +Comprehensive guidelines for implementing TanStack Query (React Query) patterns in React applications. These rules optimize data fetching, caching, mutations, and server state synchronization. + +## When to Apply + +- Creating new data fetching logic +- Setting up query configurations +- Implementing mutations and optimistic updates +- Configuring caching strategies +- Integrating with SSR/SSG +- Refactoring existing data fetching code + +## Rule Categories by Priority + +| Priority | Category | Rules | Impact | +|----------|----------|-------|--------| +| CRITICAL | Query Keys | 5 rules | Prevents cache bugs and data inconsistencies | +| CRITICAL | Caching | 5 rules | Optimizes performance and data freshness | +| HIGH | Mutations | 6 rules | Ensures data integrity and UI consistency | +| HIGH | Error Handling | 3 rules | Prevents poor user experiences | +| MEDIUM | Prefetching | 4 rules | Improves perceived performance | +| MEDIUM | Parallel Queries | 2 rules | Enables dynamic parallel fetching | +| MEDIUM | Infinite Queries | 3 rules | Prevents pagination bugs | +| MEDIUM | SSR Integration | 4 rules | Enables proper hydration | +| LOW | Performance | 4 rules | Reduces unnecessary re-renders | +| LOW | Offline Support | 2 rules | Enables offline-first patterns | + +## Quick Reference + +### Query Keys (Prefix: `qk-`) + +- `qk-array-structure` — Always use arrays for query keys +- `qk-include-dependencies` — Include all variables the query depends on +- `qk-hierarchical-organization` — Organize keys hierarchically (entity → id → filters) +- `qk-factory-pattern` — Use query key factories for complex applications +- `qk-serializable` — Ensure all key parts are JSON-serializable + +### Caching (Prefix: `cache-`) + +- `cache-stale-time` — Set appropriate staleTime based on data volatility +- `cache-gc-time` — Configure gcTime for inactive query retention +- `cache-defaults` — Set sensible defaults at QueryClient level +- `cache-invalidation` — Use targeted invalidation over broad patterns +- `cache-placeholder-vs-initial` — Understand placeholder vs initial data differences + +### Mutations (Prefix: `mut-`) + +- `mut-invalidate-queries` — Always invalidate related queries after mutations +- `mut-optimistic-updates` — Implement optimistic updates for responsive UI +- `mut-rollback-context` — Provide rollback context from onMutate +- `mut-error-handling` — Handle mutation errors gracefully +- `mut-loading-states` — Use isPending for mutation loading states +- `mut-mutation-state` — Use useMutationState for cross-component tracking + +### Error Handling (Prefix: `err-`) + +- `err-error-boundaries` — Use error boundaries with useQueryErrorResetBoundary +- `err-retry-config` — Configure retry logic appropriately +- `err-fallback-data` — Provide fallback data when appropriate + +### Prefetching (Prefix: `pf-`) + +- `pf-intent-prefetch` — Prefetch on user intent (hover, focus) +- `pf-route-prefetch` — Prefetch data during route transitions +- `pf-stale-time-config` — Set staleTime when prefetching +- `pf-ensure-query-data` — Use ensureQueryData for conditional prefetching + +### Infinite Queries (Prefix: `inf-`) + +- `inf-page-params` — Always provide getNextPageParam +- `inf-loading-guards` — Check isFetchingNextPage before fetching more +- `inf-max-pages` — Consider maxPages for large datasets + +### SSR Integration (Prefix: `ssr-`) + +- `ssr-dehydration` — Use dehydrate/hydrate pattern for SSR +- `ssr-client-per-request` — Create QueryClient per request +- `ssr-stale-time-server` — Set higher staleTime on server +- `ssr-hydration-boundary` — Wrap with HydrationBoundary + +### Parallel Queries (Prefix: `parallel-`) + +- `parallel-use-queries` — Use useQueries for dynamic parallel queries +- `query-cancellation` — Implement query cancellation properly + +### Performance (Prefix: `perf-`) + +- `perf-select-transform` — Use select to transform/filter data +- `perf-structural-sharing` — Leverage structural sharing +- `perf-notify-change-props` — Limit re-renders with notifyOnChangeProps +- `perf-placeholder-data` — Use placeholderData for instant UI + +### Offline Support (Prefix: `offline-`) + +- `network-mode` — Configure network mode for offline support +- `persist-queries` — Configure query persistence for offline support + +## How to Use + +Each rule file in the `rules/` directory contains: +1. **Explanation** — Why this pattern matters +2. **Bad Example** — Anti-pattern to avoid +3. **Good Example** — Recommended implementation +4. **Context** — When to apply or skip this rule + +## Full Reference + +See individual rule files in `rules/` directory for detailed guidance and code examples. diff --git a/.agents/skills/tanstack-query-best-practices/rules/cache-gc-time.md b/.agents/skills/tanstack-query-best-practices/rules/cache-gc-time.md new file mode 100644 index 00000000..7f8f7697 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/cache-gc-time.md @@ -0,0 +1,93 @@ +# cache-gc-time: Configure gcTime for Inactive Query Retention + +## Priority: CRITICAL + +## Explanation + +`gcTime` (garbage collection time, formerly `cacheTime`) controls how long inactive queries remain in the cache before being garbage collected. Default is 5 minutes. Configure based on your navigation patterns and memory constraints. + +## Bad Example + +```tsx +// Not considering gcTime for frequently revisited pages +const { data } = useQuery({ + queryKey: ['dashboard-stats'], + queryFn: fetchDashboardStats, + // Default gcTime of 5 minutes - might be too short for frequently revisited data +}) + +// Setting gcTime too high without consideration +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + gcTime: Infinity, // Never garbage collect - potential memory leak + }, + }, +}) + +// Setting gcTime to 0 - cache is immediately removed +const { data } = useQuery({ + queryKey: ['user-data'], + queryFn: fetchUserData, + gcTime: 0, // Loses cache benefits entirely +}) +``` + +## Good Example + +```tsx +// Longer gcTime for frequently revisited data +const { data } = useQuery({ + queryKey: ['dashboard-stats'], + queryFn: fetchDashboardStats, + gcTime: 30 * 60 * 1000, // 30 minutes - user returns to dashboard often +}) + +// Shorter gcTime for rarely revisited large data +const { data: report } = useQuery({ + queryKey: ['detailed-report', reportId], + queryFn: () => fetchReport(reportId), + gcTime: 2 * 60 * 1000, // 2 minutes - large payload, viewed once +}) + +// Sensible default with query-specific overrides +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + gcTime: 10 * 60 * 1000, // 10 minutes default + }, + }, +}) +``` + +## Understanding gcTime vs staleTime + +``` +Query Mount → Data Fresh (staleTime) → Data Stale → Query Unmount → gcTime countdown → Garbage Collected + +Timeline example (staleTime: 1min, gcTime: 5min): +0:00 - Query mounts, fetches data +0:00-1:00 - Data is fresh (no background refetch) +1:00+ - Data is stale (background refetch on new mount) +5:00 - User navigates away, query unmounts +5:00-10:00 - Data in cache but inactive (gcTime countdown) +10:00 - Data garbage collected (next mount = full loading state) +``` + +## Recommended gcTime Values + +| Scenario | gcTime | Rationale | +|----------|--------|-----------| +| Frequently revisited routes | 15 - 30min | Instant navigation | +| Detail pages (viewed once) | 2 - 5min | Memory efficient | +| Large payloads | 1 - 2min | Prevent memory bloat | +| Critical user data | 30min+ | Offline-like experience | +| SSR hydration | >= 2s | Prevent hydration issues | + +## Context + +- gcTime countdown starts when ALL query observers unmount +- Remounting before gcTime expires returns cached data instantly +- Setting gcTime < staleTime is rarely useful +- For SSR, avoid gcTime: 0 (use minimum 2000ms to allow hydration) +- Monitor memory usage in long-running applications diff --git a/.agents/skills/tanstack-query-best-practices/rules/cache-invalidation.md b/.agents/skills/tanstack-query-best-practices/rules/cache-invalidation.md new file mode 100644 index 00000000..51172f60 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/cache-invalidation.md @@ -0,0 +1,116 @@ +# cache-invalidation: Use Targeted Invalidation Over Broad Patterns + +## Priority: CRITICAL + +## Explanation + +Query invalidation marks cached data as stale, triggering background refetches. Use targeted invalidation to refresh only affected data. Overly broad invalidation causes unnecessary network requests; too narrow invalidation leaves stale data. + +## Bad Example + +```tsx +// Invalidating everything after a single todo update +const mutation = useMutation({ + mutationFn: updateTodo, + onSuccess: () => { + queryClient.invalidateQueries() // Invalidates ENTIRE cache + }, +}) + +// Invalidating too broadly +const mutation = useMutation({ + mutationFn: updateTodoStatus, + onSuccess: () => { + // Invalidates all todos including unrelated lists + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, +}) + +// Missing invalidation of related queries +const mutation = useMutation({ + mutationFn: addComment, + onSuccess: () => { + // Only invalidates comment list, misses comment count + queryClient.invalidateQueries({ queryKey: ['comments', postId] }) + }, +}) +``` + +## Good Example + +```tsx +// Targeted invalidation with exact matching +const mutation = useMutation({ + mutationFn: updateTodo, + onSuccess: (data, variables) => { + // Invalidate specific todo and related queries + queryClient.invalidateQueries({ queryKey: ['todos', variables.id] }) + // Also invalidate lists that might contain this todo + queryClient.invalidateQueries({ queryKey: ['todos', 'list'] }) + }, +}) + +// Use exact: true when you only want one specific query +const mutation = useMutation({ + mutationFn: updateUserProfile, + onSuccess: () => { + queryClient.invalidateQueries({ + queryKey: ['user', 'profile'], + exact: true, // Only this exact key, not ['user', 'profile', 'settings'] + }) + }, +}) + +// Invalidate multiple related queries +const mutation = useMutation({ + mutationFn: addComment, + onSuccess: (data, { postId }) => { + // Invalidate all comment-related queries for this post + queryClient.invalidateQueries({ queryKey: ['posts', postId, 'comments'] }) + queryClient.invalidateQueries({ queryKey: ['posts', postId, 'comment-count'] }) + // Optionally invalidate the post itself if it shows comment count + queryClient.invalidateQueries({ queryKey: ['posts', postId] }) + }, +}) + +// Predicate-based invalidation for complex scenarios +queryClient.invalidateQueries({ + predicate: (query) => + query.queryKey[0] === 'todos' && + query.state.data?.userId === currentUserId, +}) +``` + +## Invalidation Patterns + +```tsx +// Prefix matching (default) - invalidates all matching prefixes +queryClient.invalidateQueries({ queryKey: ['todos'] }) +// Matches: ['todos'], ['todos', 1], ['todos', { status: 'done' }] + +// Exact matching - only the exact key +queryClient.invalidateQueries({ queryKey: ['todos'], exact: true }) +// Matches: ['todos'] only + +// Predicate matching - custom logic +queryClient.invalidateQueries({ + predicate: (query) => query.queryKey.includes('user-generated'), +}) + +// Refetch type control +queryClient.invalidateQueries({ + queryKey: ['todos'], + refetchType: 'active', // Only refetch active queries (default) + // refetchType: 'inactive' - Only inactive + // refetchType: 'all' - Both + // refetchType: 'none' - Mark stale but don't refetch +}) +``` + +## Context + +- Invalidation only marks queries as stale; refetch happens when query is used +- `refetchType: 'active'` (default) only refetches queries with active observers +- Use hierarchical query keys to enable precise invalidation +- Consider `setQueryData` for optimistic updates instead of invalidation +- Always test invalidation patterns to ensure all affected queries are refreshed diff --git a/.agents/skills/tanstack-query-best-practices/rules/cache-placeholder-vs-initial.md b/.agents/skills/tanstack-query-best-practices/rules/cache-placeholder-vs-initial.md new file mode 100644 index 00000000..0d169b25 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/cache-placeholder-vs-initial.md @@ -0,0 +1,156 @@ +# cache-placeholder-vs-initial: Understand Placeholder vs Initial Data + +## Priority: MEDIUM + +## Explanation + +`placeholderData` and `initialData` both provide data before the fetch completes, but behave differently. `initialData` is treated as real cached data, while `placeholderData` is temporary and doesn't persist to cache. Choose based on whether your fallback data should be cached. + +## Bad Example + +```tsx +// Using initialData when you don't want it cached +function PostPreview({ postId, previewData }: Props) { + const { data } = useQuery({ + queryKey: ['posts', postId], + queryFn: () => fetchPost(postId), + initialData: previewData, // Wrong: this becomes cached "truth" + // If previewData is incomplete, it pollutes the cache + // staleTime applies to this data as if it were fetched + }) +} + +// Using placeholderData when you want persistence +function UserProfile({ userId }: Props) { + const { data } = useQuery({ + queryKey: ['users', userId], + queryFn: () => fetchUser(userId), + placeholderData: cachedUserFromList, // Wrong: won't persist + // User navigates away and back - placeholder shown again + // No cache entry created until fetch completes + }) +} +``` + +## Good Example: placeholderData for Temporary Display + +```tsx +// Show list data while fetching detail +function PostDetail({ postId }: { postId: string }) { + const queryClient = useQueryClient() + + const { data, isPlaceholderData } = useQuery({ + queryKey: ['posts', postId], + queryFn: () => fetchPost(postId), + placeholderData: () => { + // Use partial data from list cache as placeholder + const posts = queryClient.getQueryData(['posts']) + return posts?.find(p => p.id === postId) + }, + }) + + return ( +
+

{data?.title}

+ {isPlaceholderData ? ( +

Loading full content...

+ ) : ( +
{data?.content}
+ )} +
+ ) +} +``` + +## Good Example: initialData for Known Good Data + +```tsx +// SSR: Data fetched on server should be initial +function PostPage({ serverData }: { serverData: Post }) { + const { data } = useQuery({ + queryKey: ['posts', serverData.id], + queryFn: () => fetchPost(serverData.id), + initialData: serverData, + // Specify when this data was fetched for proper stale calculation + initialDataUpdatedAt: serverData.fetchedAt, + }) + + return +} + +// Pre-seeding cache with complete data +function App() { + const queryClient = useQueryClient() + + // If you have complete, authoritative data + useEffect(() => { + queryClient.setQueryData(['config'], completeConfigData) + }, []) +} +``` + +## Good Example: keepPreviousData Pattern + +```tsx +// Keep showing old data while fetching new (pagination, filters) +function ProductList({ page }: { page: number }) { + const { data, isPlaceholderData } = useQuery({ + queryKey: ['products', page], + queryFn: () => fetchProducts(page), + placeholderData: keepPreviousData, // Built-in helper + }) + + return ( +
+ {data?.map(product => ( + + ))} + {isPlaceholderData && } +
+ ) +} +``` + +## Comparison Table + +| Behavior | `initialData` | `placeholderData` | +|----------|---------------|-------------------| +| Persisted to cache | Yes | No | +| `staleTime` applies | Yes | No (always fetches) | +| `isPlaceholderData` | `false` | `true` | +| Shown to other components | Yes (cached) | No | +| Use case | SSR, complete known data | Preview, previous page | +| Affects `dataUpdatedAt` | Yes (use `initialDataUpdatedAt`) | No | + +## Good Example: Combining Both + +```tsx +function PostDetail({ postId, ssrData }: Props) { + const queryClient = useQueryClient() + + const { data } = useQuery({ + queryKey: ['posts', postId], + queryFn: () => fetchPost(postId), + + // If we have SSR data, use as initial (cached) + initialData: ssrData, + initialDataUpdatedAt: ssrData?.fetchedAt, + + // If no SSR data, try to use list preview as placeholder + placeholderData: () => { + if (ssrData) return undefined // Already have initial + const posts = queryClient.getQueryData(['posts']) + return posts?.find(p => p.id === postId) + }, + }) +} +``` + +## Context + +- `placeholderData` can be a value or function (lazy evaluation) +- `initialData` affects cache immediately on query creation +- Use `initialDataUpdatedAt` with `initialData` for proper stale calculations +- `keepPreviousData` is a built-in placeholder strategy +- Check `isPlaceholderData` to show loading indicators +- `placeholderData` is ideal for "instant" UI while fetching diff --git a/.agents/skills/tanstack-query-best-practices/rules/cache-stale-time.md b/.agents/skills/tanstack-query-best-practices/rules/cache-stale-time.md new file mode 100644 index 00000000..fa38fe44 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/cache-stale-time.md @@ -0,0 +1,80 @@ +# cache-stale-time: Set Appropriate staleTime Based on Data Volatility + +## Priority: CRITICAL + +## Explanation + +`staleTime` determines how long data is considered fresh. The default is 0ms, meaning data is immediately stale and will refetch on every new query mount. Set appropriate staleTime based on how often your data actually changes to reduce unnecessary network requests. + +## Bad Example + +```tsx +// Default staleTime of 0 - refetches on every component mount +const { data } = useQuery({ + queryKey: ['user-profile', userId], + queryFn: () => fetchUserProfile(userId), + // No staleTime set - always considered stale +}) + +// User profile probably doesn't change every second +// This causes unnecessary API calls on navigation + +// Setting same staleTime everywhere regardless of data type +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 60 * 1000, // 1 minute for everything - too simple + }, + }, +}) +``` + +## Good Example + +```tsx +// Match staleTime to data volatility +const { data: profile } = useQuery({ + queryKey: ['user-profile', userId], + queryFn: () => fetchUserProfile(userId), + staleTime: 5 * 60 * 1000, // 5 minutes - profile rarely changes +}) + +const { data: notifications } = useQuery({ + queryKey: ['notifications'], + queryFn: fetchNotifications, + staleTime: 30 * 1000, // 30 seconds - changes more frequently +}) + +const { data: stockPrice } = useQuery({ + queryKey: ['stock', symbol], + queryFn: () => fetchStockPrice(symbol), + staleTime: 0, // Real-time data - always refetch +}) + +// Set sensible defaults, override per-query +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 60 * 1000, // 1 minute default + }, + }, +}) +``` + +## Recommended staleTime Values + +| Data Type | staleTime | Rationale | +|-----------|-----------|-----------| +| Real-time (stocks, live feeds) | 0 | Must always be current | +| Frequently changing (notifications) | 30s - 1min | Balance freshness and requests | +| User-generated content | 1 - 5min | Changes on user action | +| Reference data (categories, config) | 10 - 30min | Rarely changes | +| Static content | Infinity | Never changes | + +## Context + +- `staleTime: 0` (default) triggers background refetch on every mount +- `staleTime: Infinity` never considers data stale (manual invalidation only) +- Stale data is still returned instantly - refetch happens in background +- For SSR, set higher staleTime to avoid immediate client refetch +- Consider using `queryOptions` factory to centralize staleTime per data type diff --git a/.agents/skills/tanstack-query-best-practices/rules/err-error-boundaries.md b/.agents/skills/tanstack-query-best-practices/rules/err-error-boundaries.md new file mode 100644 index 00000000..02095617 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/err-error-boundaries.md @@ -0,0 +1,150 @@ +# err-error-boundaries: Use Error Boundaries with useQueryErrorResetBoundary + +## Priority: HIGH + +## Explanation + +When using Suspense with TanStack Query, errors propagate to error boundaries. Use `useQueryErrorResetBoundary` to reset query errors when users retry, preventing stuck error states. + +## Bad Example + +```tsx +// Error boundary without query reset - retry may not work +function ErrorBoundary({ children }: { children: React.ReactNode }) { + return ( + ( +
+

Error: {error.message}

+ + {/* resetErrorBoundary alone doesn't reset query state */} +
+ )} + > + {children} +
+ ) +} + +// Query error persists after retry click +``` + +## Good Example + +```tsx +import { useQueryErrorResetBoundary } from '@tanstack/react-query' +import { ErrorBoundary } from 'react-error-boundary' + +function QueryErrorBoundary({ children }: { children: React.ReactNode }) { + const { reset } = useQueryErrorResetBoundary() + + return ( + ( +
+

Something went wrong

+
{error.message}
+ +
+ )} + > + {children} +
+ ) +} + +// Usage with Suspense +function App() { + return ( + + }> + + + + ) +} + +function Posts() { + // useSuspenseQuery throws on error, caught by boundary + const { data } = useSuspenseQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + return +} +``` + +## Good Example: With TanStack Router + +```tsx +// Route-level error handling +import { createFileRoute } from '@tanstack/react-router' +import { useQueryErrorResetBoundary } from '@tanstack/react-query' + +export const Route = createFileRoute('/posts')({ + loader: ({ context: { queryClient } }) => + queryClient.ensureQueryData(postQueries.list()), + + errorComponent: ({ error, reset }) => { + const { reset: resetQuery } = useQueryErrorResetBoundary() + + return ( +
+

Failed to load posts: {error.message}

+ +
+ ) + }, + + component: PostsPage, +}) +``` + +## Error Boundary Placement Strategy + +```tsx +// Granular error boundaries for isolated failures +function Dashboard() { + return ( +
+ {/* Each section can fail independently */} + + }> + + + + + + }> + + + + + + }> + + + +
+ ) +} +``` + +## Context + +- `useQueryErrorResetBoundary` clears error state for all queries in the boundary +- Always pair Suspense queries with error boundaries +- Place boundaries based on failure isolation needs +- Consider inline error handling for non-critical data +- The reset only affects queries that were in error state diff --git a/.agents/skills/tanstack-query-best-practices/rules/inf-page-params.md b/.agents/skills/tanstack-query-best-practices/rules/inf-page-params.md new file mode 100644 index 00000000..7a1ccf59 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/inf-page-params.md @@ -0,0 +1,132 @@ +# inf-page-params: Always Provide getNextPageParam for Infinite Queries + +## Priority: MEDIUM + +## Explanation + +`useInfiniteQuery` requires `getNextPageParam` to determine how to fetch subsequent pages. This function receives the last page's data and must return the next page parameter, or `undefined` when there are no more pages. + +## Bad Example + +```tsx +// Missing getNextPageParam - can't load more pages +const { data, fetchNextPage } = useInfiniteQuery({ + queryKey: ['posts'], + queryFn: ({ pageParam }) => fetchPosts(pageParam), + initialPageParam: 1, + // Missing getNextPageParam - fetchNextPage won't work correctly +}) +``` + +## Good Example: Offset-Based Pagination + +```tsx +const { + data, + fetchNextPage, + hasNextPage, + isFetchingNextPage, +} = useInfiniteQuery({ + queryKey: ['posts'], + queryFn: ({ pageParam }) => fetchPosts({ page: pageParam, limit: 20 }), + initialPageParam: 1, + getNextPageParam: (lastPage, allPages) => { + // Return next page number, or undefined if no more pages + if (lastPage.length < 20) { + return undefined // No more pages + } + return allPages.length + 1 + }, +}) +``` + +## Good Example: Cursor-Based Pagination + +```tsx +interface PostsResponse { + posts: Post[] + nextCursor: string | null +} + +const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({ + queryKey: ['posts'], + queryFn: ({ pageParam }): Promise => + fetchPosts({ cursor: pageParam }), + initialPageParam: undefined as string | undefined, + getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined, +}) +``` + +## Good Example: Bi-directional Pagination + +```tsx +const { data, fetchNextPage, fetchPreviousPage, hasNextPage, hasPreviousPage } = + useInfiniteQuery({ + queryKey: ['messages', chatId], + queryFn: ({ pageParam }) => fetchMessages({ chatId, cursor: pageParam }), + initialPageParam: { direction: 'initial' } as PageParam, + getNextPageParam: (lastPage) => + lastPage.hasMore ? { cursor: lastPage.nextCursor, direction: 'next' } : undefined, + getPreviousPageParam: (firstPage) => + firstPage.hasPrevious + ? { cursor: firstPage.prevCursor, direction: 'prev' } + : undefined, + }) +``` + +## Good Example: With Total Count + +```tsx +interface PaginatedResponse { + items: T[] + total: number + page: number + pageSize: number +} + +const { data, hasNextPage } = useInfiniteQuery({ + queryKey: ['products', filters], + queryFn: ({ pageParam }) => + fetchProducts({ ...filters, page: pageParam, pageSize: 20 }), + initialPageParam: 1, + getNextPageParam: (lastPage) => { + const totalPages = Math.ceil(lastPage.total / lastPage.pageSize) + if (lastPage.page < totalPages) { + return lastPage.page + 1 + } + return undefined + }, +}) +``` + +## Accessing Flattened Data + +```tsx +// data.pages is an array of page responses +// Flatten for easier iteration +const allPosts = data?.pages.flatMap(page => page.posts) ?? [] + +return ( +
+ {allPosts.map(post => ( + + ))} + {hasNextPage && ( + + )} +
+) +``` + +## Context + +- `getNextPageParam` returning `undefined` sets `hasNextPage` to `false` +- For bi-directional scrolling, also provide `getPreviousPageParam` +- `initialPageParam` is required and sets the first page parameter +- Use `maxPages` option to limit stored pages for memory management +- Consider `select` to transform page structure for component consumption diff --git a/.agents/skills/tanstack-query-best-practices/rules/mut-invalidate-queries.md b/.agents/skills/tanstack-query-best-practices/rules/mut-invalidate-queries.md new file mode 100644 index 00000000..b2de2ab5 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/mut-invalidate-queries.md @@ -0,0 +1,118 @@ +# mut-invalidate-queries: Always Invalidate Related Queries After Mutations + +## Priority: HIGH + +## Explanation + +After mutations, invalidate all queries whose data might be affected. This ensures the cache stays synchronized with the server. Forgetting to invalidate related queries leads to stale UI data. + +## Bad Example + +```tsx +// No invalidation - cache remains stale +const createTodo = useMutation({ + mutationFn: (newTodo) => api.createTodo(newTodo), + // Missing onSuccess handler - todo list won't show new item +}) + +// Partial invalidation - misses related queries +const deleteTodo = useMutation({ + mutationFn: (todoId) => api.deleteTodo(todoId), + onSuccess: () => { + // Only invalidates list, not summary/counts + queryClient.invalidateQueries({ queryKey: ['todos', 'list'] }) + // Missing: ['todos', 'count'], ['todos', 'completed-count'], etc. + }, +}) +``` + +## Good Example + +```tsx +// Comprehensive invalidation +const createTodo = useMutation({ + mutationFn: (newTodo) => api.createTodo(newTodo), + onSuccess: () => { + // Invalidate all todo-related queries + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, +}) + +// Targeted invalidation with all affected queries +const updateTodo = useMutation({ + mutationFn: ({ id, data }) => api.updateTodo(id, data), + onSuccess: (data, { id }) => { + // Specific todo + queryClient.invalidateQueries({ queryKey: ['todos', id] }) + // Lists that might contain this todo + queryClient.invalidateQueries({ queryKey: ['todos', 'list'] }) + // If todo status changed, invalidate filtered views + queryClient.invalidateQueries({ queryKey: ['todos', 'completed'] }) + queryClient.invalidateQueries({ queryKey: ['todos', 'active'] }) + }, +}) + +// Cross-entity invalidation +const assignTodoToUser = useMutation({ + mutationFn: ({ todoId, userId }) => api.assignTodo(todoId, userId), + onSuccess: (data, { todoId, userId }) => { + // Invalidate the todo + queryClient.invalidateQueries({ queryKey: ['todos', todoId] }) + // Invalidate user's assigned todos + queryClient.invalidateQueries({ queryKey: ['users', userId, 'todos'] }) + // Invalidate previous assignee's list if available + if (data.previousAssignee) { + queryClient.invalidateQueries({ + queryKey: ['users', data.previousAssignee, 'todos'], + }) + } + }, +}) +``` + +## Pattern: Mutation with Variables Access + +```tsx +const mutation = useMutation({ + mutationFn: updatePost, + onSuccess: ( + data, // Server response + variables, // What you passed to mutate() + context // What onMutate returned + ) => { + // Use variables to know which queries to invalidate + queryClient.invalidateQueries({ queryKey: ['posts', variables.id] }) + queryClient.invalidateQueries({ queryKey: ['posts', 'list', variables.category] }) + }, +}) +``` + +## Pattern: Invalidate or Update Directly + +```tsx +// Option 1: Invalidate and refetch +onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['todos'] }) +} + +// Option 2: Update cache directly (no network request) +onSuccess: (newTodo) => { + queryClient.setQueryData(['todos'], (old: Todo[]) => [...old, newTodo]) +} + +// Option 3: Hybrid - update one, invalidate others +onSuccess: (newTodo) => { + // Immediately add to list + queryClient.setQueryData(['todos', 'list'], (old: Todo[]) => [...old, newTodo]) + // Invalidate counts/summaries for eventual consistency + queryClient.invalidateQueries({ queryKey: ['todos', 'count'] }) +} +``` + +## Context + +- Place invalidation in `onSuccess` for successful mutations +- Use `onSettled` if you want to invalidate regardless of success/failure +- Think about all UI surfaces that display related data +- For complex relationships, consider a centralized invalidation helper +- Using hierarchical query keys makes this easier (see `qk-hierarchical-organization`) diff --git a/.agents/skills/tanstack-query-best-practices/rules/mut-mutation-state.md b/.agents/skills/tanstack-query-best-practices/rules/mut-mutation-state.md new file mode 100644 index 00000000..ea050c7b --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/mut-mutation-state.md @@ -0,0 +1,169 @@ +# mut-mutation-state: Use useMutationState for Cross-Component Mutation Tracking + +## Priority: MEDIUM + +## Explanation + +`useMutationState` allows you to access mutation state from anywhere in your component tree, not just where `useMutation` was called. Use it to show loading indicators, display optimistic updates, or track pending mutations across components. + +## Bad Example + +```tsx +// Prop drilling mutation state +function App() { + const mutation = useMutation({ mutationFn: createPost }) + + return ( +
+
+ + +
+
+ ) +} + +// Or using context for every mutation +const MutationContext = createContext(null) +``` + +## Good Example + +```tsx +// Define mutation with a key +const useCreatePost = () => useMutation({ + mutationKey: ['create-post'], + mutationFn: createPost, +}) + +// In the component that triggers mutation +function CreatePostButton() { + const mutation = useCreatePost() + + return ( + + ) +} + +// In any other component - track mutation state +function GlobalLoadingIndicator() { + const pendingMutations = useMutationState({ + filters: { status: 'pending' }, + select: (mutation) => mutation.state.variables, + }) + + if (pendingMutations.length === 0) return null + + return ( +
+ Saving {pendingMutations.length} item(s)... +
+ ) +} +``` + +## Good Example: Optimistic UI in Separate Component + +```tsx +// Mutation defined in form +function TodoForm() { + const createTodo = useMutation({ + mutationKey: ['create-todo'], + mutationFn: (todo: NewTodo) => api.createTodo(todo), + }) + + return ... +} + +// Optimistic display in list (different component) +function TodoList() { + const { data: todos } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos }) + + // Get pending todo creations + const pendingTodos = useMutationState({ + filters: { + mutationKey: ['create-todo'], + status: 'pending', + }, + select: (mutation) => mutation.state.variables as NewTodo, + }) + + return ( +
    + {/* Existing todos */} + {todos?.map(todo => ( + + ))} + + {/* Optimistic todos (pending creation) */} + {pendingTodos.map((todo, index) => ( + + ))} +
+ ) +} +``` + +## Good Example: Track Specific Mutations + +```tsx +function PostActions({ postId }: { postId: string }) { + // Track if THIS post is being deleted + const isDeletingThisPost = useMutationState({ + filters: { + mutationKey: ['delete-post', postId], + status: 'pending', + }, + select: () => true, + }).length > 0 + + // Track if THIS post is being updated + const isUpdatingThisPost = useMutationState({ + filters: { + mutationKey: ['update-post', postId], + status: 'pending', + }, + select: () => true, + }).length > 0 + + return ( +
+ +
+ ) +} +``` + +## Filters Reference + +```tsx +useMutationState({ + filters: { + mutationKey: ['key'], // Match mutation key + status: 'pending', // 'idle' | 'pending' | 'success' | 'error' + predicate: (mutation) => bool, // Custom filter function + }, + select: (mutation) => { + // Transform each matching mutation + // mutation.state contains: variables, data, error, status, etc. + return mutation.state.variables + }, +}) +``` + +## Context + +- Requires `mutationKey` on mutations you want to track +- Returns array of selected values from matching mutations +- Updates reactively as mutations progress +- Use `status` filter to track pending/success/error states +- Enables optimistic UI without prop drilling +- Pairs with `mutationKey` arrays for granular tracking (e.g., `['delete-post', postId]`) diff --git a/.agents/skills/tanstack-query-best-practices/rules/mut-optimistic-updates.md b/.agents/skills/tanstack-query-best-practices/rules/mut-optimistic-updates.md new file mode 100644 index 00000000..89e92358 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/mut-optimistic-updates.md @@ -0,0 +1,137 @@ +# mut-optimistic-updates: Implement Optimistic Updates for Responsive UI + +## Priority: HIGH + +## Explanation + +Optimistic updates immediately reflect changes in the UI before the server confirms them, creating a snappy user experience. Implement them for user-initiated mutations where the expected outcome is predictable. + +## Bad Example + +```tsx +// No optimistic update - UI waits for server response +const mutation = useMutation({ + mutationFn: toggleTodoComplete, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, +}) + +// User clicks checkbox, waits 200-500ms for visual feedback +``` + +## Good Example: Via Cache Manipulation + +```tsx +const mutation = useMutation({ + mutationFn: toggleTodoComplete, + onMutate: async (todoId) => { + // 1. Cancel outgoing refetches to prevent overwriting optimistic update + await queryClient.cancelQueries({ queryKey: ['todos'] }) + + // 2. Snapshot previous value for potential rollback + const previousTodos = queryClient.getQueryData(['todos']) + + // 3. Optimistically update the cache + queryClient.setQueryData(['todos'], (old: Todo[]) => + old.map((todo) => + todo.id === todoId ? { ...todo, completed: !todo.completed } : todo + ) + ) + + // 4. Return context for rollback + return { previousTodos } + }, + onError: (err, todoId, context) => { + // Rollback on error + queryClient.setQueryData(['todos'], context?.previousTodos) + }, + onSettled: () => { + // Refetch to ensure consistency regardless of success/failure + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, +}) +``` + +## Good Example: Via UI Variables (Simpler) + +```tsx +// When mutation only affects local UI, use mutation state directly +function TodoItem({ todo }: { todo: Todo }) { + const mutation = useMutation({ + mutationFn: toggleTodoComplete, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, + }) + + // Show optimistic state while pending + const displayCompleted = mutation.isPending + ? !todo.completed // Optimistic: show toggled state + : todo.completed // Settled: show actual state + + return ( +
+ mutation.mutate(todo.id)} + /> + + {todo.title} + +
+ ) +} +``` + +## Good Example: Optimistic Create with Temporary ID + +```tsx +const createTodo = useMutation({ + mutationFn: (newTodo: CreateTodoInput) => api.createTodo(newTodo), + onMutate: async (newTodo) => { + await queryClient.cancelQueries({ queryKey: ['todos'] }) + const previousTodos = queryClient.getQueryData(['todos']) + + // Add with temporary ID + const optimisticTodo = { + id: `temp-${Date.now()}`, + ...newTodo, + completed: false, + createdAt: new Date().toISOString(), + } + + queryClient.setQueryData(['todos'], (old: Todo[]) => [...old, optimisticTodo]) + + return { previousTodos, optimisticTodo } + }, + onError: (err, newTodo, context) => { + queryClient.setQueryData(['todos'], context?.previousTodos) + }, + onSuccess: (data, variables, context) => { + // Replace temp todo with real one + queryClient.setQueryData(['todos'], (old: Todo[]) => + old.map((todo) => + todo.id === context?.optimisticTodo.id ? data : todo + ) + ) + }, +}) +``` + +## When to Use Each Approach + +| Approach | Use When | +|----------|----------| +| Cache Manipulation | Update appears in multiple places, complex data structures | +| UI Variables | Update only visible in one component, simpler implementation | + +## Context + +- Always provide rollback logic in `onError` +- Cancel queries before optimistic update to prevent race conditions +- Call `invalidateQueries` in `onSettled` to sync with server truth +- For forms, consider if validation should block optimistic display +- Test error scenarios to verify rollback works correctly diff --git a/.agents/skills/tanstack-query-best-practices/rules/network-mode.md b/.agents/skills/tanstack-query-best-practices/rules/network-mode.md new file mode 100644 index 00000000..02217afe --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/network-mode.md @@ -0,0 +1,179 @@ +# network-mode: Configure Network Mode for Offline Support + +## Priority: LOW + +## Explanation + +TanStack Query's `networkMode` controls how queries and mutations behave when there's no network connection. Configure it based on your app's offline requirements: always fetch, pause when offline, or work entirely offline. + +## Bad Example + +```tsx +// Not considering offline behavior +const { data } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + // Default networkMode: 'online' + // Query pauses with no feedback when offline +}) + +// User goes offline, sees stale data with no indication +// Mutations silently queue with no UI feedback +``` + +## Good Example: Default Online Mode with Offline UI + +```tsx +// Show clear offline state to users +function TodoList() { + const { data, fetchStatus, status } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + networkMode: 'online', // Default - pauses when offline + }) + + // fetchStatus: 'fetching' | 'paused' | 'idle' + // 'paused' means waiting for network + + return ( +
+ {fetchStatus === 'paused' && ( + You're offline. Showing cached data. + )} + +
+ ) +} +``` + +## Good Example: Always Mode for Offline-First + +```tsx +// App works offline with local data +const { data, error } = useQuery({ + queryKey: ['todos'], + queryFn: async () => { + // Try network first + try { + const todos = await fetchTodosFromServer() + await saveToLocalDB(todos) // Sync to local + return todos + } catch (e) { + // Fall back to local data + return getFromLocalDB() + } + }, + networkMode: 'always', // Always runs queryFn, even offline +}) + +// Or set globally +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + networkMode: 'always', + }, + mutations: { + networkMode: 'always', + }, + }, +}) +``` + +## Good Example: Offline-First Mode + +```tsx +// Only fetch when online, but don't fail when offline +const { data } = useQuery({ + queryKey: ['user-preferences'], + queryFn: fetchPreferences, + networkMode: 'offlineFirst', + // Runs queryFn once, then waits for network if it fails + // Good for: data that's useful to attempt offline +}) +``` + +## Good Example: Mutation Offline Queue + +```tsx +function TodoApp() { + const queryClient = useQueryClient() + + const addTodo = useMutation({ + mutationFn: createTodo, + networkMode: 'online', // Pauses when offline + onMutate: async (newTodo) => { + // Optimistic update works offline + await queryClient.cancelQueries({ queryKey: ['todos'] }) + const previous = queryClient.getQueryData(['todos']) + queryClient.setQueryData(['todos'], (old: Todo[]) => [...old, newTodo]) + return { previous } + }, + onError: (err, newTodo, context) => { + queryClient.setQueryData(['todos'], context?.previous) + }, + onSettled: () => { + queryClient.invalidateQueries({ queryKey: ['todos'] }) + }, + }) + + // Track paused mutations + const pendingMutations = useMutationState({ + filters: { status: 'pending' }, + }) + + const pausedMutations = pendingMutations.filter( + m => m.state.isPaused + ) + + return ( +
+ {pausedMutations.length > 0 && ( + + {pausedMutations.length} changes waiting to sync + + )} + +
+ ) +} +``` + +## Network Mode Comparison + +| Mode | Behavior | Use Case | +|------|----------|----------| +| `'online'` (default) | Pauses when offline, resumes when online | Most apps, show offline state | +| `'always'` | Always runs queryFn regardless of network | Offline-first apps, local-only data | +| `'offlineFirst'` | Tries once, then waits for network if fails | Best-effort offline | + +## Good Example: Online Status Detection + +```tsx +import { onlineManager } from '@tanstack/react-query' + +// React to online/offline changes +function NetworkStatus() { + const isOnline = useSyncExternalStore( + onlineManager.subscribe, + () => onlineManager.isOnline(), + ) + + return ( +
+ {isOnline ? 'Connected' : 'Offline'} +
+ ) +} + +// Manually override online detection (for testing) +onlineManager.setOnline(false) +``` + +## Context + +- Default `'online'` mode is best for most apps +- `fetchStatus: 'paused'` indicates waiting for network +- Mutations queue automatically and retry when back online +- Use `onlineManager` to detect and control online state +- Combine with optimistic updates for seamless offline UX +- Consider service workers for true offline support diff --git a/.agents/skills/tanstack-query-best-practices/rules/parallel-use-queries.md b/.agents/skills/tanstack-query-best-practices/rules/parallel-use-queries.md new file mode 100644 index 00000000..291dc313 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/parallel-use-queries.md @@ -0,0 +1,152 @@ +# parallel-use-queries: Use useQueries for Dynamic Parallel Queries + +## Priority: MEDIUM + +## Explanation + +When you need to fetch multiple queries in parallel where the number or identity of queries is dynamic (e.g., fetching details for a list of IDs), use `useQueries`. It handles parallel execution and returns an array of query results. + +## Bad Example + +```tsx +// Sequential fetching with useEffect - waterfall +function UserProfiles({ userIds }: { userIds: string[] }) { + const [users, setUsers] = useState([]) + const [loading, setLoading] = useState(true) + + useEffect(() => { + async function fetchAll() { + const results = [] + for (const id of userIds) { + const user = await fetchUser(id) // Sequential! + results.push(user) + } + setUsers(results) + setLoading(false) + } + fetchAll() + }, [userIds]) + + // N requests run one after another +} + +// Multiple useQuery calls - breaks rules of hooks +function UserProfiles({ userIds }: { userIds: string[] }) { + // Can't call hooks in a loop! + const queries = userIds.map(id => useQuery({ + queryKey: ['user', id], + queryFn: () => fetchUser(id), + })) +} +``` + +## Good Example + +```tsx +import { useQueries } from '@tanstack/react-query' + +function UserProfiles({ userIds }: { userIds: string[] }) { + const userQueries = useQueries({ + queries: userIds.map(id => ({ + queryKey: ['users', id], + queryFn: () => fetchUser(id), + staleTime: 5 * 60 * 1000, + })), + }) + + const isLoading = userQueries.some(q => q.isLoading) + const isError = userQueries.some(q => q.isError) + const users = userQueries.map(q => q.data).filter(Boolean) + + if (isLoading) return + if (isError) return + + return ( +
    + {users.map(user => ( +
  • {user.name}
  • + ))} +
+ ) +} +``` + +## Good Example: With Combine Option + +```tsx +function UserProfiles({ userIds }: { userIds: string[] }) { + const { data: users, isPending } = useQueries({ + queries: userIds.map(id => ({ + queryKey: ['users', id], + queryFn: () => fetchUser(id), + })), + // Combine results into single value + combine: (results) => ({ + data: results.map(r => r.data).filter(Boolean), + isPending: results.some(r => r.isPending), + isError: results.some(r => r.isError), + }), + }) + + if (isPending) return + + return +} +``` + +## Good Example: Dependent Parallel Queries + +```tsx +function PostsWithAuthors({ postIds }: { postIds: string[] }) { + // First: fetch all posts in parallel + const postQueries = useQueries({ + queries: postIds.map(id => ({ + queryKey: ['posts', id], + queryFn: () => fetchPost(id), + })), + }) + + const posts = postQueries.map(q => q.data).filter(Boolean) + const authorIds = [...new Set(posts.map(p => p.authorId))] + + // Then: fetch all unique authors in parallel + const authorQueries = useQueries({ + queries: authorIds.map(id => ({ + queryKey: ['users', id], + queryFn: () => fetchUser(id), + enabled: posts.length > 0, // Wait for posts + })), + }) + + // Combine data... +} +``` + +## Good Example: With Suspense + +```tsx +import { useSuspenseQueries } from '@tanstack/react-query' + +function UserProfiles({ userIds }: { userIds: string[] }) { + const userQueries = useSuspenseQueries({ + queries: userIds.map(id => ({ + queryKey: ['users', id], + queryFn: () => fetchUser(id), + })), + }) + + // All data guaranteed - no loading states needed + const users = userQueries.map(q => q.data) + + return +} +``` + +## Context + +- Queries run in parallel, not sequentially +- Each query is cached independently +- Use `combine` to transform results array into single value +- Empty queries array is valid (returns empty results) +- Pairs well with `useSuspenseQueries` for guaranteed data +- Individual query options (staleTime, etc.) apply per-query diff --git a/.agents/skills/tanstack-query-best-practices/rules/perf-select-transform.md b/.agents/skills/tanstack-query-best-practices/rules/perf-select-transform.md new file mode 100644 index 00000000..3fa69214 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/perf-select-transform.md @@ -0,0 +1,144 @@ +# perf-select-transform: Use Select to Transform and Filter Data + +## Priority: LOW + +## Explanation + +The `select` option transforms query data before it reaches your component. Use it for filtering, sorting, or deriving data. Benefits include memoization (re-runs only when data changes) and reduced component re-renders. + +## Bad Example + +```tsx +// Transforming in component - runs on every render +function CompletedTodos() { + const { data: todos } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + }) + + // This filtering runs on every render + const completedTodos = todos?.filter(todo => todo.completed) ?? [] + const sortedTodos = [...completedTodos].sort((a, b) => + new Date(b.completedAt).getTime() - new Date(a.completedAt).getTime() + ) + + return +} +``` + +## Good Example + +```tsx +// Using select - runs only when data changes +function CompletedTodos() { + const { data: completedTodos } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + select: (todos) => + todos + .filter(todo => todo.completed) + .sort((a, b) => + new Date(b.completedAt).getTime() - new Date(a.completedAt).getTime() + ), + }) + + return +} +``` + +## Good Example: Selecting Specific Fields + +```tsx +// Derive computed values +function TodoStats() { + const { data: stats } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + select: (todos) => ({ + total: todos.length, + completed: todos.filter(t => t.completed).length, + pending: todos.filter(t => !t.completed).length, + completionRate: todos.length + ? (todos.filter(t => t.completed).length / todos.length) * 100 + : 0, + }), + }) + + return ( +
+ {stats?.completed} / {stats?.total} completed + ({stats?.completionRate.toFixed(1)}%) +
+ ) +} +``` + +## Good Example: Stable Select with useCallback + +```tsx +// When select depends on external values, stabilize with useCallback +function FilteredTodos({ status }: { status: 'all' | 'active' | 'completed' }) { + const selectTodos = useCallback( + (todos: Todo[]) => { + switch (status) { + case 'active': + return todos.filter(t => !t.completed) + case 'completed': + return todos.filter(t => t.completed) + default: + return todos + } + }, + [status] + ) + + const { data: filteredTodos } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + select: selectTodos, + }) + + return +} +``` + +## Good Example: Picking Single Item from List + +```tsx +// Select single item from cached list +function useTodoById(id: number) { + return useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + select: (todos) => todos.find(todo => todo.id === id), + }) +} + +// Usage - shares cache with list query +function TodoDetail({ id }: { id: number }) { + const { data: todo } = useTodoById(id) + + if (!todo) return
Todo not found
+ return
{todo.title}
+} +``` + +## When to Use Select + +| Scenario | Use Select? | +|----------|-------------| +| Filtering list data | Yes | +| Sorting data | Yes | +| Computing derived values | Yes | +| Picking single item from list | Yes | +| Heavy transformations | Yes (memoized) | +| Simple data pass-through | No | +| Transformation needs external state | Yes, with useCallback | + +## Context + +- `select` leverages structural sharing - only re-runs when data actually changes +- Original query data stays cached; transformation applies to consumer +- Multiple components can use different `select` on the same query +- Avoid unstable function references - use `useCallback` when needed +- For complex transformations, consider useMemo in component instead if readability suffers diff --git a/.agents/skills/tanstack-query-best-practices/rules/persist-queries.md b/.agents/skills/tanstack-query-best-practices/rules/persist-queries.md new file mode 100644 index 00000000..282adafe --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/persist-queries.md @@ -0,0 +1,194 @@ +# persist-queries: Configure Query Persistence for Offline Support + +## Priority: LOW + +## Explanation + +TanStack Query can persist the cache to storage (localStorage, IndexedDB, AsyncStorage) and restore it on app load. This enables offline support and faster startup by eliminating initial loading states. + +## Bad Example + +```tsx +// No persistence - always starts fresh +const queryClient = new QueryClient() + +function App() { + return ( + + + + ) +} + +// User refreshes page: +// 1. Empty cache +// 2. Loading spinners everywhere +// 3. Refetch all data +// Poor offline experience +``` + +## Good Example: Basic Persistence with localStorage + +```tsx +import { QueryClient } from '@tanstack/react-query' +import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister' +import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + gcTime: 1000 * 60 * 60 * 24, // 24 hours - keep cache longer for persistence + staleTime: 1000 * 60 * 5, // 5 minutes + }, + }, +}) + +const persister = createSyncStoragePersister({ + storage: window.localStorage, + key: 'REACT_QUERY_CACHE', +}) + +function App() { + return ( + + + + ) +} +``` + +## Good Example: Async Persistence with IndexedDB + +```tsx +import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' +import { get, set, del } from 'idb-keyval' + +const persister = createAsyncStoragePersister({ + storage: { + getItem: async (key) => await get(key), + setItem: async (key, value) => await set(key, value), + removeItem: async (key) => await del(key), + }, + key: 'REACT_QUERY_CACHE', +}) + +function App() { + return ( + + + + ) +} +``` + +## Good Example: Selective Persistence + +```tsx +import { persistQueryClient } from '@tanstack/react-query-persist-client' + +const queryClient = new QueryClient({ + defaultOptions: { + queries: { + gcTime: 1000 * 60 * 60 * 24, + }, + }, +}) + +// Only persist certain queries +persistQueryClient({ + queryClient, + persister, + dehydrateOptions: { + shouldDehydrateQuery: (query) => { + // Don't persist user-specific sensitive data + if (query.queryKey[0] === 'user-session') return false + // Don't persist real-time data + if (query.queryKey[0] === 'notifications') return false + // Don't persist failed queries + if (query.state.status !== 'success') return false + // Persist everything else + return true + }, + }, +}) +``` + +## Good Example: React Native with AsyncStorage + +```tsx +import AsyncStorage from '@react-native-async-storage/async-storage' +import { createAsyncStoragePersister } from '@tanstack/query-async-storage-persister' + +const persister = createAsyncStoragePersister({ + storage: AsyncStorage, + key: 'app-query-cache', +}) + +// Usage is the same as web +``` + +## Good Example: Handling Restoration Loading + +```tsx +import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client' + +function App() { + return ( + { + // Cache restored successfully + console.log('Cache restored') + }} + > + {/* Show loading while restoring */} + + {({ isRestoring }) => + isRestoring ? : + } + + + ) +} + +// Or use the hook +function MainApp() { + const { isRestoring } = usePersistQueryClientRestore() + + if (isRestoring) return + return +} +``` + +## Persistence Configuration + +| Option | Purpose | +|--------|---------| +| `maxAge` | Maximum cache age before considered invalid | +| `buster` | String to invalidate cache (use app version) | +| `dehydrateOptions.shouldDehydrateQuery` | Filter which queries to persist | +| `hydrateOptions.shouldHydrate` | Filter which queries to restore | + +## Context + +- Requires `@tanstack/react-query-persist-client` package +- Set `gcTime` higher than default (5 min) for persistence to be useful +- Use `buster` option to invalidate cache on app updates +- Don't persist sensitive data or real-time data +- IndexedDB is better than localStorage for large caches +- Restored data is still subject to staleTime checks +- Works well with `networkMode: 'offlineFirst'` diff --git a/.agents/skills/tanstack-query-best-practices/rules/pf-intent-prefetch.md b/.agents/skills/tanstack-query-best-practices/rules/pf-intent-prefetch.md new file mode 100644 index 00000000..d7423113 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/pf-intent-prefetch.md @@ -0,0 +1,143 @@ +# pf-intent-prefetch: Prefetch on User Intent (Hover, Focus) + +## Priority: MEDIUM + +## Explanation + +Prefetch data when users show intent to navigate (hover, focus) rather than waiting for click. This eliminates perceived loading time for likely next actions. + +## Bad Example + +```tsx +// No prefetching - data fetches on click +function PostList({ posts }: { posts: Post[] }) { + return ( +
    + {posts.map(post => ( +
  • + + {post.title} + + {/* User clicks, waits for data to load */} +
  • + ))} +
+ ) +} +``` + +## Good Example + +```tsx +import { useQueryClient } from '@tanstack/react-query' +import { postQueries } from '@/lib/queries' + +function PostList({ posts }: { posts: Post[] }) { + const queryClient = useQueryClient() + + const handlePrefetch = (postId: number) => { + queryClient.prefetchQuery({ + ...postQueries.detail(postId), + staleTime: 60 * 1000, // Consider fresh for 1 minute + }) + } + + return ( +
    + {posts.map(post => ( +
  • + handlePrefetch(post.id)} + onFocus={() => handlePrefetch(post.id)} + > + {post.title} + +
  • + ))} +
+ ) +} +``` + +## Good Example: With TanStack Router + +```tsx +import { Link } from '@tanstack/react-router' + +// TanStack Router has built-in prefetching +function PostList({ posts }: { posts: Post[] }) { + return ( +
    + {posts.map(post => ( +
  • + + {post.title} + +
  • + ))} +
+ ) +} + +// Or set as router default +const router = createRouter({ + routeTree, + defaultPreload: 'intent', + defaultPreloadDelay: 100, // Wait 100ms before prefetching +}) +``` + +## Good Example: Prefetch with Delay + +```tsx +function PostLink({ post }: { post: Post }) { + const queryClient = useQueryClient() + const timeoutRef = useRef() + + const handleMouseEnter = () => { + // Delay prefetch to avoid unnecessary requests on quick mouse movements + timeoutRef.current = setTimeout(() => { + queryClient.prefetchQuery(postQueries.detail(post.id)) + }, 100) + } + + const handleMouseLeave = () => { + if (timeoutRef.current) { + clearTimeout(timeoutRef.current) + } + } + + return ( + + {post.title} + + ) +} +``` + +## Prefetch Triggers + +| Trigger | When to Use | +|---------|-------------| +| `onMouseEnter` | Desktop, links/buttons user will likely click | +| `onFocus` | Keyboard navigation, accessibility | +| `onTouchStart` | Mobile, before navigation | +| Component mount | Likely next pages, wizard steps | +| Intersection Observer | Below-fold content | + +## Context + +- Set appropriate `staleTime` when prefetching to avoid immediate refetch +- Consider mobile where hover isn't available +- Don't prefetch everything - focus on likely paths +- Prefetched data uses `gcTime` for retention +- Watch network tab to verify prefetch timing diff --git a/.agents/skills/tanstack-query-best-practices/rules/qk-array-structure.md b/.agents/skills/tanstack-query-best-practices/rules/qk-array-structure.md new file mode 100644 index 00000000..70364c0c --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/qk-array-structure.md @@ -0,0 +1,50 @@ +# qk-array-structure: Always Use Arrays for Query Keys + +## Priority: CRITICAL + +## Explanation + +Query keys must always be arrays at the top level. This enables proper caching, invalidation matching, and query deduplication. Using non-array keys will cause unexpected behavior and cache misses. + +## Bad Example + +```tsx +// Never use strings or non-array types as query keys +const { data } = useQuery({ + queryKey: 'todos', // Wrong: string instead of array + queryFn: fetchTodos, +}) + +const { data: user } = useQuery({ + queryKey: { id: 1, type: 'user' }, // Wrong: object instead of array + queryFn: fetchUser, +}) +``` + +## Good Example + +```tsx +// Always use arrays for query keys +const { data } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, +}) + +const { data: user } = useQuery({ + queryKey: ['user', 1], + queryFn: () => fetchUser(1), +}) + +// Complex keys with objects inside arrays are fine +const { data: filteredTodos } = useQuery({ + queryKey: ['todos', { status: 'done', page: 1 }], + queryFn: () => fetchTodos({ status: 'done', page: 1 }), +}) +``` + +## Context + +- Always applicable when defining query keys +- Arrays enable prefix-based invalidation (e.g., `invalidateQueries({ queryKey: ['todos'] })` matches all todo queries) +- Object property order inside arrays doesn't matter for matching +- Array element order does matter: `['todos', 1]` !== `['1', 'todos']` diff --git a/.agents/skills/tanstack-query-best-practices/rules/qk-factory-pattern.md b/.agents/skills/tanstack-query-best-practices/rules/qk-factory-pattern.md new file mode 100644 index 00000000..a358c4f7 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/qk-factory-pattern.md @@ -0,0 +1,102 @@ +# qk-factory-pattern: Use Query Key Factories for Complex Applications + +## Priority: CRITICAL + +## Explanation + +For applications with many queries, centralize query key definitions in factory functions. This ensures consistency, enables autocomplete, prevents typos, and makes refactoring safer. Query key factories are the recommended pattern for production applications. + +## Bad Example + +```tsx +// Scattered, inconsistent key definitions across files +// file: components/TodoList.tsx +const { data } = useQuery({ + queryKey: ['todos', 'list'], + queryFn: fetchTodos, +}) + +// file: components/TodoDetail.tsx +const { data } = useQuery({ + queryKey: ['todo', id], // Inconsistent: 'todo' vs 'todos' + queryFn: () => fetchTodo(id), +}) + +// file: components/TodoComments.tsx +const { data } = useQuery({ + queryKey: ['todoComments', todoId], // Different naming convention + queryFn: () => fetchComments(todoId), +}) + +// Invalidation is error-prone +queryClient.invalidateQueries({ queryKey: ['todos'] }) // Misses 'todo' and 'todoComments' +``` + +## Good Example + +```tsx +// file: lib/query-keys.ts +export const todoKeys = { + all: ['todos'] as const, + lists: () => [...todoKeys.all, 'list'] as const, + list: (filters: TodoFilters) => [...todoKeys.lists(), filters] as const, + details: () => [...todoKeys.all, 'detail'] as const, + detail: (id: number) => [...todoKeys.details(), id] as const, + comments: (id: number) => [...todoKeys.detail(id), 'comments'] as const, +} + +export const userKeys = { + all: ['users'] as const, + detail: (id: string) => [...userKeys.all, id] as const, + posts: (id: string) => [...userKeys.detail(id), 'posts'] as const, +} + +// file: components/TodoList.tsx +import { todoKeys } from '@/lib/query-keys' + +const { data } = useQuery({ + queryKey: todoKeys.list({ status: 'active' }), + queryFn: () => fetchTodos({ status: 'active' }), +}) + +// file: components/TodoDetail.tsx +const { data } = useQuery({ + queryKey: todoKeys.detail(id), + queryFn: () => fetchTodo(id), +}) + +// Invalidation is type-safe and predictable +queryClient.invalidateQueries({ queryKey: todoKeys.all }) // Invalidates everything +queryClient.invalidateQueries({ queryKey: todoKeys.detail(5) }) // Specific todo + comments +``` + +## Query Options Factory Pattern + +```tsx +// Even better: combine with queryOptions for full type safety +import { queryOptions } from '@tanstack/react-query' + +export const todoQueries = { + all: () => queryOptions({ + queryKey: todoKeys.all, + queryFn: fetchAllTodos, + }), + detail: (id: number) => queryOptions({ + queryKey: todoKeys.detail(id), + queryFn: () => fetchTodo(id), + staleTime: 5 * 60 * 1000, + }), +} + +// Usage +const { data } = useQuery(todoQueries.detail(5)) +await queryClient.prefetchQuery(todoQueries.detail(5)) +``` + +## Context + +- Essential for applications with 10+ different query types +- Enables IDE autocomplete and typo prevention +- Makes invalidation patterns discoverable +- Pairs well with `queryOptions` for full type inference +- Consider the `@lukemorales/query-key-factory` package for standardized implementation diff --git a/.agents/skills/tanstack-query-best-practices/rules/qk-hierarchical-organization.md b/.agents/skills/tanstack-query-best-practices/rules/qk-hierarchical-organization.md new file mode 100644 index 00000000..dd934e6d --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/qk-hierarchical-organization.md @@ -0,0 +1,76 @@ +# qk-hierarchical-organization: Organize Keys Hierarchically + +## Priority: CRITICAL + +## Explanation + +Structure query keys from general to specific: entity type first, then ID, then modifiers/filters. This enables efficient invalidation at any level of specificity and creates predictable cache organization. + +## Bad Example + +```tsx +// Flat, inconsistent key structures +const { data: todos } = useQuery({ + queryKey: ['all-todos-list'], + queryFn: fetchTodos, +}) + +const { data: todo } = useQuery({ + queryKey: ['single-todo-5'], + queryFn: () => fetchTodo(5), +}) + +const { data: comments } = useQuery({ + queryKey: ['todo-5-comments'], + queryFn: () => fetchTodoComments(5), +}) + +// Can't easily invalidate all todo-related queries +``` + +## Good Example + +```tsx +// Hierarchical: entity → id → sub-resource → filters +const { data: todos } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, +}) + +const { data: todo } = useQuery({ + queryKey: ['todos', 5], + queryFn: () => fetchTodo(5), +}) + +const { data: comments } = useQuery({ + queryKey: ['todos', 5, 'comments'], + queryFn: () => fetchTodoComments(5), +}) + +const { data: filteredTodos } = useQuery({ + queryKey: ['todos', { status: 'done', page: 1 }], + queryFn: () => fetchTodos({ status: 'done', page: 1 }), +}) + +// Now we can invalidate at any level: +queryClient.invalidateQueries({ queryKey: ['todos'] }) // All todos +queryClient.invalidateQueries({ queryKey: ['todos', 5] }) // Todo 5 and its sub-resources +queryClient.invalidateQueries({ queryKey: ['todos', 5, 'comments'] }) // Just comments +``` + +## Recommended Hierarchy Pattern + +``` +['entity'] // List +['entity', id] // Single item +['entity', id, 'sub-resource'] // Related data +['entity', { filters }] // Filtered list +['entity', id, 'sub-resource', { filters }] // Filtered sub-resource +``` + +## Context + +- Essential for applications with related data +- Enables efficient cache management +- Works with prefix-based invalidation +- Consider using query key factories (see `qk-factory-pattern`) for consistency diff --git a/.agents/skills/tanstack-query-best-practices/rules/qk-include-dependencies.md b/.agents/skills/tanstack-query-best-practices/rules/qk-include-dependencies.md new file mode 100644 index 00000000..dfaa0f43 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/qk-include-dependencies.md @@ -0,0 +1,62 @@ +# qk-include-dependencies: Include All Variables the Query Depends On + +## Priority: CRITICAL + +## Explanation + +If your query function depends on a variable, that variable must be included in the query key. This ensures independent caching per variable combination and automatic refetching when dependencies change. Missing dependencies cause stale data bugs and cache collisions. + +## Bad Example + +```tsx +function UserPosts({ userId }: { userId: string }) { + // Missing userId in query key - all users share the same cache! + const { data } = useQuery({ + queryKey: ['posts'], + queryFn: () => fetchPostsByUser(userId), + }) + + return +} + +function FilteredTodos({ status, page }: { status: string; page: number }) { + // Missing filter parameters - won't refetch when filters change + const { data } = useQuery({ + queryKey: ['todos'], + queryFn: () => fetchTodos({ status, page }), + }) + + return +} +``` + +## Good Example + +```tsx +function UserPosts({ userId }: { userId: string }) { + // userId included - each user has their own cache entry + const { data } = useQuery({ + queryKey: ['posts', userId], + queryFn: () => fetchPostsByUser(userId), + }) + + return +} + +function FilteredTodos({ status, page }: { status: string; page: number }) { + // All dependencies included - refetches when any change + const { data } = useQuery({ + queryKey: ['todos', { status, page }], + queryFn: () => fetchTodos({ status, page }), + }) + + return +} +``` + +## Context + +- This is arguably the most important query key rule +- Applies whenever query function uses external variables +- Prevents subtle bugs where different contexts share cached data +- Works in conjunction with staleTime - even with long staleTime, changing keys triggers new fetches diff --git a/.agents/skills/tanstack-query-best-practices/rules/qk-serializable.md b/.agents/skills/tanstack-query-best-practices/rules/qk-serializable.md new file mode 100644 index 00000000..0af91939 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/qk-serializable.md @@ -0,0 +1,93 @@ +# qk-serializable: Ensure All Key Parts Are JSON-Serializable + +## Priority: CRITICAL + +## Explanation + +Query keys are hashed using JSON serialization for cache lookups. Non-serializable values (functions, class instances, symbols, circular references) break caching and cause unexpected behavior. All parts of your query key must be JSON-serializable. + +## Bad Example + +```tsx +// Functions are not serializable +const { data } = useQuery({ + queryKey: ['todos', () => 'active'], // Wrong: function in key + queryFn: fetchTodos, +}) + +// Class instances lose their prototype +class Filter { + constructor(public status: string) {} + isActive() { return this.status === 'active' } +} +const filter = new Filter('active') +const { data: todos } = useQuery({ + queryKey: ['todos', filter], // Wrong: class instance + queryFn: () => fetchTodos(filter), +}) + +// Dates are technically serializable but become strings +const { data: events } = useQuery({ + queryKey: ['events', new Date()], // Problematic: new Date() each render + queryFn: () => fetchEvents(date), +}) + +// Symbols are not serializable +const { data: settings } = useQuery({ + queryKey: ['settings', Symbol('user')], // Wrong: symbol + queryFn: fetchSettings, +}) +``` + +## Good Example + +```tsx +// Use primitive values and plain objects +const { data } = useQuery({ + queryKey: ['todos', 'active'], + queryFn: fetchTodos, +}) + +// Plain objects are fine +const filters = { status: 'active', priority: 'high' } +const { data: todos } = useQuery({ + queryKey: ['todos', filters], + queryFn: () => fetchTodos(filters), +}) + +// For dates, use stable string representations +const dateKey = date.toISOString().split('T')[0] // '2024-01-15' +const { data: events } = useQuery({ + queryKey: ['events', dateKey], + queryFn: () => fetchEvents(date), +}) + +// Arrays of primitives work correctly +const { data: users } = useQuery({ + queryKey: ['users', { ids: [1, 2, 3] }], + queryFn: () => fetchUsers([1, 2, 3]), +}) +``` + +## Serializable Types + +**Safe to use:** +- Strings, numbers, booleans, null +- Plain objects (no prototype methods) +- Arrays of serializable values +- undefined (stripped but handled) + +**Avoid:** +- Functions +- Class instances +- Symbols +- Date objects (use ISO strings instead) +- Map/Set (use arrays/objects instead) +- Circular references + +## Context + +- TanStack Query uses deterministic JSON hashing +- Object property order doesn't matter: `{ a: 1, b: 2 }` equals `{ b: 2, a: 1 }` +- Keys with `undefined` properties are normalized: `{ a: 1, b: undefined }` equals `{ a: 1 }` +- Test serialization: `JSON.stringify(queryKey)` should work without errors diff --git a/.agents/skills/tanstack-query-best-practices/rules/query-cancellation.md b/.agents/skills/tanstack-query-best-practices/rules/query-cancellation.md new file mode 100644 index 00000000..5ec3f8c2 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/query-cancellation.md @@ -0,0 +1,171 @@ +# query-cancellation: Implement Query Cancellation Properly + +## Priority: MEDIUM + +## Explanation + +TanStack Query provides an `AbortSignal` to cancel in-flight requests when queries become stale or components unmount. Pass this signal to your fetch calls to prevent memory leaks and wasted bandwidth. + +## Bad Example + +```tsx +// Not using abort signal - requests complete even when unnecessary +const { data } = useQuery({ + queryKey: ['search', searchTerm], + queryFn: async () => { + // User types fast: "a", "ab", "abc" + // Three requests fire, all complete, wasting bandwidth + const response = await fetch(`/api/search?q=${searchTerm}`) + return response.json() + }, +}) + +// Component unmounts but request keeps running +function UserProfile({ userId }: { userId: string }) { + const { data } = useQuery({ + queryKey: ['user', userId], + queryFn: async () => { + const response = await fetch(`/api/users/${userId}`) + return response.json() // Completes even if user navigated away + }, + }) +} +``` + +## Good Example: Using AbortSignal with Fetch + +```tsx +const { data } = useQuery({ + queryKey: ['search', searchTerm], + queryFn: async ({ signal }) => { + const response = await fetch(`/api/search?q=${searchTerm}`, { + signal, // Pass abort signal to fetch + }) + return response.json() + }, +}) + +// Now when user types "a", "ab", "abc" quickly: +// - "a" request is cancelled when "ab" starts +// - "ab" request is cancelled when "abc" starts +// - Only "abc" completes +``` + +## Good Example: With Axios + +```tsx +import axios from 'axios' + +const { data } = useQuery({ + queryKey: ['users', userId], + queryFn: async ({ signal }) => { + const response = await axios.get(`/api/users/${userId}`, { + signal, // Axios supports AbortSignal + }) + return response.data + }, +}) +``` + +## Good Example: Manual Cancellation + +```tsx +function SearchResults() { + const queryClient = useQueryClient() + const [searchTerm, setSearchTerm] = useState('') + + const { data } = useQuery({ + queryKey: ['search', searchTerm], + queryFn: async ({ signal }) => { + const response = await fetch(`/api/search?q=${searchTerm}`, { signal }) + return response.json() + }, + enabled: searchTerm.length > 0, + }) + + // Cancel all search queries manually + const handleClear = () => { + queryClient.cancelQueries({ queryKey: ['search'] }) + setSearchTerm('') + } + + return ( +
+ setSearchTerm(e.target.value)} + /> + + +
+ ) +} +``` + +## Good Example: In Mutations (Before Optimistic Update) + +```tsx +const updateTodo = useMutation({ + mutationFn: (todo: Todo) => api.updateTodo(todo), + onMutate: async (newTodo) => { + // Cancel outgoing queries to prevent overwriting optimistic update + await queryClient.cancelQueries({ queryKey: ['todos'] }) + await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] }) + + // Proceed with optimistic update... + const previousTodos = queryClient.getQueryData(['todos']) + queryClient.setQueryData(['todos'], (old) => /* ... */) + + return { previousTodos } + }, +}) +``` + +## Good Example: Custom Cancellable Promise + +```tsx +// For non-fetch APIs that need custom cancellation +const { data } = useQuery({ + queryKey: ['expensive-computation', params], + queryFn: ({ signal }) => { + return new Promise((resolve, reject) => { + // Check if already cancelled + if (signal.aborted) { + reject(new DOMException('Aborted', 'AbortError')) + return + } + + const worker = new Worker('computation.js') + worker.postMessage(params) + + worker.onmessage = (e) => resolve(e.data) + worker.onerror = (e) => reject(e) + + // Listen for cancellation + signal.addEventListener('abort', () => { + worker.terminate() + reject(new DOMException('Aborted', 'AbortError')) + }) + }) + }, +}) +``` + +## When Queries Are Cancelled + +| Scenario | Cancelled? | +|----------|------------| +| Query key changes | Yes | +| Component unmounts | Yes | +| `queryClient.cancelQueries()` called | Yes | +| Refetch triggered | Previous request cancelled | +| `enabled` becomes false | Yes | + +## Context + +- Always pass `signal` to fetch/axios for automatic cancellation +- Cancelled queries don't trigger `onError` - they're silently dropped +- Use `queryClient.cancelQueries()` before optimistic updates +- AbortError is thrown when cancelled - handle if needed +- Cancellation prevents wasted bandwidth and race conditions +- Essential for search-as-you-type and fast navigation patterns diff --git a/.agents/skills/tanstack-query-best-practices/rules/ssr-dehydration.md b/.agents/skills/tanstack-query-best-practices/rules/ssr-dehydration.md new file mode 100644 index 00000000..456caea2 --- /dev/null +++ b/.agents/skills/tanstack-query-best-practices/rules/ssr-dehydration.md @@ -0,0 +1,158 @@ +# ssr-dehydration: Use Dehydrate/Hydrate Pattern for SSR + +## Priority: MEDIUM + +## Explanation + +For server-side rendering, prefetch queries on the server, dehydrate the cache to a serializable format, send it to the client, and hydrate on the client. This prevents content flash and duplicate requests. + +## Bad Example + +```tsx +// No SSR data passing - client refetches everything +// server-side +export async function getServerSideProps() { + const data = await fetchPosts() + return { props: { posts: data } } // Bypasses React Query cache +} + +// client-side +function PostsPage({ posts }: { posts: Post[] }) { + // This doesn't benefit from the server fetch + const { data } = useQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + // Will refetch on client, causing flash + }) + + return // Awkward fallback pattern +} +``` + +## Good Example: Next.js App Router + +```tsx +// app/posts/page.tsx +import { + dehydrate, + HydrationBoundary, + QueryClient, +} from '@tanstack/react-query' +import { postQueries } from '@/lib/queries' + +export default async function PostsPage() { + const queryClient = new QueryClient() + + await queryClient.prefetchQuery(postQueries.list()) + + return ( + + + + ) +} + +// components/PostList.tsx +'use client' + +import { useSuspenseQuery } from '@tanstack/react-query' +import { postQueries } from '@/lib/queries' + +export function PostList() { + const { data: posts } = useSuspenseQuery(postQueries.list()) + + return ( +
    + {posts.map(post => ( +
  • {post.title}
  • + ))} +
+ ) +} +``` + +## Good Example: TanStack Start/Router + +```tsx +// routes/posts.tsx +import { createFileRoute } from '@tanstack/react-router' +import { postQueries } from '@/lib/queries' + +export const Route = createFileRoute('/posts')({ + loader: async ({ context: { queryClient } }) => { + // Prefetch in route loader + await queryClient.ensureQueryData(postQueries.list()) + }, + component: PostsPage, +}) + +function PostsPage() { + const { data: posts } = useSuspenseQuery(postQueries.list()) + return +} +``` + +## Good Example: Manual SSR Setup + +```tsx +// server.tsx +import { dehydrate, QueryClient } from '@tanstack/react-query' +import { renderToString } from 'react-dom/server' + +export async function render(url: string) { + const queryClient = new QueryClient({ + defaultOptions: { + queries: { + staleTime: 60 * 1000, // Prevent immediate client refetch + }, + }, + }) + + // Prefetch required data + await queryClient.prefetchQuery({ + queryKey: ['posts'], + queryFn: fetchPosts, + }) + + const dehydratedState = dehydrate(queryClient) + + const html = renderToString( + + + + ) + + // Serialize safely - JSON.stringify is XSS vulnerable + const serializedState = serialize(dehydratedState) + + return ` + + +
${html}
+ + + + ` +} + +// client.tsx +import { hydrate, QueryClient, QueryClientProvider } from '@tanstack/react-query' + +const queryClient = new QueryClient() +hydrate(queryClient, window.__DEHYDRATED_STATE__) + +hydrateRoot( + document.getElementById('app'), + + + +) +``` + +## Context + +- Create new QueryClient per request to prevent data sharing between users +- Set `staleTime > 0` on server to prevent immediate client refetch +- Use a safe serializer (not JSON.stringify) to prevent XSS +- Failed queries aren't dehydrated by default; use `shouldDehydrateQuery` to override +- `HydrationBoundary` can be nested for route-level prefetching diff --git a/.agents/skills/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.md new file mode 100644 index 00000000..4e340a50 --- /dev/null +++ b/.agents/skills/vercel-react-best-practices/AGENTS.md @@ -0,0 +1,3810 @@ +# React Best Practices + +**Version 1.0.0** +Vercel Engineering +January 2026 + +> **Note:** +> This document is mainly for agents and LLMs to follow when maintaining, +> generating, or refactoring React and Next.js codebases. Humans +> may also find it useful, but guidance here is optimized for automation +> and consistency by AI-assisted workflows. + +--- + +## Abstract + +Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation. + +--- + +## Table of Contents + +1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL** + - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags) + - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed) + - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization) + - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes) + - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations) + - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries) +2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL** + - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports) + - 2.2 [Conditional Module Loading](#22-conditional-module-loading) + - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries) + - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components) + - 2.5 [Prefer Statically Analyzable Paths](#25-prefer-statically-analyzable-paths) + - 2.6 [Preload Based on User Intent](#26-preload-based-on-user-intent) +3. [Server-Side Performance](#3-server-side-performance) — **HIGH** + - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes) + - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props) + - 3.3 [Avoid Shared Module State for Request Data](#33-avoid-shared-module-state-for-request-data) + - 3.4 [Cross-Request LRU Caching](#34-cross-request-lru-caching) + - 3.5 [Hoist Static I/O to Module Level](#35-hoist-static-io-to-module-level) + - 3.6 [Minimize Serialization at RSC Boundaries](#36-minimize-serialization-at-rsc-boundaries) + - 3.7 [Parallel Data Fetching with Component Composition](#37-parallel-data-fetching-with-component-composition) + - 3.8 [Parallel Nested Data Fetching](#38-parallel-nested-data-fetching) + - 3.9 [Per-Request Deduplication with React.cache()](#39-per-request-deduplication-with-reactcache) + - 3.10 [Use after() for Non-Blocking Operations](#310-use-after-for-non-blocking-operations) +4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH** + - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners) + - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance) + - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication) + - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data) +5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM** + - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering) + - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point) + - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo) + - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components) + - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant) + - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components) + - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies) + - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers) + - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations) + - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state) + - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates) + - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization) + - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates) + - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders) + - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values) +6. [Rendering Performance](#6-rendering-performance) — **MEDIUM** + - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element) + - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists) + - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements) + - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision) + - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering) + - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches) + - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide) + - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags) + - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering) + - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints) + - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states) +7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM** + - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing) + - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups) + - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops) + - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls) + - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls) + - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations) + - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback) + - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons) + - 7.9 [Early Return from Functions](#79-early-return-from-functions) + - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation) + - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass) + - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort) + - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups) + - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability) +8. [Advanced Patterns](#8-advanced-patterns) — **LOW** + - 8.1 [Do Not Put Effect Events in Dependency Arrays](#81-do-not-put-effect-events-in-dependency-arrays) + - 8.2 [Initialize App Once, Not Per Mount](#82-initialize-app-once-not-per-mount) + - 8.3 [Store Event Handlers in Refs](#83-store-event-handlers-in-refs) + - 8.4 [useEffectEvent for Stable Callback Refs](#84-useeffectevent-for-stable-callback-refs) + +--- + +## 1. Eliminating Waterfalls + +**Impact: CRITICAL** + +Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains. + +### 1.1 Check Cheap Conditions Before Async Flags + +**Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)** + +When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true. + +This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks. + +**Incorrect:** + +```typescript +const someFlag = await getFlag() + +if (someFlag && someCondition) { + // ... +} +``` + +**Correct:** + +```typescript +if (someCondition) { + const someFlag = await getFlag() + if (someFlag) { + // ... + } +} +``` + +This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path. + +Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order. + +### 1.2 Defer Await Until Needed + +**Impact: HIGH (avoids blocking unused code paths)** + +Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them. + +**Incorrect: blocks both branches** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + const userData = await fetchUserData(userId) + + if (skipProcessing) { + // Returns immediately but still waited for userData + return { skipped: true } + } + + // Only this branch uses userData + return processUserData(userData) +} +``` + +**Correct: only blocks when needed** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + if (skipProcessing) { + // Returns immediately without waiting + return { skipped: true } + } + + // Fetch only when needed + const userData = await fetchUserData(userId) + return processUserData(userData) +} +``` + +**Another example: early return optimization** + +```typescript +// Incorrect: always fetches permissions +async function updateResource(resourceId: string, userId: string) { + const permissions = await fetchPermissions(userId) + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} + +// Correct: fetches only when needed +async function updateResource(resourceId: string, userId: string) { + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + const permissions = await fetchPermissions(userId) + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} +``` + +This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive. + +For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md). + +### 1.3 Dependency-Based Parallelization + +**Impact: CRITICAL (2-10× improvement)** + +For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment. + +**Incorrect: profile waits for config unnecessarily** + +```typescript +const [user, config] = await Promise.all([ + fetchUser(), + fetchConfig() +]) +const profile = await fetchProfile(user.id) +``` + +**Correct: config and profile run in parallel** + +```typescript +import { all } from 'better-all' + +const { user, config, profile } = await all({ + async user() { return fetchUser() }, + async config() { return fetchConfig() }, + async profile() { + return fetchProfile((await this.$.user).id) + } +}) +``` + +**Alternative without extra dependencies:** + +```typescript +const userPromise = fetchUser() +const profilePromise = userPromise.then(user => fetchProfile(user.id)) + +const [user, config, profile] = await Promise.all([ + userPromise, + fetchConfig(), + profilePromise +]) +``` + +We can also create all the promises first, and do `Promise.all()` at the end. + +Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all) + +### 1.4 Prevent Waterfall Chains in API Routes + +**Impact: CRITICAL (2-10× improvement)** + +In API routes and Server Actions, start independent operations immediately, even if you don't await them yet. + +**Incorrect: config waits for auth, data waits for both** + +```typescript +export async function GET(request: Request) { + const session = await auth() + const config = await fetchConfig() + const data = await fetchData(session.user.id) + return Response.json({ data, config }) +} +``` + +**Correct: auth and config start immediately** + +```typescript +export async function GET(request: Request) { + const sessionPromise = auth() + const configPromise = fetchConfig() + const session = await sessionPromise + const [config, data] = await Promise.all([ + configPromise, + fetchData(session.user.id) + ]) + return Response.json({ data, config }) +} +``` + +For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization). + +### 1.5 Promise.all() for Independent Operations + +**Impact: CRITICAL (2-10× improvement)** + +When async operations have no interdependencies, execute them concurrently using `Promise.all()`. + +**Incorrect: sequential execution, 3 round trips** + +```typescript +const user = await fetchUser() +const posts = await fetchPosts() +const comments = await fetchComments() +``` + +**Correct: parallel execution, 1 round trip** + +```typescript +const [user, posts, comments] = await Promise.all([ + fetchUser(), + fetchPosts(), + fetchComments() +]) +``` + +### 1.6 Strategic Suspense Boundaries + +**Impact: HIGH (faster initial paint)** + +Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads. + +**Incorrect: wrapper blocked by data fetching** + +```tsx +async function Page() { + const data = await fetchData() // Blocks entire page + + return ( +
+
Sidebar
+
Header
+
+ +
+
Footer
+
+ ) +} +``` + +The entire layout waits for data even though only the middle section needs it. + +**Correct: wrapper shows immediately, data streams in** + +```tsx +function Page() { + return ( +
+
Sidebar
+
Header
+
+ }> + + +
+
Footer
+
+ ) +} + +async function DataDisplay() { + const data = await fetchData() // Only blocks this component + return
{data.content}
+} +``` + +Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data. + +**Alternative: share promise across components** + +```tsx +function Page() { + // Start fetch immediately, but don't await + const dataPromise = fetchData() + + return ( +
+
Sidebar
+
Header
+ }> + + + +
Footer
+
+ ) +} + +function DataDisplay({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Unwraps the promise + return
{data.content}
+} + +function DataSummary({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Reuses the same promise + return
{data.summary}
+} +``` + +Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together. + +**When NOT to use this pattern:** + +- Critical data needed for layout decisions (affects positioning) + +- SEO-critical content above the fold + +- Small, fast queries where suspense overhead isn't worth it + +- When you want to avoid layout shift (loading → content jump) + +**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities. + +--- + +## 2. Bundle Size Optimization + +**Impact: CRITICAL** + +Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint. + +### 2.1 Avoid Barrel File Imports + +**Impact: CRITICAL (200-800ms import cost, slow builds)** + +Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`). + +Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts. + +**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph. + +**Incorrect: imports entire library** + +```tsx +import { Check, X, Menu } from 'lucide-react' +// Loads 1,583 modules, takes ~2.8s extra in dev +// Runtime cost: 200-800ms on every cold start + +import { Button, TextField } from '@mui/material' +// Loads 2,225 modules, takes ~4.2s extra in dev +``` + +**Correct - Next.js 13.5+ (recommended):** + +```tsx +// Keep the standard imports - Next.js transforms them to direct imports +import { Check, X, Menu } from 'lucide-react' +// Full TypeScript support, no manual path wrangling +``` + +This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost. + +**Correct - Direct imports (non-Next.js projects):** + +```tsx +import Button from '@mui/material/Button' +import TextField from '@mui/material/TextField' +// Loads only what you use +``` + +> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports. + +These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR. + +Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`. + +Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js) + +### 2.2 Conditional Module Loading + +**Impact: HIGH (loads large data only when needed)** + +Load large data or modules only when a feature is activated. + +**Example: lazy-load animation frames** + +```tsx +function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch> }) { + const [frames, setFrames] = useState(null) + + useEffect(() => { + if (enabled && !frames && typeof window !== 'undefined') { + import('./animation-frames.js') + .then(mod => setFrames(mod.frames)) + .catch(() => setEnabled(false)) + } + }, [enabled, frames, setEnabled]) + + if (!frames) return + return +} +``` + +The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed. + +### 2.3 Defer Non-Critical Third-Party Libraries + +**Impact: MEDIUM (loads after hydration)** + +Analytics, logging, and error tracking don't block user interaction. Load them after hydration. + +**Incorrect: blocks initial bundle** + +```tsx +import { Analytics } from '@vercel/analytics/react' + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` + +**Correct: loads after hydration** + +```tsx +import dynamic from 'next/dynamic' + +const Analytics = dynamic( + () => import('@vercel/analytics/react').then(m => m.Analytics), + { ssr: false } +) + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` + +### 2.4 Dynamic Imports for Heavy Components + +**Impact: CRITICAL (directly affects TTI and LCP)** + +Use `next/dynamic` to lazy-load large components not needed on initial render. + +**Incorrect: Monaco bundles with main chunk ~300KB** + +```tsx +import { MonacoEditor } from './monaco-editor' + +function CodePanel({ code }: { code: string }) { + return +} +``` + +**Correct: Monaco loads on demand** + +```tsx +import dynamic from 'next/dynamic' + +const MonacoEditor = dynamic( + () => import('./monaco-editor').then(m => m.MonacoEditor), + { ssr: false } +) + +function CodePanel({ code }: { code: string }) { + return +} +``` + +### 2.5 Prefer Statically Analyzable Paths + +**Impact: HIGH (avoids accidental broad bundles and file traces)** + +Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe. + +Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code. + +When analysis becomes too broad, the cost is real: + +- Larger server bundles + +- Slower builds + +- Worse cold starts + +- More memory use + +**Incorrect: the bundler cannot tell what may be imported** + +```ts +const PAGE_MODULES = { + home: './pages/home', + settings: './pages/settings', +} as const + +const Page = await import(PAGE_MODULES[pageName]) +``` + +**Correct: use an explicit map of allowed modules** + +```ts +const PAGE_MODULES = { + home: () => import('./pages/home'), + settings: () => import('./pages/settings'), +} as const + +const Page = await PAGE_MODULES[pageName]() +``` + +**Incorrect: a 2-value enum still hides the final path from static analysis** + +```ts +const baseDir = path.join(process.cwd(), 'content/' + contentKind) +``` + +**Correct: make each final path literal at the callsite** + +```ts +const baseDir = + kind === ContentKind.Blog + ? path.join(process.cwd(), 'content/blog') + : path.join(process.cwd(), 'content/docs') +``` + +In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage. + +Reference: [https://nextjs.org/docs/app/api-reference/config/next-config-js/output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [https://nextjs.org/learn/seo/dynamic-imports](https://nextjs.org/learn/seo/dynamic-imports), [https://vite.dev/guide/features.html](https://vite.dev/guide/features.html), [https://esbuild.github.io/api/](https://esbuild.github.io/api/), [https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [https://webpack.js.org/guides/dependency-management/](https://webpack.js.org/guides/dependency-management/) + +### 2.6 Preload Based on User Intent + +**Impact: MEDIUM (reduces perceived latency)** + +Preload heavy bundles before they're needed to reduce perceived latency. + +**Example: preload on hover/focus** + +```tsx +function EditorButton({ onClick }: { onClick: () => void }) { + const preload = () => { + if (typeof window !== 'undefined') { + void import('./monaco-editor') + } + } + + return ( + + ) +} +``` + +**Example: preload when feature flag is enabled** + +```tsx +function FlagsProvider({ children, flags }: Props) { + useEffect(() => { + if (flags.editorEnabled && typeof window !== 'undefined') { + void import('./monaco-editor').then(mod => mod.init()) + } + }, [flags.editorEnabled]) + + return + {children} + +} +``` + +The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. + +--- + +## 3. Server-Side Performance + +**Impact: HIGH** + +Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times. + +### 3.1 Authenticate Server Actions Like API Routes + +**Impact: CRITICAL (prevents unauthorized access to server mutations)** + +Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly. + +Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation." + +**Incorrect: no authentication check** + +```typescript +'use server' + +export async function deleteUser(userId: string) { + // Anyone can call this! No auth check + await db.user.delete({ where: { id: userId } }) + return { success: true } +} +``` + +**Correct: authentication inside the action** + +```typescript +'use server' + +import { verifySession } from '@/lib/auth' +import { unauthorized } from '@/lib/errors' + +export async function deleteUser(userId: string) { + // Always check auth inside the action + const session = await verifySession() + + if (!session) { + throw unauthorized('Must be logged in') + } + + // Check authorization too + if (session.user.role !== 'admin' && session.user.id !== userId) { + throw unauthorized('Cannot delete other users') + } + + await db.user.delete({ where: { id: userId } }) + return { success: true } +} +``` + +**With input validation:** + +```typescript +'use server' + +import { verifySession } from '@/lib/auth' +import { z } from 'zod' + +const updateProfileSchema = z.object({ + userId: z.string().uuid(), + name: z.string().min(1).max(100), + email: z.string().email() +}) + +export async function updateProfile(data: unknown) { + // Validate input first + const validated = updateProfileSchema.parse(data) + + // Then authenticate + const session = await verifySession() + if (!session) { + throw new Error('Unauthorized') + } + + // Then authorize + if (session.user.id !== validated.userId) { + throw new Error('Can only update own profile') + } + + // Finally perform the mutation + await db.user.update({ + where: { id: validated.userId }, + data: { + name: validated.name, + email: validated.email + } + }) + + return { success: true } +} +``` + +Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication) + +### 3.2 Avoid Duplicate Serialization in RSC Props + +**Impact: LOW (reduces network payload by avoiding duplicate serialization)** + +RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server. + +**Incorrect: duplicates array** + +```tsx +// RSC: sends 6 strings (2 arrays × 3 items) + +``` + +**Correct: sends 3 strings** + +```tsx +// RSC: send once + + +// Client: transform there +'use client' +const sorted = useMemo(() => [...usernames].sort(), [usernames]) +``` + +**Nested deduplication behavior:** + +```tsx +// string[] - duplicates everything +usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings + +// object[] - duplicates array structure only +users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4) +``` + +Deduplication works recursively. Impact varies by data type: + +- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated + +- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference + +**Operations breaking deduplication: create new references** + +- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]` + +- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())` + +**More examples:** + +```tsx +// ❌ Bad + u.active)} /> + + +// ✅ Good + + +// Do filtering/destructuring in client +``` + +**Exception:** Pass derived data when transformation is expensive or client doesn't need original. + +### 3.3 Avoid Shared Module State for Request Data + +**Impact: HIGH (prevents concurrency bugs and request data leaks)** + +For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response. + +Treat module scope on the server as process-wide shared memory, not request-local state. + +**Incorrect: request data leaks across concurrent renders** + +```tsx +let currentUser: User | null = null + +export default async function Page() { + currentUser = await auth() + return +} + +async function Dashboard() { + return
{currentUser?.name}
+} +``` + +If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`. + +**Correct: keep request data local to the render tree** + +```tsx +export default async function Page() { + const user = await auth() + return +} + +function Dashboard({ user }: { user: User | null }) { + return
{user?.name}
+} +``` + +Safe exceptions: + +- Immutable static assets or config loaded once at module scope + +- Shared caches intentionally designed for cross-request reuse and keyed correctly + +- Process-wide singletons that do not store request- or user-specific mutable data + +For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md). + +### 3.4 Cross-Request LRU Caching + +**Impact: HIGH (caches across requests)** + +`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache. + +**Implementation:** + +```typescript +import { LRUCache } from 'lru-cache' + +const cache = new LRUCache({ + max: 1000, + ttl: 5 * 60 * 1000 // 5 minutes +}) + +export async function getUser(id: string) { + const cached = cache.get(id) + if (cached) return cached + + const user = await db.user.findUnique({ where: { id } }) + cache.set(id, user) + return user +} + +// Request 1: DB query, result cached +// Request 2: cache hit, no DB query +``` + +Use when sequential user actions hit multiple endpoints needing the same data within seconds. + +**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis. + +**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching. + +Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache) + +### 3.5 Hoist Static I/O to Module Level + +**Impact: HIGH (avoids repeated file/network I/O per request)** + +When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation. + +**Incorrect: reads font file on every request** + +```typescript +// app/api/og/route.tsx +import { ImageResponse } from 'next/og' + +export async function GET(request: Request) { + // Runs on EVERY request - expensive! + const fontData = await fetch( + new URL('./fonts/Inter.ttf', import.meta.url) + ).then(res => res.arrayBuffer()) + + const logoData = await fetch( + new URL('./images/logo.png', import.meta.url) + ).then(res => res.arrayBuffer()) + + return new ImageResponse( +
+ + Hello World +
, + { fonts: [{ name: 'Inter', data: fontData }] } + ) +} +``` + +**Correct: loads once at module initialization** + +```typescript +// app/api/og/route.tsx +import { ImageResponse } from 'next/og' + +// Module-level: runs ONCE when module is first imported +const fontData = fetch( + new URL('./fonts/Inter.ttf', import.meta.url) +).then(res => res.arrayBuffer()) + +const logoData = fetch( + new URL('./images/logo.png', import.meta.url) +).then(res => res.arrayBuffer()) + +export async function GET(request: Request) { + // Await the already-started promises + const [font, logo] = await Promise.all([fontData, logoData]) + + return new ImageResponse( +
+ + Hello World +
, + { fonts: [{ name: 'Inter', data: font }] } + ) +} +``` + +**Correct: synchronous fs at module level** + +```typescript +// app/api/og/route.tsx +import { ImageResponse } from 'next/og' +import { readFileSync } from 'fs' +import { join } from 'path' + +// Synchronous read at module level - blocks only during module init +const fontData = readFileSync( + join(process.cwd(), 'public/fonts/Inter.ttf') +) + +const logoData = readFileSync( + join(process.cwd(), 'public/images/logo.png') +) + +export async function GET(request: Request) { + return new ImageResponse( +
+ + Hello World +
, + { fonts: [{ name: 'Inter', data: fontData }] } + ) +} +``` + +**Incorrect: reads config on every call** + +```typescript +import fs from 'node:fs/promises' + +export async function processRequest(data: Data) { + const config = JSON.parse( + await fs.readFile('./config.json', 'utf-8') + ) + const template = await fs.readFile('./template.html', 'utf-8') + + return render(template, data, config) +} +``` + +**Correct: hoists config and template to module level** + +```typescript +import fs from 'node:fs/promises' + +const configPromise = fs + .readFile('./config.json', 'utf-8') + .then(JSON.parse) +const templatePromise = fs.readFile('./template.html', 'utf-8') + +export async function processRequest(data: Data) { + const [config, template] = await Promise.all([ + configPromise, + templatePromise, + ]) + + return render(template, data, config) +} +``` + +When to use this pattern: + +- Loading fonts for OG image generation + +- Loading static logos, icons, or watermarks + +- Reading configuration files that don't change at runtime + +- Loading email templates or other static templates + +- Any static asset that's the same across all requests + +When not to use this pattern: + +- Assets that vary per request or user + +- Files that may change during runtime (use caching with TTL instead) + +- Large files that would consume too much memory if kept loaded + +- Sensitive data that shouldn't persist in memory + +With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties. + +In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled. + +### 3.6 Minimize Serialization at RSC Boundaries + +**Impact: HIGH (reduces data transfer size)** + +The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses. + +**Incorrect: serializes all 50 fields** + +```tsx +async function Page() { + const user = await fetchUser() // 50 fields + return +} + +'use client' +function Profile({ user }: { user: User }) { + return
{user.name}
// uses 1 field +} +``` + +**Correct: serializes only 1 field** + +```tsx +async function Page() { + const user = await fetchUser() + return +} + +'use client' +function Profile({ name }: { name: string }) { + return
{name}
+} +``` + +### 3.7 Parallel Data Fetching with Component Composition + +**Impact: CRITICAL (eliminates server-side waterfalls)** + +React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching. + +**Incorrect: Sidebar waits for Page's fetch to complete** + +```tsx +export default async function Page() { + const header = await fetchHeader() + return ( +
+
{header}
+ +
+ ) +} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} +``` + +**Correct: both fetch simultaneously** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +export default function Page() { + return ( +
+
+ +
+ ) +} +``` + +**Alternative with children prop:** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +function Layout({ children }: { children: ReactNode }) { + return ( +
+
+ {children} +
+ ) +} + +export default function Page() { + return ( + + + + ) +} +``` + +### 3.8 Parallel Nested Data Fetching + +**Impact: CRITICAL (eliminates server-side waterfalls)** + +When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest. + +**Incorrect: a single slow item blocks all nested fetches** + +```tsx +const chats = await Promise.all( + chatIds.map(id => getChat(id)) +) + +const chatAuthors = await Promise.all( + chats.map(chat => getUser(chat.author)) +) +``` + +If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready. + +**Correct: each item chains its own nested fetch** + +```tsx +const chatAuthors = await Promise.all( + chatIds.map(id => getChat(id).then(chat => getUser(chat.author))) +) +``` + +Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others. + +### 3.9 Per-Request Deduplication with React.cache() + +**Impact: MEDIUM (deduplicates within request)** + +Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most. + +**Usage:** + +```typescript +import { cache } from 'react' + +export const getCurrentUser = cache(async () => { + const session = await auth() + if (!session?.user?.id) return null + return await db.user.findUnique({ + where: { id: session.user.id } + }) +}) +``` + +Within a single request, multiple calls to `getCurrentUser()` execute the query only once. + +**Avoid inline objects as arguments:** + +`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits. + +**Incorrect: always cache miss** + +```typescript +const getUser = cache(async (params: { uid: number }) => { + return await db.user.findUnique({ where: { id: params.uid } }) +}) + +// Each call creates new object, never hits cache +getUser({ uid: 1 }) +getUser({ uid: 1 }) // Cache miss, runs query again +``` + +**Correct: cache hit** + +```typescript +const params = { uid: 1 } +getUser(params) // Query runs +getUser(params) // Cache hit (same reference) +``` + +If you must pass objects, pass the same reference: + +**Next.js-Specific Note:** + +In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks: + +- Database queries (Prisma, Drizzle, etc.) + +- Heavy computations + +- Authentication checks + +- File system operations + +- Any non-fetch async work + +Use `React.cache()` to deduplicate these operations across your component tree. + +Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache) + +### 3.10 Use after() for Non-Blocking Operations + +**Impact: MEDIUM (faster response times)** + +Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response. + +**Incorrect: blocks response** + +```tsx +import { logUserAction } from '@/app/utils' + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request) + + // Logging blocks the response + const userAgent = request.headers.get('user-agent') || 'unknown' + await logUserAction({ userAgent }) + + return new Response(JSON.stringify({ status: 'success' }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) +} +``` + +**Correct: non-blocking** + +```tsx +import { after } from 'next/server' +import { headers, cookies } from 'next/headers' +import { logUserAction } from '@/app/utils' + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request) + + // Log after response is sent + after(async () => { + const userAgent = (await headers()).get('user-agent') || 'unknown' + const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous' + + logUserAction({ sessionCookie, userAgent }) + }) + + return new Response(JSON.stringify({ status: 'success' }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) +} +``` + +The response is sent immediately while logging happens in the background. + +**Common use cases:** + +- Analytics tracking + +- Audit logging + +- Sending notifications + +- Cache invalidation + +- Cleanup tasks + +**Important notes:** + +- `after()` runs even if the response fails or redirects + +- Works in Server Actions, Route Handlers, and Server Components + +Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after) + +--- + +## 4. Client-Side Data Fetching + +**Impact: MEDIUM-HIGH** + +Automatic deduplication and efficient data fetching patterns reduce redundant network requests. + +### 4.1 Deduplicate Global Event Listeners + +**Impact: LOW (single listener for N components)** + +Use `useSWRSubscription()` to share global event listeners across component instances. + +**Incorrect: N instances = N listeners** + +```tsx +function useKeyboardShortcut(key: string, callback: () => void) { + useEffect(() => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && e.key === key) { + callback() + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }, [key, callback]) +} +``` + +When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener. + +**Correct: N instances = 1 listener** + +```tsx +import useSWRSubscription from 'swr/subscription' + +// Module-level Map to track callbacks per key +const keyCallbacks = new Map void>>() + +function useKeyboardShortcut(key: string, callback: () => void) { + // Register this callback in the Map + useEffect(() => { + if (!keyCallbacks.has(key)) { + keyCallbacks.set(key, new Set()) + } + keyCallbacks.get(key)!.add(callback) + + return () => { + const set = keyCallbacks.get(key) + if (set) { + set.delete(callback) + if (set.size === 0) { + keyCallbacks.delete(key) + } + } + } + }, [key, callback]) + + useSWRSubscription('global-keydown', () => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && keyCallbacks.has(e.key)) { + keyCallbacks.get(e.key)!.forEach(cb => cb()) + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }) +} + +function Profile() { + // Multiple shortcuts will share the same listener + useKeyboardShortcut('p', () => { /* ... */ }) + useKeyboardShortcut('k', () => { /* ... */ }) + // ... +} +``` + +### 4.2 Use Passive Event Listeners for Scrolling Performance + +**Impact: MEDIUM (eliminates scroll delay caused by event listeners)** + +Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay. + +**Incorrect:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch) + document.addEventListener('wheel', handleWheel) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Correct:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch, { passive: true }) + document.addEventListener('wheel', handleWheel, { passive: true }) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`. + +**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`. + +### 4.3 Use SWR for Automatic Deduplication + +**Impact: MEDIUM-HIGH (automatic deduplication)** + +SWR enables request deduplication, caching, and revalidation across component instances. + +**Incorrect: no deduplication, each instance fetches** + +```tsx +function UserList() { + const [users, setUsers] = useState([]) + useEffect(() => { + fetch('/api/users') + .then(r => r.json()) + .then(setUsers) + }, []) +} +``` + +**Correct: multiple instances share one request** + +```tsx +import useSWR from 'swr' + +function UserList() { + const { data: users } = useSWR('/api/users', fetcher) +} +``` + +**For immutable data:** + +```tsx +import { useImmutableSWR } from '@/lib/swr' + +function StaticContent() { + const { data } = useImmutableSWR('/api/config', fetcher) +} +``` + +**For mutations:** + +```tsx +import { useSWRMutation } from 'swr/mutation' + +function UpdateButton() { + const { trigger } = useSWRMutation('/api/user', updateUser) + return +} +``` + +Reference: [https://swr.vercel.app](https://swr.vercel.app) + +### 4.4 Version and Minimize localStorage Data + +**Impact: MEDIUM (prevents schema conflicts, reduces storage size)** + +Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. + +**Incorrect:** + +```typescript +// No version, stores everything, no error handling +localStorage.setItem('userConfig', JSON.stringify(fullUserObject)) +const data = localStorage.getItem('userConfig') +``` + +**Correct:** + +```typescript +const VERSION = 'v2' + +function saveConfig(config: { theme: string; language: string }) { + try { + localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)) + } catch { + // Throws in incognito/private browsing, quota exceeded, or disabled + } +} + +function loadConfig() { + try { + const data = localStorage.getItem(`userConfig:${VERSION}`) + return data ? JSON.parse(data) : null + } catch { + return null + } +} + +// Migration from v1 to v2 +function migrate() { + try { + const v1 = localStorage.getItem('userConfig:v1') + if (v1) { + const old = JSON.parse(v1) + saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang }) + localStorage.removeItem('userConfig:v1') + } + } catch {} +} +``` + +**Store minimal fields from server responses:** + +```typescript +// User object has 20+ fields, only store what UI needs +function cachePrefs(user: FullUser) { + try { + localStorage.setItem('prefs:v1', JSON.stringify({ + theme: user.preferences.theme, + notifications: user.preferences.notifications + })) + } catch {} +} +``` + +**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. + +**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. + +--- + +## 5. Re-render Optimization + +**Impact: MEDIUM** + +Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness. + +### 5.1 Calculate Derived State During Rendering + +**Impact: MEDIUM (avoids redundant renders and state drift)** + +If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead. + +**Incorrect: redundant state and effect** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const [fullName, setFullName] = useState('') + + useEffect(() => { + setFullName(firstName + ' ' + lastName) + }, [firstName, lastName]) + + return

{fullName}

+} +``` + +**Correct: derive during render** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const fullName = firstName + ' ' + lastName + + return

{fullName}

+} +``` + +Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect) + +### 5.2 Defer State Reads to Usage Point + +**Impact: MEDIUM (avoids unnecessary subscriptions)** + +Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks. + +**Incorrect: subscribes to all searchParams changes** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const searchParams = useSearchParams() + + const handleShare = () => { + const ref = searchParams.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` + +**Correct: reads on demand, no subscription** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const handleShare = () => { + const params = new URLSearchParams(window.location.search) + const ref = params.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` + +### 5.3 Do not wrap a simple expression with a primitive result type in useMemo + +**Impact: LOW-MEDIUM (wasted computation on every render)** + +When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`. + +Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself. + +**Incorrect:** + +```tsx +function Header({ user, notifications }: Props) { + const isLoading = useMemo(() => { + return user.isLoading || notifications.isLoading + }, [user.isLoading, notifications.isLoading]) + + if (isLoading) return + // return some markup +} +``` + +**Correct:** + +```tsx +function Header({ user, notifications }: Props) { + const isLoading = user.isLoading || notifications.isLoading + + if (isLoading) return + // return some markup +} +``` + +### 5.4 Don't Define Components Inside Components + +**Impact: HIGH (prevents remount on every render)** + +Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM. + +A common reason developers do this is to access parent variables without passing props. Always pass props instead. + +**Incorrect: remounts on every render** + +```tsx +function UserProfile({ user, theme }) { + // Defined inside to access `theme` - BAD + const Avatar = () => ( + + ) + + // Defined inside to access `user` - BAD + const Stats = () => ( +
+ {user.followers} followers + {user.posts} posts +
+ ) + + return ( +
+ + +
+ ) +} +``` + +Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes. + +**Correct: pass props instead** + +```tsx +function Avatar({ src, theme }: { src: string; theme: string }) { + return ( + + ) +} + +function Stats({ followers, posts }: { followers: number; posts: number }) { + return ( +
+ {followers} followers + {posts} posts +
+ ) +} + +function UserProfile({ user, theme }) { + return ( +
+ + +
+ ) +} +``` + +**Symptoms of this bug:** + +- Input fields lose focus on every keystroke + +- Animations restart unexpectedly + +- `useEffect` cleanup/setup runs on every parent render + +- Scroll position resets inside the component + +### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant + +**Impact: MEDIUM (restores memoization by using a constant for default value)** + +When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`. + +To address this issue, extract the default value into a constant. + +**Incorrect: `onClick` has different values on every rerender** + +```tsx +const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) { + // ... +}) + +// Used without optional onClick + +``` + +**Correct: stable default value** + +```tsx +const NOOP = () => {}; + +const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) { + // ... +}) + +// Used without optional onClick + +``` + +### 5.6 Extract to Memoized Components + +**Impact: MEDIUM (enables early returns)** + +Extract expensive work into memoized components to enable early returns before computation. + +**Incorrect: computes avatar even when loading** + +```tsx +function Profile({ user, loading }: Props) { + const avatar = useMemo(() => { + const id = computeAvatarId(user) + return + }, [user]) + + if (loading) return + return
{avatar}
+} +``` + +**Correct: skips computation when loading** + +```tsx +const UserAvatar = memo(function UserAvatar({ user }: { user: User }) { + const id = useMemo(() => computeAvatarId(user), [user]) + return +}) + +function Profile({ user, loading }: Props) { + if (loading) return + return ( +
+ +
+ ) +} +``` + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders. + +### 5.7 Narrow Effect Dependencies + +**Impact: LOW (minimizes effect re-runs)** + +Specify primitive dependencies instead of objects to minimize effect re-runs. + +**Incorrect: re-runs on any user field change** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user]) +``` + +**Correct: re-runs only when id changes** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user.id]) +``` + +**For derived state, compute outside effect:** + +```tsx +// Incorrect: runs on width=767, 766, 765... +useEffect(() => { + if (width < 768) { + enableMobileMode() + } +}, [width]) + +// Correct: runs only on boolean transition +const isMobile = width < 768 +useEffect(() => { + if (isMobile) { + enableMobileMode() + } +}, [isMobile]) +``` + +### 5.8 Put Interaction Logic in Event Handlers + +**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)** + +If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action. + +**Incorrect: event modeled as state + effect** + +```tsx +function Form() { + const [submitted, setSubmitted] = useState(false) + const theme = useContext(ThemeContext) + + useEffect(() => { + if (submitted) { + post('/api/register') + showToast('Registered', theme) + } + }, [submitted, theme]) + + return +} +``` + +**Correct: do it in the handler** + +```tsx +function Form() { + const theme = useContext(ThemeContext) + + function handleSubmit() { + post('/api/register') + showToast('Registered', theme) + } + + return +} +``` + +Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler) + +### 5.9 Split Combined Hook Computations + +**Impact: MEDIUM (avoids recomputing independent steps)** + +When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value. + +**Incorrect: changing `sortOrder` recomputes filtering** + +```tsx +const sortedProducts = useMemo(() => { + const filtered = products.filter((p) => p.category === category) + const sorted = filtered.toSorted((a, b) => + sortOrder === "asc" ? a.price - b.price : b.price - a.price + ) + return sorted +}, [products, category, sortOrder]) +``` + +**Correct: filtering only recomputes when products or category change** + +```tsx +const filteredProducts = useMemo( + () => products.filter((p) => p.category === category), + [products, category] +) + +const sortedProducts = useMemo( + () => + filteredProducts.toSorted((a, b) => + sortOrder === "asc" ? a.price - b.price : b.price - a.price + ), + [filteredProducts, sortOrder] +) +``` + +This pattern also applies to `useEffect` when combining unrelated side effects: + +**Incorrect: both effects run when either dependency changes** + +```tsx +useEffect(() => { + analytics.trackPageView(pathname) + document.title = `${pageTitle} | My App` +}, [pathname, pageTitle]) +``` + +**Correct: effects run independently** + +```tsx +useEffect(() => { + analytics.trackPageView(pathname) +}, [pathname]) + +useEffect(() => { + document.title = `${pageTitle} | My App` +}, [pageTitle]) +``` + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you. + +### 5.10 Subscribe to Derived State + +**Impact: MEDIUM (reduces re-render frequency)** + +Subscribe to derived boolean state instead of continuous values to reduce re-render frequency. + +**Incorrect: re-renders on every pixel change** + +```tsx +function Sidebar() { + const width = useWindowWidth() // updates continuously + const isMobile = width < 768 + return