Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
154 commits
Select commit Hold shift + click to select a range
bebad6e
Update README.md
agenticassets Nov 18, 2025
2d0a22b
Merge branch 'vercel-labs:main' into main
agenticassets Jan 15, 2026
54b07e4
Add comprehensive Claude Code configuration and documentation
agenticassets Jan 16, 2026
b6dbf4f
add skills
agenticassets Jan 16, 2026
a150d48
Fix GitHub OAuth scope and hide template branding
agenticassets Jan 16, 2026
5018920
Hide GitHub stars and Deploy buttons across all pages
agenticassets Jan 16, 2026
79f9f3c
Add comprehensive GitHub OAuth troubleshooting documentation
agenticassets Jan 16, 2026
e93ba7b
Update branding to Agentic Assets
agenticassets Jan 16, 2026
7b95ee0
Add guidance for MCP server authentication headers
agenticassets Jan 16, 2026
840cecb
Add Orbis as preset MCP server
agenticassets Jan 16, 2026
6f6ef3a
Update branding from 'Coding Agent Template' to 'AI Coding Agent'
agenticassets Jan 16, 2026
e844b36
add
agenticassets Jan 16, 2026
fc9cd42
update
agenticassets Jan 16, 2026
69c347a
update
agenticassets Jan 16, 2026
910f767
Add Agentic Assets logo to landing page
agenticassets Jan 16, 2026
230db0d
add ai gateway for claude code
agenticassets Jan 16, 2026
b44ce5d
Update rate limits and admin domains
cursoragent Jan 16, 2026
4252503
Fix session user handling
cursoragent Jan 16, 2026
9138f0c
Update documentation for Claude AI Gateway support
agenticassets Jan 16, 2026
864c8c6
Merge pull request #1 from agenticassets/cursor/agent-run-limits-admi…
agenticassets Jan 16, 2026
29c5057
Merge pull request #2 from agenticassets/2026-1-15-cns-claude-code-ai…
agenticassets Jan 16, 2026
c376d28
add other models to claude code
agenticassets Jan 16, 2026
1607872
Merge branch 'main' of https://github.com/agenticassets/AA-coding-agent
agenticassets Jan 16, 2026
1ea2cfc
Make logo responsive to dark mode and reduce size by 20%
agenticassets Jan 16, 2026
c566dc0
fix logo
agenticassets Jan 16, 2026
24ddfd7
Move logo inline with text and make it a clickable link
agenticassets Jan 16, 2026
3349c23
There's there's an issue with the API keys window that pops up when i...
agenticassets Jan 16, 2026
4008c58
add models
agenticassets Jan 16, 2026
8e66a74
add
agenticassets Jan 16, 2026
26984cd
Merge pull request #3 from agenticassets/agent/2026-01-16T04-46-56-hN…
agenticassets Jan 16, 2026
549e6f9
Merge branch 'main' of https://github.com/agenticassets/AA-coding-agent
agenticassets Jan 16, 2026
1926237
Adjust logo vertical alignment with small downward offset
agenticassets Jan 16, 2026
035f302
That didn't work. Please think harder. Figure out why it's not. Help ...
agenticassets Jan 16, 2026
fd23357
Increase logo vertical offset to 3px for better alignment
agenticassets Jan 16, 2026
007b7f6
Oh but the issue before is that even when I clicked it, it work. The ...
agenticassets Jan 16, 2026
f71bfb1
Merge pull request #4 from agenticassets/agent/2026-01-16T04-46-56-hN…
agenticassets Jan 16, 2026
984311e
but make sure the input still shows •••••••••••••••• as a placeholder...
agenticassets Jan 16, 2026
83c9dbb
Merge pull request #5 from agenticassets/agent/2026-01-16T04-46-56-hN…
agenticassets Jan 16, 2026
c705d79
Fix API key input bugs: preserve key after save and show eye button f…
claude Jan 16, 2026
c92e2c8
Merge pull request #6 from agenticassets/claude/review-api-key-input-…
agenticassets Jan 16, 2026
433d0c6
add subagents
agenticassets Jan 16, 2026
f5887c0
Merge branch 'main' of https://github.com/agenticassets/AA-coding-agent
agenticassets Jan 16, 2026
950eb11
fix logo
agenticassets Jan 16, 2026
ee21d6c
Add Vercel Web Analytics to Next.js
vercel[bot] Jan 16, 2026
183bad3
Merge pull request #7 from agenticassets/vercel/vercel-web-analytics-…
agenticassets Jan 16, 2026
4af9c49
Add external API token authentication for cross-platform integration
claude Jan 16, 2026
a0de20d
docs: add external API token authentication documentation
claude Jan 16, 2026
99e3b3a
fix: address security and type issues in API token feature
claude Jan 16, 2026
7db585f
fix: critical auth, security, and accessibility issues in API token f…
claude Jan 16, 2026
e89321b
Fix mobile logo alignment on landing page
claude Jan 16, 2026
cbbfe89
docs: add API usage guidance and update documentation
claude Jan 16, 2026
c977498
Merge pull request #8 from agenticassets/claude/review-recent-commits…
agenticassets Jan 16, 2026
f7dc6e4
feat: add Settings link to user dropdown menu
claude Jan 16, 2026
1b5934f
refactor: integrate API tokens into API Keys dialog
claude Jan 16, 2026
9668e8a
Merge pull request #9 from agenticassets/claude/review-recent-commits…
agenticassets Jan 16, 2026
2bd4bed
Merge pull request #10 from agenticassets/claude/fix-mobile-logo-alig…
agenticassets Jan 16, 2026
e4cbba6
fix: improve API Keys dialog mobile responsiveness
claude Jan 16, 2026
57eda25
Merge pull request #11 from agenticassets/claude/review-recent-commit…
agenticassets Jan 16, 2026
62a195e
fix: contain code block horizontal scroll within its container
claude Jan 16, 2026
f74fcd1
Merge pull request #12 from agenticassets/claude/review-recent-commit…
agenticassets Jan 16, 2026
1c08642
fix: add MCP server model compatibility warnings and improve error lo…
claude Jan 16, 2026
462e82f
fix: use .mcp.json file for MCP server discovery instead of CLI commands
claude Jan 16, 2026
323e1f3
fix: remove incorrect MCP model compatibility warnings
claude Jan 16, 2026
0f9cadb
Merge pull request #13 from agenticassets/claude/debug-mcp-servers-ZBPxE
agenticassets Jan 16, 2026
518cc6b
add AA logos
agenticassets Jan 16, 2026
ae4ab79
fix: include env variables as HTTP headers for remote MCP servers
claude Jan 16, 2026
949da5f
Merge pull request #14 from agenticassets/claude/debug-mcp-servers-ZBPxE
agenticassets Jan 16, 2026
142bc48
Merge branch 'main' of https://github.com/agenticassets/AA-coding-agent
agenticassets Jan 16, 2026
942e710
fix: resolve agent stuck issues with timeout, session handling, and c…
claude Jan 17, 2026
d02a837
Merge pull request #15 from agenticassets/claude/debug-agent-stuck-1Vjd1
agenticassets Jan 17, 2026
fc78e6c
feat: add MCP server for coding agent access
claude Jan 17, 2026
1f92d48
fix: exclude template files from ESLint linting
claude Jan 17, 2026
c21e7d4
feat: add MCP server configuration to API keys dialog
claude Jan 17, 2026
388c811
fix: remove duplicate favicon causing build error
claude Jan 17, 2026
eaa80b3
Merge pull request #16 from agenticassets/claude/delegate-codebase-re…
agenticassets Jan 17, 2026
ee6910b
feat: show YOUR_API_KEY placeholder in examples unless token just cre…
claude Jan 17, 2026
7e68aac
feat: add standalone MCP URL display before configuration examples
claude Jan 17, 2026
61dff52
Merge pull request #17 from agenticassets/claude/delegate-codebase-re…
agenticassets Jan 17, 2026
6eac580
feat: add internal MCP server documentation page with markdown rendering
claude Jan 17, 2026
c745914
Merge pull request #18 from agenticassets/claude/delegate-codebase-re…
agenticassets Jan 17, 2026
a52f10d
add agents
agenticassets Jan 17, 2026
31e41db
update
agenticassets Jan 17, 2026
75c04a0
docs: comprehensive documentation audit and CLAUDE.md creation
claude Jan 17, 2026
b508da4
fix: rewrite 3 contaminated agents to remove Orbis project references
claude Jan 17, 2026
f1d476d
update hook
agenticassets Jan 17, 2026
f80306b
docs: condense folder-specific CLAUDE.md files to 30-40 lines
claude Jan 17, 2026
dc739e9
Merge pull request #19 from agenticassets/claude/review-commits-updat…
agenticassets Jan 17, 2026
364e08e
feat: enable MCP external access with GitHub authentication
claude Jan 17, 2026
452df24
docs: update documentation for MCP external access support
claude Jan 17, 2026
ce1b61c
fix: critical MCP task execution and security improvements
claude Jan 17, 2026
82a7f35
Merge pull request #20 from agenticassets/claude/delegate-tasks-2aLNJ
agenticassets Jan 17, 2026
4e25370
docs: add ultra-lean folder-specific CLAUDE.md files
claude Jan 17, 2026
da27bf8
Merge pull request #21 from agenticassets/claude/delegate-tasks-2aLNJ
agenticassets Jan 17, 2026
4637c79
fix: security improvements and code quality refinements
claude Jan 17, 2026
ab04dd7
docs: add security audit and migration documentation
claude Jan 17, 2026
14219c9
Merge pull request #22 from agenticassets/claude/review-recent-commit…
agenticassets Jan 17, 2026
5dbcc59
docs: comprehensive documentation audit and updates for 2026
claude Jan 17, 2026
9ad1276
Merge pull request #23 from agenticassets/claude/review-recent-commit…
agenticassets Jan 18, 2026
78d66c7
Add sandbox agent stuck analysis report
cursoragent Jan 18, 2026
64967f3
fix: resolve stuck sandbox agent issues with 5 comprehensive fixes
claude Jan 18, 2026
7faf5b2
Merge pull request #25 from agenticassets/claude/sandbox-agent-review…
agenticassets Jan 18, 2026
feb0d52
feat: add sub-agent display and timeout handling
claude Jan 18, 2026
b4abcf6
chore: format collapsible component
claude Jan 18, 2026
05d168a
docs: add security review for sub-agent timeout implementation
claude Jan 18, 2026
21e4e60
fix: resolve critical race conditions and improve accessibility
claude Jan 18, 2026
45d3db2
fix: address review findings - remove dead code, optimize queries, ad…
claude Jan 18, 2026
775a220
Merge pull request #26 from agenticassets/claude/sub-agent-display-ti…
agenticassets Jan 18, 2026
d6513d4
chore: add database migration for sub-agent tracking columns
claude Jan 18, 2026
f57301a
fix: add sub-agent columns to initial migration for fresh installs
claude Jan 18, 2026
01629c9
Merge pull request #27 from agenticassets/claude/sub-agent-display-ti…
agenticassets Jan 18, 2026
7e1eb12
fix: resolve GitHub push authentication failures in agent execution
claude Jan 18, 2026
fe2cb1e
fix: add GitHub token validation to follow-up messages
claude Jan 18, 2026
d72d148
Merge pull request #28 from agenticassets/claude/fix-github-push-dfNMj
agenticassets Jan 18, 2026
fdc6e36
docs: add branch selection feature research document
claude Jan 20, 2026
fb95cd7
feat: add GitHub branch selection for task creation
claude Jan 20, 2026
cda968d
docs: improve documentation accuracy and inline code comments
claude Jan 20, 2026
c110669
Merge pull request #29 from agenticassets/claude/research-github-supa…
agenticassets Jan 20, 2026
cfbf4c8
fix: add missing source_branch migration and GitHub PAT support
claude Jan 20, 2026
c3bfacd
Merge pull request #30 from agenticassets/claude/review-recent-commit…
agenticassets Jan 20, 2026
4203126
fix: add sourceBranch to MCP tools and make migration idempotent
claude Jan 20, 2026
ce7598e
fix: update API keys dialog with accurate documentation and GitHub PA…
claude Jan 20, 2026
763bef3
Merge pull request #31 from agenticassets/claude/review-branch-select…
agenticassets Jan 20, 2026
47351f0
fix: add missing 0024_snapshot.json for source_branch migration
claude Jan 20, 2026
31f148f
Merge pull request #32 from agenticassets/claude/debug-loading-issues…
agenticassets Jan 20, 2026
58b90f9
fix: prevent 500 errors in auth routes by adding proper error handling
claude Jan 20, 2026
a5e8b6c
Merge pull request #33 from agenticassets/claude/fix-migration-snapsh…
agenticassets Jan 20, 2026
721f35e
fix: comprehensive error handling for all auth and session routes
claude Jan 20, 2026
0cc9f34
Merge pull request #34 from agenticassets/claude/review-commits-code-…
agenticassets Jan 20, 2026
dc64e20
add
agenticassets Jan 20, 2026
6a1e9c3
update docs
agenticassets Jan 20, 2026
249cfad
fit github toke nissues
agenticassets Jan 20, 2026
0c0c7a7
Merge pull request #35 from agenticassets/2026-1-20-fix-github-issues
agenticassets Jan 20, 2026
d7d0c41
Optimize editor re-render behavior
cursoragent Jan 22, 2026
474a678
Fix Monaco editor options typing
cursoragent Jan 22, 2026
e91c29e
Stabilize editor callback deps
cursoragent Jan 22, 2026
afb5821
Consolidate performance optimizations from cursor/AGENTIC branches
claude Jan 22, 2026
1dee8ed
Add user-friendly MCP guide documentation
claude Jan 22, 2026
3a5e2f7
Comprehensive code review: security, performance, and database optimi…
claude Jan 26, 2026
84e359e
Merge pull request #38 from agenticassets/claude/code-review-refineme…
agenticassets Jan 27, 2026
0dffca1
Merge pull request #39 from agenticassets/claude/mcp-markdown-guide-H…
agenticassets Jan 27, 2026
5634e84
Merge pull request #37 from agenticassets/cursor/AGENTIC-19-editor-re…
agenticassets Jan 27, 2026
d6b1e51
Merge origin/main: resolve conflicts with performance optimizations
claude Jan 27, 2026
7db41fb
Merge pull request #41 from agenticassets/claude/resolve-merge-confli…
agenticassets Jan 27, 2026
432a473
Implement sandbox timeout guardrails and cost controls
claude Jan 27, 2026
9e965e2
Merge pull request #42 from agenticassets/claude/sandbox-timeout-guar…
cseagraves Jan 27, 2026
301f937
Optimize Next.js orchestration: parallelize async operations and redu…
claude Jan 27, 2026
adfbefc
Apply comprehensive Vercel React Best Practices across all 8 categories
claude Jan 27, 2026
335dc62
Fix build and lint warnings
cursoragent Jan 27, 2026
fa83632
Fix model lookup typing
cursoragent Jan 27, 2026
4a386b8
Migrate middleware to proxy
cursoragent Jan 27, 2026
fe3d571
Merge pull request #43 from agenticassets/cursor/deployment-readiness…
agenticassets Jan 27, 2026
ca52a1b
Merge pull request #44 from agenticassets/claude/optimize-nextjs-orch…
agenticassets Jan 27, 2026
a27d4ab
Apply Vercel React best practices performance optimizations
claude Jan 31, 2026
25e3626
Apply remaining Vercel React best practices optimizations
claude Jan 31, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
2,249 changes: 2,249 additions & 0 deletions .agent/skills/vercel-react-best-practices/AGENTS.md

Large diffs are not rendered by default.

125 changes: 125 additions & 0 deletions .agent/skills/vercel-react-best-practices/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
---
name: vercel-react-best-practices
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---

# Vercel React Best Practices

Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 45 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.

## When to Apply

Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
- Reviewing code for performance issues
- Refactoring existing React/Next.js code
- Optimizing bundle size or load times

## Rule Categories by Priority

| Priority | Category | Impact | Prefix |
|----------|----------|--------|--------|
| 1 | Eliminating Waterfalls | CRITICAL | `async-` |
| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
| 3 | Server-Side Performance | HIGH | `server-` |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
| 6 | Rendering Performance | MEDIUM | `rendering-` |
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
| 8 | Advanced Patterns | LOW | `advanced-` |

## Quick Reference

### 1. Eliminating Waterfalls (CRITICAL)

- `async-defer-await` - Move await into branches where actually used
- `async-parallel` - Use Promise.all() for independent operations
- `async-dependencies` - Use better-all for partial dependencies
- `async-api-routes` - Start promises early, await late in API routes
- `async-suspense-boundaries` - Use Suspense to stream content

### 2. Bundle Size Optimization (CRITICAL)

- `bundle-barrel-imports` - Import directly, avoid barrel files
- `bundle-dynamic-imports` - Use next/dynamic for heavy components
- `bundle-defer-third-party` - Load analytics/logging after hydration
- `bundle-conditional` - Load modules only when feature is activated
- `bundle-preload` - Preload on hover/focus for perceived speed

### 3. Server-Side Performance (HIGH)

- `server-cache-react` - Use React.cache() for per-request deduplication
- `server-cache-lru` - Use LRU cache for cross-request caching
- `server-serialization` - Minimize data passed to client components
- `server-parallel-fetching` - Restructure components to parallelize fetches
- `server-after-nonblocking` - Use after() for non-blocking operations

### 4. Client-Side Data Fetching (MEDIUM-HIGH)

- `client-swr-dedup` - Use SWR for automatic request deduplication
- `client-event-listeners` - Deduplicate global event listeners

### 5. Re-render Optimization (MEDIUM)

- `rerender-defer-reads` - Don't subscribe to state only used in callbacks
- `rerender-memo` - Extract expensive work into memoized components
- `rerender-dependencies` - Use primitive dependencies in effects
- `rerender-derived-state` - Subscribe to derived booleans, not raw values
- `rerender-functional-setstate` - Use functional setState for stable callbacks
- `rerender-lazy-state-init` - Pass function to useState for expensive values
- `rerender-transitions` - Use startTransition for non-urgent updates

### 6. Rendering Performance (MEDIUM)

- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
- `rendering-content-visibility` - Use content-visibility for long lists
- `rendering-hoist-jsx` - Extract static JSX outside components
- `rendering-svg-precision` - Reduce SVG coordinate precision
- `rendering-hydration-no-flicker` - Use inline script for client-only data
- `rendering-activity` - Use Activity component for show/hide
- `rendering-conditional-render` - Use ternary, not && for conditionals

### 7. JavaScript Performance (LOW-MEDIUM)

- `js-batch-dom-css` - Group CSS changes via classes or cssText
- `js-index-maps` - Build Map for repeated lookups
- `js-cache-property-access` - Cache object properties in loops
- `js-cache-function-results` - Cache function results in module-level Map
- `js-cache-storage` - Cache localStorage/sessionStorage reads
- `js-combine-iterations` - Combine multiple filter/map into one loop
- `js-length-check-first` - Check array length before expensive comparison
- `js-early-exit` - Return early from functions
- `js-hoist-regexp` - Hoist RegExp creation outside loops
- `js-min-max-loop` - Use loop for min/max instead of sort
- `js-set-map-lookups` - Use Set/Map for O(1) lookups
- `js-tosorted-immutable` - Use toSorted() for immutability

### 8. Advanced Patterns (LOW)

- `advanced-event-handler-refs` - Store event handlers in refs
- `advanced-use-latest` - useLatest for stable callback refs

## How to Use

Read individual rule files for detailed explanations and code examples:

```
rules/async-parallel.md
rules/bundle-barrel-imports.md
rules/_sections.md
```

Each rule file contains:
- Brief explanation of why it matters
- Incorrect code example with explanation
- Correct code example with explanation
- Additional context and references

## Full Compiled Document

For the complete guide with all rules expanded: `AGENTS.md`
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
---
title: Store Event Handlers in Refs
impact: LOW
impactDescription: stable subscriptions
tags: advanced, hooks, refs, event-handlers, optimization
---

## Store Event Handlers in Refs

Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.

**Incorrect (re-subscribes on every render):**

```tsx
function useWindowEvent(event: string, handler: () => void) {
useEffect(() => {
window.addEventListener(event, handler)
return () => window.removeEventListener(event, handler)
}, [event, handler])
}
```

**Correct (stable subscription):**

```tsx
function useWindowEvent(event: string, handler: () => void) {
const handlerRef = useRef(handler)
useEffect(() => {
handlerRef.current = handler
}, [handler])

useEffect(() => {
const listener = () => handlerRef.current()
window.addEventListener(event, listener)
return () => window.removeEventListener(event, listener)
}, [event])
}
```

**Alternative: use `useEffectEvent` if you're on latest React:**

```tsx
import { useEffectEvent } from 'react'

function useWindowEvent(event: string, handler: () => void) {
const onEvent = useEffectEvent(handler)

useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
```

`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
---
title: useLatest for Stable Callback Refs
impact: LOW
impactDescription: prevents effect re-runs
tags: advanced, hooks, useLatest, refs, optimization
---

## useLatest for Stable Callback Refs

Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.

**Implementation:**

```typescript
function useLatest<T>(value: T) {
const ref = useRef(value)
useEffect(() => {
ref.current = value
}, [value])
return ref
}
```

**Incorrect (effect re-runs on every callback change):**

```tsx
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')

useEffect(() => {
const timeout = setTimeout(() => onSearch(query), 300)
return () => clearTimeout(timeout)
}, [query, onSearch])
}
```

**Correct (stable effect, fresh callback):**

```tsx
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('')
const onSearchRef = useLatest(onSearch)

useEffect(() => {
const timeout = setTimeout(() => onSearchRef.current(query), 300)
return () => clearTimeout(timeout)
}, [query])
}
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
---
title: Prevent Waterfall Chains in API Routes
impact: CRITICAL
impactDescription: 2-10× improvement
tags: api-routes, server-actions, waterfalls, parallelization
---

## Prevent Waterfall Chains in API Routes

In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.

**Incorrect (config waits for auth, data waits for both):**

```typescript
export async function GET(request: Request) {
const session = await auth()
const config = await fetchConfig()
const data = await fetchData(session.user.id)
return Response.json({ data, config })
}
```

**Correct (auth and config start immediately):**

```typescript
export async function GET(request: Request) {
const sessionPromise = auth()
const configPromise = fetchConfig()
const session = await sessionPromise
const [config, data] = await Promise.all([
configPromise,
fetchData(session.user.id)
])
return Response.json({ data, config })
}
```

For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
title: Defer Await Until Needed
impact: HIGH
impactDescription: avoids blocking unused code paths
tags: async, await, conditional, optimization
---

## Defer Await Until Needed

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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
title: Dependency-Based Parallelization
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, dependencies, better-all
---

## Dependency-Based Parallelization

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)
}
})
```

Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
Loading