agents-config 1.1.0 → 1.1.1
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.
- package/README.md +8 -3
- package/package.json +1 -1
- package/skills/vercel-react-best-practices/AGENTS.md +0 -2719
- package/skills/vercel-react-best-practices/SKILL.md +0 -125
- package/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +0 -55
- package/skills/vercel-react-best-practices/rules/advanced-use-latest.md +0 -39
- package/skills/vercel-react-best-practices/rules/async-api-routes.md +0 -38
- package/skills/vercel-react-best-practices/rules/async-defer-await.md +0 -80
- package/skills/vercel-react-best-practices/rules/async-dependencies.md +0 -51
- package/skills/vercel-react-best-practices/rules/async-parallel.md +0 -28
- package/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +0 -99
- package/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +0 -59
- package/skills/vercel-react-best-practices/rules/bundle-conditional.md +0 -31
- package/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +0 -49
- package/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +0 -35
- package/skills/vercel-react-best-practices/rules/bundle-preload.md +0 -50
- package/skills/vercel-react-best-practices/rules/client-event-listeners.md +0 -74
- package/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +0 -71
- package/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +0 -48
- package/skills/vercel-react-best-practices/rules/client-swr-dedup.md +0 -56
- package/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +0 -107
- package/skills/vercel-react-best-practices/rules/js-cache-function-results.md +0 -80
- package/skills/vercel-react-best-practices/rules/js-cache-property-access.md +0 -28
- package/skills/vercel-react-best-practices/rules/js-cache-storage.md +0 -70
- package/skills/vercel-react-best-practices/rules/js-combine-iterations.md +0 -32
- package/skills/vercel-react-best-practices/rules/js-early-exit.md +0 -50
- package/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +0 -45
- package/skills/vercel-react-best-practices/rules/js-index-maps.md +0 -37
- package/skills/vercel-react-best-practices/rules/js-length-check-first.md +0 -49
- package/skills/vercel-react-best-practices/rules/js-min-max-loop.md +0 -82
- package/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +0 -24
- package/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +0 -57
- package/skills/vercel-react-best-practices/rules/rendering-activity.md +0 -26
- package/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +0 -47
- package/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +0 -40
- package/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +0 -38
- package/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +0 -46
- package/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +0 -82
- package/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +0 -28
- package/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md +0 -75
- package/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +0 -39
- package/skills/vercel-react-best-practices/rules/rerender-dependencies.md +0 -45
- package/skills/vercel-react-best-practices/rules/rerender-derived-state.md +0 -29
- package/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +0 -74
- package/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +0 -58
- package/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md +0 -38
- package/skills/vercel-react-best-practices/rules/rerender-memo.md +0 -44
- package/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +0 -35
- package/skills/vercel-react-best-practices/rules/rerender-transitions.md +0 -40
- package/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +0 -73
- package/skills/vercel-react-best-practices/rules/server-auth-actions.md +0 -96
- package/skills/vercel-react-best-practices/rules/server-cache-lru.md +0 -41
- package/skills/vercel-react-best-practices/rules/server-cache-react.md +0 -76
- package/skills/vercel-react-best-practices/rules/server-dedup-props.md +0 -65
- package/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +0 -83
- package/skills/vercel-react-best-practices/rules/server-serialization.md +0 -38
|
@@ -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,38 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
|
|
3
|
-
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
|
4
|
-
impact: MEDIUM
|
|
5
|
-
impactDescription: restores memoization by using a constant for default value
|
|
6
|
-
tags: rerender, memo, optimization
|
|
7
|
-
|
|
8
|
-
---
|
|
9
|
-
|
|
10
|
-
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
|
11
|
-
|
|
12
|
-
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()`.
|
|
13
|
-
|
|
14
|
-
To address this issue, extract the default value into a constant.
|
|
15
|
-
|
|
16
|
-
**Incorrect (`onClick` has different values on every rerender):**
|
|
17
|
-
|
|
18
|
-
```tsx
|
|
19
|
-
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
|
|
20
|
-
// ...
|
|
21
|
-
})
|
|
22
|
-
|
|
23
|
-
// Used without optional onClick
|
|
24
|
-
<UserAvatar />
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
**Correct (stable default value):**
|
|
28
|
-
|
|
29
|
-
```tsx
|
|
30
|
-
const NOOP = () => {};
|
|
31
|
-
|
|
32
|
-
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
|
|
33
|
-
// ...
|
|
34
|
-
})
|
|
35
|
-
|
|
36
|
-
// Used without optional onClick
|
|
37
|
-
<UserAvatar />
|
|
38
|
-
```
|
|
@@ -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,35 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
title: Do not wrap a simple expression with a primitive result type in useMemo
|
|
3
|
-
impact: LOW-MEDIUM
|
|
4
|
-
impactDescription: wasted computation on every render
|
|
5
|
-
tags: rerender, useMemo, optimization
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## Do not wrap a simple expression with a primitive result type in useMemo
|
|
9
|
-
|
|
10
|
-
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`.
|
|
11
|
-
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
|
|
12
|
-
|
|
13
|
-
**Incorrect:**
|
|
14
|
-
|
|
15
|
-
```tsx
|
|
16
|
-
function Header({ user, notifications }: Props) {
|
|
17
|
-
const isLoading = useMemo(() => {
|
|
18
|
-
return user.isLoading || notifications.isLoading
|
|
19
|
-
}, [user.isLoading, notifications.isLoading])
|
|
20
|
-
|
|
21
|
-
if (isLoading) return <Skeleton />
|
|
22
|
-
// return some markup
|
|
23
|
-
}
|
|
24
|
-
```
|
|
25
|
-
|
|
26
|
-
**Correct:**
|
|
27
|
-
|
|
28
|
-
```tsx
|
|
29
|
-
function Header({ user, notifications }: Props) {
|
|
30
|
-
const isLoading = user.isLoading || notifications.isLoading
|
|
31
|
-
|
|
32
|
-
if (isLoading) return <Skeleton />
|
|
33
|
-
// return some markup
|
|
34
|
-
}
|
|
35
|
-
```
|
|
@@ -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,96 +0,0 @@
|
|
|
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)
|
|
@@ -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)
|