create-modern-react 2.3.4 → 2.3.5

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 (71) hide show
  1. package/lib/setup.js +24 -1
  2. package/package.json +4 -2
  3. package/scripts/postinstall.js +18 -0
  4. package/templates/base/.claude/skills.tar.gz +0 -0
  5. package/templates/base/.claude/skills/agent-browser/SKILL.md +0 -356
  6. package/templates/base/.claude/skills/agent-browser/references/authentication.md +0 -188
  7. package/templates/base/.claude/skills/agent-browser/references/proxy-support.md +0 -175
  8. package/templates/base/.claude/skills/agent-browser/references/session-management.md +0 -181
  9. package/templates/base/.claude/skills/agent-browser/references/snapshot-refs.md +0 -186
  10. package/templates/base/.claude/skills/agent-browser/references/video-recording.md +0 -162
  11. package/templates/base/.claude/skills/agent-browser/templates/authenticated-session.sh +0 -91
  12. package/templates/base/.claude/skills/agent-browser/templates/capture-workflow.sh +0 -68
  13. package/templates/base/.claude/skills/agent-browser/templates/form-automation.sh +0 -64
  14. package/templates/base/.claude/skills/autoskill/skill.md +0 -134
  15. package/templates/base/.claude/skills/design-principles/skill.md +0 -237
  16. package/templates/base/.claude/skills/frontend-design/skill.md +0 -42
  17. package/templates/base/.claude/skills/learn-together/skill.md +0 -448
  18. package/templates/base/.claude/skills/question-me/skill.md +0 -175
  19. package/templates/base/.claude/skills/react-best-practices/AGENTS.md +0 -2410
  20. package/templates/base/.claude/skills/react-best-practices/README.md +0 -123
  21. package/templates/base/.claude/skills/react-best-practices/SKILL.md +0 -135
  22. package/templates/base/.claude/skills/react-best-practices/metadata.json +0 -15
  23. package/templates/base/.claude/skills/react-best-practices/rules/_sections.md +0 -46
  24. package/templates/base/.claude/skills/react-best-practices/rules/_template.md +0 -28
  25. package/templates/base/.claude/skills/react-best-practices/rules/advanced-event-handler-refs.md +0 -55
  26. package/templates/base/.claude/skills/react-best-practices/rules/advanced-use-latest.md +0 -49
  27. package/templates/base/.claude/skills/react-best-practices/rules/async-api-routes.md +0 -38
  28. package/templates/base/.claude/skills/react-best-practices/rules/async-defer-await.md +0 -80
  29. package/templates/base/.claude/skills/react-best-practices/rules/async-dependencies.md +0 -36
  30. package/templates/base/.claude/skills/react-best-practices/rules/async-parallel.md +0 -28
  31. package/templates/base/.claude/skills/react-best-practices/rules/async-suspense-boundaries.md +0 -99
  32. package/templates/base/.claude/skills/react-best-practices/rules/bundle-barrel-imports.md +0 -59
  33. package/templates/base/.claude/skills/react-best-practices/rules/bundle-conditional.md +0 -31
  34. package/templates/base/.claude/skills/react-best-practices/rules/bundle-defer-third-party.md +0 -49
  35. package/templates/base/.claude/skills/react-best-practices/rules/bundle-dynamic-imports.md +0 -35
  36. package/templates/base/.claude/skills/react-best-practices/rules/bundle-preload.md +0 -50
  37. package/templates/base/.claude/skills/react-best-practices/rules/client-event-listeners.md +0 -74
  38. package/templates/base/.claude/skills/react-best-practices/rules/client-localstorage-schema.md +0 -71
  39. package/templates/base/.claude/skills/react-best-practices/rules/client-passive-event-listeners.md +0 -48
  40. package/templates/base/.claude/skills/react-best-practices/rules/client-swr-dedup.md +0 -56
  41. package/templates/base/.claude/skills/react-best-practices/rules/js-batch-dom-css.md +0 -57
  42. package/templates/base/.claude/skills/react-best-practices/rules/js-cache-function-results.md +0 -80
  43. package/templates/base/.claude/skills/react-best-practices/rules/js-cache-property-access.md +0 -28
  44. package/templates/base/.claude/skills/react-best-practices/rules/js-cache-storage.md +0 -70
  45. package/templates/base/.claude/skills/react-best-practices/rules/js-combine-iterations.md +0 -32
  46. package/templates/base/.claude/skills/react-best-practices/rules/js-early-exit.md +0 -50
  47. package/templates/base/.claude/skills/react-best-practices/rules/js-hoist-regexp.md +0 -45
  48. package/templates/base/.claude/skills/react-best-practices/rules/js-index-maps.md +0 -37
  49. package/templates/base/.claude/skills/react-best-practices/rules/js-length-check-first.md +0 -49
  50. package/templates/base/.claude/skills/react-best-practices/rules/js-min-max-loop.md +0 -82
  51. package/templates/base/.claude/skills/react-best-practices/rules/js-set-map-lookups.md +0 -24
  52. package/templates/base/.claude/skills/react-best-practices/rules/js-tosorted-immutable.md +0 -57
  53. package/templates/base/.claude/skills/react-best-practices/rules/rendering-activity.md +0 -26
  54. package/templates/base/.claude/skills/react-best-practices/rules/rendering-animate-svg-wrapper.md +0 -47
  55. package/templates/base/.claude/skills/react-best-practices/rules/rendering-conditional-render.md +0 -40
  56. package/templates/base/.claude/skills/react-best-practices/rules/rendering-content-visibility.md +0 -38
  57. package/templates/base/.claude/skills/react-best-practices/rules/rendering-hoist-jsx.md +0 -46
  58. package/templates/base/.claude/skills/react-best-practices/rules/rendering-hydration-no-flicker.md +0 -82
  59. package/templates/base/.claude/skills/react-best-practices/rules/rendering-svg-precision.md +0 -28
  60. package/templates/base/.claude/skills/react-best-practices/rules/rerender-defer-reads.md +0 -39
  61. package/templates/base/.claude/skills/react-best-practices/rules/rerender-dependencies.md +0 -45
  62. package/templates/base/.claude/skills/react-best-practices/rules/rerender-derived-state.md +0 -29
  63. package/templates/base/.claude/skills/react-best-practices/rules/rerender-functional-setstate.md +0 -74
  64. package/templates/base/.claude/skills/react-best-practices/rules/rerender-lazy-state-init.md +0 -58
  65. package/templates/base/.claude/skills/react-best-practices/rules/rerender-memo.md +0 -44
  66. package/templates/base/.claude/skills/react-best-practices/rules/rerender-transitions.md +0 -40
  67. package/templates/base/.claude/skills/react-best-practices/rules/server-after-nonblocking.md +0 -73
  68. package/templates/base/.claude/skills/react-best-practices/rules/server-cache-lru.md +0 -41
  69. package/templates/base/.claude/skills/react-best-practices/rules/server-cache-react.md +0 -76
  70. package/templates/base/.claude/skills/react-best-practices/rules/server-parallel-fetching.md +0 -83
  71. package/templates/base/.claude/skills/react-best-practices/rules/server-serialization.md +0 -38
@@ -1,38 +0,0 @@
1
- ---
2
- title: CSS content-visibility for Long Lists
3
- impact: HIGH
4
- impactDescription: faster initial render
5
- tags: rendering, css, content-visibility, long-lists
6
- ---
7
-
8
- ## CSS content-visibility for Long Lists
9
-
10
- Apply `content-visibility: auto` to defer off-screen rendering.
11
-
12
- **CSS:**
13
-
14
- ```css
15
- .message-item {
16
- content-visibility: auto;
17
- contain-intrinsic-size: 0 80px;
18
- }
19
- ```
20
-
21
- **Example:**
22
-
23
- ```tsx
24
- function MessageList({ messages }: { messages: Message[] }) {
25
- return (
26
- <div className="overflow-y-auto h-screen">
27
- {messages.map(msg => (
28
- <div key={msg.id} className="message-item">
29
- <Avatar user={msg.author} />
30
- <div>{msg.content}</div>
31
- </div>
32
- ))}
33
- </div>
34
- )
35
- }
36
- ```
37
-
38
- For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
@@ -1,46 +0,0 @@
1
- ---
2
- title: Hoist Static JSX Elements
3
- impact: LOW
4
- impactDescription: avoids re-creation
5
- tags: rendering, jsx, static, optimization
6
- ---
7
-
8
- ## Hoist Static JSX Elements
9
-
10
- Extract static JSX outside components to avoid re-creation.
11
-
12
- **Incorrect (recreates element every render):**
13
-
14
- ```tsx
15
- function LoadingSkeleton() {
16
- return <div className="animate-pulse h-20 bg-gray-200" />
17
- }
18
-
19
- function Container() {
20
- return (
21
- <div>
22
- {loading && <LoadingSkeleton />}
23
- </div>
24
- )
25
- }
26
- ```
27
-
28
- **Correct (reuses same element):**
29
-
30
- ```tsx
31
- const loadingSkeleton = (
32
- <div className="animate-pulse h-20 bg-gray-200" />
33
- )
34
-
35
- function Container() {
36
- return (
37
- <div>
38
- {loading && loadingSkeleton}
39
- </div>
40
- )
41
- }
42
- ```
43
-
44
- This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
45
-
46
- **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
@@ -1,82 +0,0 @@
1
- ---
2
- title: Prevent Hydration Mismatch Without Flickering
3
- impact: MEDIUM
4
- impactDescription: avoids visual flicker and hydration errors
5
- tags: rendering, ssr, hydration, localStorage, flicker
6
- ---
7
-
8
- ## Prevent Hydration Mismatch Without Flickering
9
-
10
- When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
11
-
12
- **Incorrect (breaks SSR):**
13
-
14
- ```tsx
15
- function ThemeWrapper({ children }: { children: ReactNode }) {
16
- // localStorage is not available on server - throws error
17
- const theme = localStorage.getItem('theme') || 'light'
18
-
19
- return (
20
- <div className={theme}>
21
- {children}
22
- </div>
23
- )
24
- }
25
- ```
26
-
27
- Server-side rendering will fail because `localStorage` is undefined.
28
-
29
- **Incorrect (visual flickering):**
30
-
31
- ```tsx
32
- function ThemeWrapper({ children }: { children: ReactNode }) {
33
- const [theme, setTheme] = useState('light')
34
-
35
- useEffect(() => {
36
- // Runs after hydration - causes visible flash
37
- const stored = localStorage.getItem('theme')
38
- if (stored) {
39
- setTheme(stored)
40
- }
41
- }, [])
42
-
43
- return (
44
- <div className={theme}>
45
- {children}
46
- </div>
47
- )
48
- }
49
- ```
50
-
51
- Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
52
-
53
- **Correct (no flicker, no hydration mismatch):**
54
-
55
- ```tsx
56
- function ThemeWrapper({ children }: { children: ReactNode }) {
57
- return (
58
- <>
59
- <div id="theme-wrapper">
60
- {children}
61
- </div>
62
- <script
63
- dangerouslySetInnerHTML={{
64
- __html: `
65
- (function() {
66
- try {
67
- var theme = localStorage.getItem('theme') || 'light';
68
- var el = document.getElementById('theme-wrapper');
69
- if (el) el.className = theme;
70
- } catch (e) {}
71
- })();
72
- `,
73
- }}
74
- />
75
- </>
76
- )
77
- }
78
- ```
79
-
80
- The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
81
-
82
- This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
@@ -1,28 +0,0 @@
1
- ---
2
- title: Optimize SVG Precision
3
- impact: LOW
4
- impactDescription: reduces file size
5
- tags: rendering, svg, optimization, svgo
6
- ---
7
-
8
- ## Optimize SVG Precision
9
-
10
- Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
11
-
12
- **Incorrect (excessive precision):**
13
-
14
- ```svg
15
- <path d="M 10.293847 20.847362 L 30.938472 40.192837" />
16
- ```
17
-
18
- **Correct (1 decimal place):**
19
-
20
- ```svg
21
- <path d="M 10.3 20.8 L 30.9 40.2" />
22
- ```
23
-
24
- **Automate with SVGO:**
25
-
26
- ```bash
27
- npx svgo --precision=1 --multipass icon.svg
28
- ```
@@ -1,39 +0,0 @@
1
- ---
2
- title: Defer State Reads to Usage Point
3
- impact: MEDIUM
4
- impactDescription: avoids unnecessary subscriptions
5
- tags: rerender, searchParams, localStorage, optimization
6
- ---
7
-
8
- ## Defer State Reads to Usage Point
9
-
10
- Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
11
-
12
- **Incorrect (subscribes to all searchParams changes):**
13
-
14
- ```tsx
15
- function ShareButton({ chatId }: { chatId: string }) {
16
- const searchParams = useSearchParams()
17
-
18
- const handleShare = () => {
19
- const ref = searchParams.get('ref')
20
- shareChat(chatId, { ref })
21
- }
22
-
23
- return <button onClick={handleShare}>Share</button>
24
- }
25
- ```
26
-
27
- **Correct (reads on demand, no subscription):**
28
-
29
- ```tsx
30
- function ShareButton({ chatId }: { chatId: string }) {
31
- const handleShare = () => {
32
- const params = new URLSearchParams(window.location.search)
33
- const ref = params.get('ref')
34
- shareChat(chatId, { ref })
35
- }
36
-
37
- return <button onClick={handleShare}>Share</button>
38
- }
39
- ```
@@ -1,45 +0,0 @@
1
- ---
2
- title: Narrow Effect Dependencies
3
- impact: LOW
4
- impactDescription: minimizes effect re-runs
5
- tags: rerender, useEffect, dependencies, optimization
6
- ---
7
-
8
- ## Narrow Effect Dependencies
9
-
10
- Specify primitive dependencies instead of objects to minimize effect re-runs.
11
-
12
- **Incorrect (re-runs on any user field change):**
13
-
14
- ```tsx
15
- useEffect(() => {
16
- console.log(user.id)
17
- }, [user])
18
- ```
19
-
20
- **Correct (re-runs only when id changes):**
21
-
22
- ```tsx
23
- useEffect(() => {
24
- console.log(user.id)
25
- }, [user.id])
26
- ```
27
-
28
- **For derived state, compute outside effect:**
29
-
30
- ```tsx
31
- // Incorrect: runs on width=767, 766, 765...
32
- useEffect(() => {
33
- if (width < 768) {
34
- enableMobileMode()
35
- }
36
- }, [width])
37
-
38
- // Correct: runs only on boolean transition
39
- const isMobile = width < 768
40
- useEffect(() => {
41
- if (isMobile) {
42
- enableMobileMode()
43
- }
44
- }, [isMobile])
45
- ```
@@ -1,29 +0,0 @@
1
- ---
2
- title: Subscribe to Derived State
3
- impact: MEDIUM
4
- impactDescription: reduces re-render frequency
5
- tags: rerender, derived-state, media-query, optimization
6
- ---
7
-
8
- ## Subscribe to Derived State
9
-
10
- Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
11
-
12
- **Incorrect (re-renders on every pixel change):**
13
-
14
- ```tsx
15
- function Sidebar() {
16
- const width = useWindowWidth() // updates continuously
17
- const isMobile = width < 768
18
- return <nav className={isMobile ? 'mobile' : 'desktop'} />
19
- }
20
- ```
21
-
22
- **Correct (re-renders only when boolean changes):**
23
-
24
- ```tsx
25
- function Sidebar() {
26
- const isMobile = useMediaQuery('(max-width: 767px)')
27
- return <nav className={isMobile ? 'mobile' : 'desktop'} />
28
- }
29
- ```
@@ -1,74 +0,0 @@
1
- ---
2
- title: Use Functional setState Updates
3
- impact: MEDIUM
4
- impactDescription: prevents stale closures and unnecessary callback recreations
5
- tags: react, hooks, useState, useCallback, callbacks, closures
6
- ---
7
-
8
- ## Use Functional setState Updates
9
-
10
- When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
11
-
12
- **Incorrect (requires state as dependency):**
13
-
14
- ```tsx
15
- function TodoList() {
16
- const [items, setItems] = useState(initialItems)
17
-
18
- // Callback must depend on items, recreated on every items change
19
- const addItems = useCallback((newItems: Item[]) => {
20
- setItems([...items, ...newItems])
21
- }, [items]) // ❌ items dependency causes recreations
22
-
23
- // Risk of stale closure if dependency is forgotten
24
- const removeItem = useCallback((id: string) => {
25
- setItems(items.filter(item => item.id !== id))
26
- }, []) // ❌ Missing items dependency - will use stale items!
27
-
28
- return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
29
- }
30
- ```
31
-
32
- The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
33
-
34
- **Correct (stable callbacks, no stale closures):**
35
-
36
- ```tsx
37
- function TodoList() {
38
- const [items, setItems] = useState(initialItems)
39
-
40
- // Stable callback, never recreated
41
- const addItems = useCallback((newItems: Item[]) => {
42
- setItems(curr => [...curr, ...newItems])
43
- }, []) // ✅ No dependencies needed
44
-
45
- // Always uses latest state, no stale closure risk
46
- const removeItem = useCallback((id: string) => {
47
- setItems(curr => curr.filter(item => item.id !== id))
48
- }, []) // ✅ Safe and stable
49
-
50
- return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
51
- }
52
- ```
53
-
54
- **Benefits:**
55
-
56
- 1. **Stable callback references** - Callbacks don't need to be recreated when state changes
57
- 2. **No stale closures** - Always operates on the latest state value
58
- 3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
59
- 4. **Prevents bugs** - Eliminates the most common source of React closure bugs
60
-
61
- **When to use functional updates:**
62
-
63
- - Any setState that depends on the current state value
64
- - Inside useCallback/useMemo when state is needed
65
- - Event handlers that reference state
66
- - Async operations that update state
67
-
68
- **When direct updates are fine:**
69
-
70
- - Setting state to a static value: `setCount(0)`
71
- - Setting state from props/arguments only: `setName(newName)`
72
- - State doesn't depend on previous value
73
-
74
- **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
@@ -1,58 +0,0 @@
1
- ---
2
- title: Use Lazy State Initialization
3
- impact: MEDIUM
4
- impactDescription: wasted computation on every render
5
- tags: react, hooks, useState, performance, initialization
6
- ---
7
-
8
- ## Use Lazy State Initialization
9
-
10
- Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
11
-
12
- **Incorrect (runs on every render):**
13
-
14
- ```tsx
15
- function FilteredList({ items }: { items: Item[] }) {
16
- // buildSearchIndex() runs on EVERY render, even after initialization
17
- const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
18
- const [query, setQuery] = useState('')
19
-
20
- // When query changes, buildSearchIndex runs again unnecessarily
21
- return <SearchResults index={searchIndex} query={query} />
22
- }
23
-
24
- function UserProfile() {
25
- // JSON.parse runs on every render
26
- const [settings, setSettings] = useState(
27
- JSON.parse(localStorage.getItem('settings') || '{}')
28
- )
29
-
30
- return <SettingsForm settings={settings} onChange={setSettings} />
31
- }
32
- ```
33
-
34
- **Correct (runs only once):**
35
-
36
- ```tsx
37
- function FilteredList({ items }: { items: Item[] }) {
38
- // buildSearchIndex() runs ONLY on initial render
39
- const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
40
- const [query, setQuery] = useState('')
41
-
42
- return <SearchResults index={searchIndex} query={query} />
43
- }
44
-
45
- function UserProfile() {
46
- // JSON.parse runs only on initial render
47
- const [settings, setSettings] = useState(() => {
48
- const stored = localStorage.getItem('settings')
49
- return stored ? JSON.parse(stored) : {}
50
- })
51
-
52
- return <SettingsForm settings={settings} onChange={setSettings} />
53
- }
54
- ```
55
-
56
- Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
57
-
58
- For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
@@ -1,44 +0,0 @@
1
- ---
2
- title: Extract to Memoized Components
3
- impact: MEDIUM
4
- impactDescription: enables early returns
5
- tags: rerender, memo, useMemo, optimization
6
- ---
7
-
8
- ## Extract to Memoized Components
9
-
10
- Extract expensive work into memoized components to enable early returns before computation.
11
-
12
- **Incorrect (computes avatar even when loading):**
13
-
14
- ```tsx
15
- function Profile({ user, loading }: Props) {
16
- const avatar = useMemo(() => {
17
- const id = computeAvatarId(user)
18
- return <Avatar id={id} />
19
- }, [user])
20
-
21
- if (loading) return <Skeleton />
22
- return <div>{avatar}</div>
23
- }
24
- ```
25
-
26
- **Correct (skips computation when loading):**
27
-
28
- ```tsx
29
- const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
30
- const id = useMemo(() => computeAvatarId(user), [user])
31
- return <Avatar id={id} />
32
- })
33
-
34
- function Profile({ user, loading }: Props) {
35
- if (loading) return <Skeleton />
36
- return (
37
- <div>
38
- <UserAvatar user={user} />
39
- </div>
40
- )
41
- }
42
- ```
43
-
44
- **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.
@@ -1,40 +0,0 @@
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
- ```
@@ -1,73 +0,0 @@
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)
@@ -1,41 +0,0 @@
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)