create-quadrokit 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -3
  3. package/template-common/.agents/skills/quadro-paged-collection/SKILL.md +33 -0
  4. package/template-common/.agents/skills/vercel-composition-patterns/AGENTS.md +946 -0
  5. package/template-common/.agents/skills/vercel-composition-patterns/README.md +60 -0
  6. package/template-common/.agents/skills/vercel-composition-patterns/SKILL.md +89 -0
  7. package/template-common/.agents/skills/vercel-composition-patterns/rules/_sections.md +29 -0
  8. package/template-common/.agents/skills/vercel-composition-patterns/rules/_template.md +24 -0
  9. package/template-common/.agents/skills/vercel-composition-patterns/rules/architecture-avoid-boolean-props.md +100 -0
  10. package/template-common/.agents/skills/vercel-composition-patterns/rules/architecture-compound-components.md +112 -0
  11. package/template-common/.agents/skills/vercel-composition-patterns/rules/patterns-children-over-render-props.md +87 -0
  12. package/template-common/.agents/skills/vercel-composition-patterns/rules/patterns-explicit-variants.md +100 -0
  13. package/template-common/.agents/skills/vercel-composition-patterns/rules/react19-no-forwardref.md +42 -0
  14. package/template-common/.agents/skills/vercel-composition-patterns/rules/state-context-interface.md +191 -0
  15. package/template-common/.agents/skills/vercel-composition-patterns/rules/state-decouple-implementation.md +113 -0
  16. package/template-common/.agents/skills/vercel-composition-patterns/rules/state-lift-state.md +125 -0
  17. package/template-common/.agents/skills/vercel-react-best-practices/AGENTS.md +3750 -0
  18. package/template-common/.agents/skills/vercel-react-best-practices/README.md +123 -0
  19. package/template-common/.agents/skills/vercel-react-best-practices/SKILL.md +148 -0
  20. package/template-common/.agents/skills/vercel-react-best-practices/rules/_sections.md +46 -0
  21. package/template-common/.agents/skills/vercel-react-best-practices/rules/_template.md +28 -0
  22. package/template-common/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md +56 -0
  23. package/template-common/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +55 -0
  24. package/template-common/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md +42 -0
  25. package/template-common/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md +39 -0
  26. package/template-common/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md +38 -0
  27. package/template-common/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md +37 -0
  28. package/template-common/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md +82 -0
  29. package/template-common/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md +51 -0
  30. package/template-common/.agents/skills/vercel-react-best-practices/rules/async-parallel.md +28 -0
  31. package/template-common/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +99 -0
  32. package/template-common/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +60 -0
  33. package/template-common/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md +31 -0
  34. package/template-common/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +49 -0
  35. package/template-common/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +35 -0
  36. package/template-common/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md +50 -0
  37. package/template-common/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md +74 -0
  38. package/template-common/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +71 -0
  39. package/template-common/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +48 -0
  40. package/template-common/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md +56 -0
  41. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +107 -0
  42. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md +80 -0
  43. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md +28 -0
  44. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md +70 -0
  45. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md +32 -0
  46. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md +50 -0
  47. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md +60 -0
  48. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +45 -0
  49. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md +37 -0
  50. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md +49 -0
  51. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md +82 -0
  52. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md +105 -0
  53. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +24 -0
  54. package/template-common/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +57 -0
  55. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md +26 -0
  56. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
  57. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +40 -0
  58. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +38 -0
  59. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +46 -0
  60. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +82 -0
  61. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md +30 -0
  62. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md +85 -0
  63. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md +68 -0
  64. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +28 -0
  65. package/template-common/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md +75 -0
  66. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +39 -0
  67. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md +45 -0
  68. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md +40 -0
  69. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md +29 -0
  70. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +74 -0
  71. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +58 -0
  72. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md +38 -0
  73. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md +44 -0
  74. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md +45 -0
  75. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md +82 -0
  76. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +35 -0
  77. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md +64 -0
  78. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md +40 -0
  79. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md +59 -0
  80. package/template-common/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md +73 -0
  81. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +73 -0
  82. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md +96 -0
  83. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md +41 -0
  84. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md +76 -0
  85. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md +65 -0
  86. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md +149 -0
  87. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md +50 -0
  88. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +83 -0
  89. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md +34 -0
  90. package/template-common/.agents/skills/vercel-react-best-practices/rules/server-serialization.md +38 -0
  91. package/template-common/.agents/skills/web-design-guidelines/SKILL.md +39 -0
  92. package/template-common/skills-lock.json +20 -0
@@ -0,0 +1,40 @@
1
+ ---
2
+ title: Use Transitions for Non-Urgent Updates
3
+ impact: MEDIUM
4
+ impactDescription: maintains UI responsiveness
5
+ tags: rerender, transitions, startTransition, performance
6
+ ---
7
+
8
+ ## Use Transitions for Non-Urgent Updates
9
+
10
+ Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
11
+
12
+ **Incorrect (blocks UI on every scroll):**
13
+
14
+ ```tsx
15
+ function ScrollTracker() {
16
+ const [scrollY, setScrollY] = useState(0)
17
+ useEffect(() => {
18
+ const handler = () => setScrollY(window.scrollY)
19
+ window.addEventListener('scroll', handler, { passive: true })
20
+ return () => window.removeEventListener('scroll', handler)
21
+ }, [])
22
+ }
23
+ ```
24
+
25
+ **Correct (non-blocking updates):**
26
+
27
+ ```tsx
28
+ import { startTransition } from 'react'
29
+
30
+ function ScrollTracker() {
31
+ const [scrollY, setScrollY] = useState(0)
32
+ useEffect(() => {
33
+ const handler = () => {
34
+ startTransition(() => setScrollY(window.scrollY))
35
+ }
36
+ window.addEventListener('scroll', handler, { passive: true })
37
+ return () => window.removeEventListener('scroll', handler)
38
+ }, [])
39
+ }
40
+ ```
@@ -0,0 +1,59 @@
1
+ ---
2
+ title: Use useDeferredValue for Expensive Derived Renders
3
+ impact: MEDIUM
4
+ impactDescription: keeps input responsive during heavy computation
5
+ tags: rerender, useDeferredValue, optimization, concurrent
6
+ ---
7
+
8
+ ## Use useDeferredValue for Expensive Derived Renders
9
+
10
+ When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
11
+
12
+ **Incorrect (input feels laggy while filtering):**
13
+
14
+ ```tsx
15
+ function Search({ items }: { items: Item[] }) {
16
+ const [query, setQuery] = useState('')
17
+ const filtered = items.filter(item => fuzzyMatch(item, query))
18
+
19
+ return (
20
+ <>
21
+ <input value={query} onChange={e => setQuery(e.target.value)} />
22
+ <ResultsList results={filtered} />
23
+ </>
24
+ )
25
+ }
26
+ ```
27
+
28
+ **Correct (input stays snappy, results render when ready):**
29
+
30
+ ```tsx
31
+ function Search({ items }: { items: Item[] }) {
32
+ const [query, setQuery] = useState('')
33
+ const deferredQuery = useDeferredValue(query)
34
+ const filtered = useMemo(
35
+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),
36
+ [items, deferredQuery]
37
+ )
38
+ const isStale = query !== deferredQuery
39
+
40
+ return (
41
+ <>
42
+ <input value={query} onChange={e => setQuery(e.target.value)} />
43
+ <div style={{ opacity: isStale ? 0.7 : 1 }}>
44
+ <ResultsList results={filtered} />
45
+ </div>
46
+ </>
47
+ )
48
+ }
49
+ ```
50
+
51
+ **When to use:**
52
+
53
+ - Filtering/searching large lists
54
+ - Expensive visualizations (charts, graphs) reacting to input
55
+ - Any derived state that causes noticeable render delays
56
+
57
+ **Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
58
+
59
+ Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
@@ -0,0 +1,73 @@
1
+ ---
2
+ title: Use useRef for Transient Values
3
+ impact: MEDIUM
4
+ impactDescription: avoids unnecessary re-renders on frequent updates
5
+ tags: rerender, useref, state, performance
6
+ ---
7
+
8
+ ## Use useRef for Transient Values
9
+
10
+ When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
11
+
12
+ **Incorrect (renders every update):**
13
+
14
+ ```tsx
15
+ function Tracker() {
16
+ const [lastX, setLastX] = useState(0)
17
+
18
+ useEffect(() => {
19
+ const onMove = (e: MouseEvent) => setLastX(e.clientX)
20
+ window.addEventListener('mousemove', onMove)
21
+ return () => window.removeEventListener('mousemove', onMove)
22
+ }, [])
23
+
24
+ return (
25
+ <div
26
+ style={{
27
+ position: 'fixed',
28
+ top: 0,
29
+ left: lastX,
30
+ width: 8,
31
+ height: 8,
32
+ background: 'black',
33
+ }}
34
+ />
35
+ )
36
+ }
37
+ ```
38
+
39
+ **Correct (no re-render for tracking):**
40
+
41
+ ```tsx
42
+ function Tracker() {
43
+ const lastXRef = useRef(0)
44
+ const dotRef = useRef<HTMLDivElement>(null)
45
+
46
+ useEffect(() => {
47
+ const onMove = (e: MouseEvent) => {
48
+ lastXRef.current = e.clientX
49
+ const node = dotRef.current
50
+ if (node) {
51
+ node.style.transform = `translateX(${e.clientX}px)`
52
+ }
53
+ }
54
+ window.addEventListener('mousemove', onMove)
55
+ return () => window.removeEventListener('mousemove', onMove)
56
+ }, [])
57
+
58
+ return (
59
+ <div
60
+ ref={dotRef}
61
+ style={{
62
+ position: 'fixed',
63
+ top: 0,
64
+ left: 0,
65
+ width: 8,
66
+ height: 8,
67
+ background: 'black',
68
+ transform: 'translateX(0px)',
69
+ }}
70
+ />
71
+ )
72
+ }
73
+ ```
@@ -0,0 +1,73 @@
1
+ ---
2
+ title: Use after() for Non-Blocking Operations
3
+ impact: MEDIUM
4
+ impactDescription: faster response times
5
+ tags: server, async, logging, analytics, side-effects
6
+ ---
7
+
8
+ ## Use after() for Non-Blocking Operations
9
+
10
+ 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.
11
+
12
+ **Incorrect (blocks response):**
13
+
14
+ ```tsx
15
+ import { logUserAction } from '@/app/utils'
16
+
17
+ export async function POST(request: Request) {
18
+ // Perform mutation
19
+ await updateDatabase(request)
20
+
21
+ // Logging blocks the response
22
+ const userAgent = request.headers.get('user-agent') || 'unknown'
23
+ await logUserAction({ userAgent })
24
+
25
+ return new Response(JSON.stringify({ status: 'success' }), {
26
+ status: 200,
27
+ headers: { 'Content-Type': 'application/json' }
28
+ })
29
+ }
30
+ ```
31
+
32
+ **Correct (non-blocking):**
33
+
34
+ ```tsx
35
+ import { after } from 'next/server'
36
+ import { headers, cookies } from 'next/headers'
37
+ import { logUserAction } from '@/app/utils'
38
+
39
+ export async function POST(request: Request) {
40
+ // Perform mutation
41
+ await updateDatabase(request)
42
+
43
+ // Log after response is sent
44
+ after(async () => {
45
+ const userAgent = (await headers()).get('user-agent') || 'unknown'
46
+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
47
+
48
+ logUserAction({ sessionCookie, userAgent })
49
+ })
50
+
51
+ return new Response(JSON.stringify({ status: 'success' }), {
52
+ status: 200,
53
+ headers: { 'Content-Type': 'application/json' }
54
+ })
55
+ }
56
+ ```
57
+
58
+ The response is sent immediately while logging happens in the background.
59
+
60
+ **Common use cases:**
61
+
62
+ - Analytics tracking
63
+ - Audit logging
64
+ - Sending notifications
65
+ - Cache invalidation
66
+ - Cleanup tasks
67
+
68
+ **Important notes:**
69
+
70
+ - `after()` runs even if the response fails or redirects
71
+ - Works in Server Actions, Route Handlers, and Server Components
72
+
73
+ Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
@@ -0,0 +1,96 @@
1
+ ---
2
+ title: Authenticate Server Actions Like API Routes
3
+ impact: CRITICAL
4
+ impactDescription: prevents unauthorized access to server mutations
5
+ tags: server, server-actions, authentication, security, authorization
6
+ ---
7
+
8
+ ## Authenticate Server Actions Like API Routes
9
+
10
+ **Impact: CRITICAL (prevents unauthorized access to server mutations)**
11
+
12
+ 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.
13
+
14
+ 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."
15
+
16
+ **Incorrect (no authentication check):**
17
+
18
+ ```typescript
19
+ 'use server'
20
+
21
+ export async function deleteUser(userId: string) {
22
+ // Anyone can call this! No auth check
23
+ await db.user.delete({ where: { id: userId } })
24
+ return { success: true }
25
+ }
26
+ ```
27
+
28
+ **Correct (authentication inside the action):**
29
+
30
+ ```typescript
31
+ 'use server'
32
+
33
+ import { verifySession } from '@/lib/auth'
34
+ import { unauthorized } from '@/lib/errors'
35
+
36
+ export async function deleteUser(userId: string) {
37
+ // Always check auth inside the action
38
+ const session = await verifySession()
39
+
40
+ if (!session) {
41
+ throw unauthorized('Must be logged in')
42
+ }
43
+
44
+ // Check authorization too
45
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
46
+ throw unauthorized('Cannot delete other users')
47
+ }
48
+
49
+ await db.user.delete({ where: { id: userId } })
50
+ return { success: true }
51
+ }
52
+ ```
53
+
54
+ **With input validation:**
55
+
56
+ ```typescript
57
+ 'use server'
58
+
59
+ import { verifySession } from '@/lib/auth'
60
+ import { z } from 'zod'
61
+
62
+ const updateProfileSchema = z.object({
63
+ userId: z.string().uuid(),
64
+ name: z.string().min(1).max(100),
65
+ email: z.string().email()
66
+ })
67
+
68
+ export async function updateProfile(data: unknown) {
69
+ // Validate input first
70
+ const validated = updateProfileSchema.parse(data)
71
+
72
+ // Then authenticate
73
+ const session = await verifySession()
74
+ if (!session) {
75
+ throw new Error('Unauthorized')
76
+ }
77
+
78
+ // Then authorize
79
+ if (session.user.id !== validated.userId) {
80
+ throw new Error('Can only update own profile')
81
+ }
82
+
83
+ // Finally perform the mutation
84
+ await db.user.update({
85
+ where: { id: validated.userId },
86
+ data: {
87
+ name: validated.name,
88
+ email: validated.email
89
+ }
90
+ })
91
+
92
+ return { success: true }
93
+ }
94
+ ```
95
+
96
+ Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
@@ -0,0 +1,41 @@
1
+ ---
2
+ title: Cross-Request LRU Caching
3
+ impact: HIGH
4
+ impactDescription: caches across requests
5
+ tags: server, cache, lru, cross-request
6
+ ---
7
+
8
+ ## Cross-Request LRU Caching
9
+
10
+ `React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
11
+
12
+ **Implementation:**
13
+
14
+ ```typescript
15
+ import { LRUCache } from 'lru-cache'
16
+
17
+ const cache = new LRUCache<string, any>({
18
+ max: 1000,
19
+ ttl: 5 * 60 * 1000 // 5 minutes
20
+ })
21
+
22
+ export async function getUser(id: string) {
23
+ const cached = cache.get(id)
24
+ if (cached) return cached
25
+
26
+ const user = await db.user.findUnique({ where: { id } })
27
+ cache.set(id, user)
28
+ return user
29
+ }
30
+
31
+ // Request 1: DB query, result cached
32
+ // Request 2: cache hit, no DB query
33
+ ```
34
+
35
+ Use when sequential user actions hit multiple endpoints needing the same data within seconds.
36
+
37
+ **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.
38
+
39
+ **In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
40
+
41
+ Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
@@ -0,0 +1,76 @@
1
+ ---
2
+ title: Per-Request Deduplication with React.cache()
3
+ impact: MEDIUM
4
+ impactDescription: deduplicates within request
5
+ tags: server, cache, react-cache, deduplication
6
+ ---
7
+
8
+ ## Per-Request Deduplication with React.cache()
9
+
10
+ Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
11
+
12
+ **Usage:**
13
+
14
+ ```typescript
15
+ import { cache } from 'react'
16
+
17
+ export const getCurrentUser = cache(async () => {
18
+ const session = await auth()
19
+ if (!session?.user?.id) return null
20
+ return await db.user.findUnique({
21
+ where: { id: session.user.id }
22
+ })
23
+ })
24
+ ```
25
+
26
+ Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
27
+
28
+ **Avoid inline objects as arguments:**
29
+
30
+ `React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
31
+
32
+ **Incorrect (always cache miss):**
33
+
34
+ ```typescript
35
+ const getUser = cache(async (params: { uid: number }) => {
36
+ return await db.user.findUnique({ where: { id: params.uid } })
37
+ })
38
+
39
+ // Each call creates new object, never hits cache
40
+ getUser({ uid: 1 })
41
+ getUser({ uid: 1 }) // Cache miss, runs query again
42
+ ```
43
+
44
+ **Correct (cache hit):**
45
+
46
+ ```typescript
47
+ const getUser = cache(async (uid: number) => {
48
+ return await db.user.findUnique({ where: { id: uid } })
49
+ })
50
+
51
+ // Primitive args use value equality
52
+ getUser(1)
53
+ getUser(1) // Cache hit, returns cached result
54
+ ```
55
+
56
+ If you must pass objects, pass the same reference:
57
+
58
+ ```typescript
59
+ const params = { uid: 1 }
60
+ getUser(params) // Query runs
61
+ getUser(params) // Cache hit (same reference)
62
+ ```
63
+
64
+ **Next.js-Specific Note:**
65
+
66
+ 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:
67
+
68
+ - Database queries (Prisma, Drizzle, etc.)
69
+ - Heavy computations
70
+ - Authentication checks
71
+ - File system operations
72
+ - Any non-fetch async work
73
+
74
+ Use `React.cache()` to deduplicate these operations across your component tree.
75
+
76
+ Reference: [React.cache documentation](https://react.dev/reference/react/cache)
@@ -0,0 +1,65 @@
1
+ ---
2
+ title: Avoid Duplicate Serialization in RSC Props
3
+ impact: LOW
4
+ impactDescription: reduces network payload by avoiding duplicate serialization
5
+ tags: server, rsc, serialization, props, client-components
6
+ ---
7
+
8
+ ## Avoid Duplicate Serialization in RSC Props
9
+
10
+ **Impact: LOW (reduces network payload by avoiding duplicate serialization)**
11
+
12
+ 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.
13
+
14
+ **Incorrect (duplicates array):**
15
+
16
+ ```tsx
17
+ // RSC: sends 6 strings (2 arrays × 3 items)
18
+ <ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
19
+ ```
20
+
21
+ **Correct (sends 3 strings):**
22
+
23
+ ```tsx
24
+ // RSC: send once
25
+ <ClientList usernames={usernames} />
26
+
27
+ // Client: transform there
28
+ 'use client'
29
+ const sorted = useMemo(() => [...usernames].sort(), [usernames])
30
+ ```
31
+
32
+ **Nested deduplication behavior:**
33
+
34
+ Deduplication works recursively. Impact varies by data type:
35
+
36
+ - `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
37
+ - `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
38
+
39
+ ```tsx
40
+ // string[] - duplicates everything
41
+ usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
42
+
43
+ // object[] - duplicates array structure only
44
+ users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
45
+ ```
46
+
47
+ **Operations breaking deduplication (create new references):**
48
+
49
+ - Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
50
+ - Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
51
+
52
+ **More examples:**
53
+
54
+ ```tsx
55
+ // ❌ Bad
56
+ <C users={users} active={users.filter(u => u.active)} />
57
+ <C product={product} productName={product.name} />
58
+
59
+ // ✅ Good
60
+ <C users={users} />
61
+ <C product={product} />
62
+ // Do filtering/destructuring in client
63
+ ```
64
+
65
+ **Exception:** Pass derived data when transformation is expensive or client doesn't need original.
@@ -0,0 +1,149 @@
1
+ ---
2
+ title: Hoist Static I/O to Module Level
3
+ impact: HIGH
4
+ impactDescription: avoids repeated file/network I/O per request
5
+ tags: server, io, performance, next.js, route-handlers, og-image
6
+ ---
7
+
8
+ ## Hoist Static I/O to Module Level
9
+
10
+ **Impact: HIGH (avoids repeated file/network I/O per request)**
11
+
12
+ 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.
13
+
14
+ **Incorrect (reads font file on every request):**
15
+
16
+ ```typescript
17
+ // app/api/og/route.tsx
18
+ import { ImageResponse } from 'next/og'
19
+
20
+ export async function GET(request: Request) {
21
+ // Runs on EVERY request - expensive!
22
+ const fontData = await fetch(
23
+ new URL('./fonts/Inter.ttf', import.meta.url)
24
+ ).then(res => res.arrayBuffer())
25
+
26
+ const logoData = await fetch(
27
+ new URL('./images/logo.png', import.meta.url)
28
+ ).then(res => res.arrayBuffer())
29
+
30
+ return new ImageResponse(
31
+ <div style={{ fontFamily: 'Inter' }}>
32
+ <img src={logoData} />
33
+ Hello World
34
+ </div>,
35
+ { fonts: [{ name: 'Inter', data: fontData }] }
36
+ )
37
+ }
38
+ ```
39
+
40
+ **Correct (loads once at module initialization):**
41
+
42
+ ```typescript
43
+ // app/api/og/route.tsx
44
+ import { ImageResponse } from 'next/og'
45
+
46
+ // Module-level: runs ONCE when module is first imported
47
+ const fontData = fetch(
48
+ new URL('./fonts/Inter.ttf', import.meta.url)
49
+ ).then(res => res.arrayBuffer())
50
+
51
+ const logoData = fetch(
52
+ new URL('./images/logo.png', import.meta.url)
53
+ ).then(res => res.arrayBuffer())
54
+
55
+ export async function GET(request: Request) {
56
+ // Await the already-started promises
57
+ const [font, logo] = await Promise.all([fontData, logoData])
58
+
59
+ return new ImageResponse(
60
+ <div style={{ fontFamily: 'Inter' }}>
61
+ <img src={logo} />
62
+ Hello World
63
+ </div>,
64
+ { fonts: [{ name: 'Inter', data: font }] }
65
+ )
66
+ }
67
+ ```
68
+
69
+ **Correct (synchronous fs at module level):**
70
+
71
+ ```typescript
72
+ // app/api/og/route.tsx
73
+ import { ImageResponse } from 'next/og'
74
+ import { readFileSync } from 'fs'
75
+ import { join } from 'path'
76
+
77
+ // Synchronous read at module level - blocks only during module init
78
+ const fontData = readFileSync(
79
+ join(process.cwd(), 'public/fonts/Inter.ttf')
80
+ )
81
+
82
+ const logoData = readFileSync(
83
+ join(process.cwd(), 'public/images/logo.png')
84
+ )
85
+
86
+ export async function GET(request: Request) {
87
+ return new ImageResponse(
88
+ <div style={{ fontFamily: 'Inter' }}>
89
+ <img src={logoData} />
90
+ Hello World
91
+ </div>,
92
+ { fonts: [{ name: 'Inter', data: fontData }] }
93
+ )
94
+ }
95
+ ```
96
+
97
+ **Incorrect (reads config on every call):**
98
+
99
+ ```typescript
100
+ import fs from 'node:fs/promises'
101
+
102
+ export async function processRequest(data: Data) {
103
+ const config = JSON.parse(
104
+ await fs.readFile('./config.json', 'utf-8')
105
+ )
106
+ const template = await fs.readFile('./template.html', 'utf-8')
107
+
108
+ return render(template, data, config)
109
+ }
110
+ ```
111
+
112
+ **Correct (hoists config and template to module level):**
113
+
114
+ ```typescript
115
+ import fs from 'node:fs/promises'
116
+
117
+ const configPromise = fs
118
+ .readFile('./config.json', 'utf-8')
119
+ .then(JSON.parse)
120
+ const templatePromise = fs.readFile('./template.html', 'utf-8')
121
+
122
+ export async function processRequest(data: Data) {
123
+ const [config, template] = await Promise.all([
124
+ configPromise,
125
+ templatePromise,
126
+ ])
127
+
128
+ return render(template, data, config)
129
+ }
130
+ ```
131
+
132
+ When to use this pattern:
133
+
134
+ - Loading fonts for OG image generation
135
+ - Loading static logos, icons, or watermarks
136
+ - Reading configuration files that don't change at runtime
137
+ - Loading email templates or other static templates
138
+ - Any static asset that's the same across all requests
139
+
140
+ When not to use this pattern:
141
+
142
+ - Assets that vary per request or user
143
+ - Files that may change during runtime (use caching with TTL instead)
144
+ - Large files that would consume too much memory if kept loaded
145
+ - Sensitive data that shouldn't persist in memory
146
+
147
+ 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.
148
+
149
+ In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.