From d0ed0ab196d7e650777477390111b7d787eae5a0 Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 17 Sep 2026 11:00:57 +0200 Subject: [PATCH 01/18] feat: add manual test trigger functionality with haptic feedback and notification --- .../frontend/src/components/ArmingButton.tsx | 62 +++++++++++++++++++ .../frontend/src/components/ViolationCard.tsx | 25 +++++--- 2 files changed, 80 insertions(+), 7 deletions(-) diff --git a/headless-rust/frontend/src/components/ArmingButton.tsx b/headless-rust/frontend/src/components/ArmingButton.tsx index 8179fe0..f23d98f 100644 --- a/headless-rust/frontend/src/components/ArmingButton.tsx +++ b/headless-rust/frontend/src/components/ArmingButton.tsx @@ -1,12 +1,15 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { HugeiconsIcon } from "@hugeicons/react"; import { + FlashIcon, Shield01Icon, ShieldHalfIcon, ShieldKeyIcon, } from "@hugeicons/core-free-icons"; import { cn } from "@/lib/utils"; import { useAppStore } from "@/stores/useAppStore"; +import { getRpc } from "@/lib/rpc"; +import { toast } from "sonner"; // ponytail: native navigator.vibrate for mobile haptic feedback, zero dependencies const triggerHaptic = (pattern: number | number[]) => { @@ -127,6 +130,31 @@ export function ArmingButton() { // Derive which conditions are missing for the hint text const missingCamera = !cameraConnected; const missingSerial = !connectedPort; + const canTrigger = Boolean(connectedPort && cameraConnected); + + const [isTriggering, setIsTriggering] = useState(false); + + // ponytail: direct RPC test trigger with haptic feedback and toast notification + const handleTestTrigger = useCallback(async () => { + if (!canTrigger || isTriggering) return; + triggerHaptic(20); + setIsTriggering(true); + try { + const res = await getRpc().request.testTrigger({}); + if (res.success) { + triggerHaptic([30, 40]); + toast.success("Manual test trigger fired", { + description: "Test frame captured and recorded", + }); + } + } catch (err: any) { + toast.error("Test trigger failed", { + description: err?.message || "Communication failure", + }); + } finally { + setIsTriggering(false); + } + }, [canTrigger, isTriggering]); return (
+ + {/* Manual Test Trigger */} +
+ +
); } diff --git a/headless-rust/frontend/src/components/ViolationCard.tsx b/headless-rust/frontend/src/components/ViolationCard.tsx index 2d45114..a37c7ff 100644 --- a/headless-rust/frontend/src/components/ViolationCard.tsx +++ b/headless-rust/frontend/src/components/ViolationCard.tsx @@ -111,13 +111,24 @@ export function ViolationCard({
-

- {violation.measuredSpeed} km/h -

-

- Limit {violation.maxSpeed} km/h - (+{overSpeed}) -

+ {violation.measuredSpeed < 0 ? ( + <> + + Test Trigger + +

Manual verification frame

+ + ) : ( + <> +

+ {violation.measuredSpeed} km/h +

+

+ Limit {violation.maxSpeed} km/h + (+{overSpeed}) +

+ + )}
)}
@@ -83,12 +89,18 @@ export function LastCapturedImage() { {new Date(lastViolation.timestamp).toLocaleTimeString()} -
- - {lastViolation.measuredSpeed} + {lastViolation.measuredSpeed < 0 ? ( + + TEST TRIGGER - km/h -
+ ) : ( +
+ + {lastViolation.measuredSpeed} + + km/h +
+ )} )} From 4e5909ad00783294db5ff6102fe4af2810cf84ea Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 17 Sep 2026 11:01:38 +0200 Subject: [PATCH 05/18] feat: implement testTrigger RPC method for capturing and storing test violations --- headless-rust/src/web/rpc.rs | 62 ++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/headless-rust/src/web/rpc.rs b/headless-rust/src/web/rpc.rs index df2262e..9dc2f77 100644 --- a/headless-rust/src/web/rpc.rs +++ b/headless-rust/src/web/rpc.rs @@ -468,6 +468,68 @@ async fn dispatch_method(ctx: &RpcContext, method: &str, params: Value) -> Resul } } + "testTrigger" => { + let cam_status = ctx.camera.get_status(); + if !cam_status.connected { + return Err("Camera is not connected".to_string()); + } + let serial_status = ctx.serial.get_status(); + if !serial_status.connected { + return Err("Serial port is not connected".to_string()); + } + + let cam = ctx.camera.clone(); + let store = ctx.store.clone(); + let db = ctx.db.clone(); + let v_tx = ctx.violation_tx.clone(); + let cur_limit = ctx.serial.get_max_speed(); + + // ponytail: test trigger leverages core instant capture and rayon pre-cache pipeline + let res = tokio::task::spawn_blocking(move || -> Result { + let jpg_bytes = cam + .capture_frame_jpeg(90) + .ok_or_else(|| "Failed to capture frame from camera".to_string())?; + + let img_path = store + .save_image_bytes(&jpg_bytes, "jpg") + .map_err(|e| format!("Failed to save image: {}", e))?; + + let conn = db.lock(); + let input = SaveViolationInput { + image_base64: None, + measured_speed: -1.0, + max_speed: cur_limit, + direction: "test".to_string(), + }; + + let v = crate::db::violations::insert_violation(&conn, &input, &img_path) + .map_err(|e| format!("Failed to insert test violation: {}", e))?; + + tracing::info!("[test-trigger] Recorded test violation #{} (speed: {})", v.id, v.measured_speed); + let _ = v_tx.send(v.clone()); + + let store_pre = store.clone(); + let pre_bytes = jpg_bytes.clone(); + let pre_path = img_path.clone(); + rayon::spawn(move || { + let p_grid = crate::storage::compress::CompressParams { width: Some(400), quality: Some(80), ..Default::default() }; + let p_row = crate::storage::compress::CompressParams { width: Some(160), quality: Some(75), ..Default::default() }; + let _ = store_pre.compressor.process_image(&pre_bytes, &pre_path, &p_grid); + let _ = store_pre.compressor.process_image(&pre_bytes, &pre_path, &p_row); + }); + + Ok(serde_json::json!({ + "success": true, + "violation": v, + "imagePath": img_path + })) + }) + .await + .map_err(|e| e.to_string())??; + + Ok(res) + } + "setCameraExposure" => { let val = params["value"].as_f64().ok_or("Missing exposure value")?; let cam = ctx.camera.clone(); From 887cee51b16792fe44521cfc917b40176835159b Mon Sep 17 00:00:00 2001 From: LeoLTM <44781682+LeoLTM@users.noreply.github.com> Date: Thu, 17 Sep 2026 11:14:55 +0200 Subject: [PATCH 06/18] chore: replace emdashes --- headless-rust/frontend/src/components/ArmingButton.tsx | 2 +- headless-rust/frontend/src/components/FirmwareFlasher.tsx | 2 +- headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/headless-rust/frontend/src/components/ArmingButton.tsx b/headless-rust/frontend/src/components/ArmingButton.tsx index f23d98f..ddf7a52 100644 --- a/headless-rust/frontend/src/components/ArmingButton.tsx +++ b/headless-rust/frontend/src/components/ArmingButton.tsx @@ -277,7 +277,7 @@ export function ArmingButton() { {isArmed ? "Violations are being recorded" : isDisarmed - ? "Monitoring only — no violations recorded" + ? "Monitoring only - no violations recorded" : [missingCamera && "camera", missingSerial && "serial connection"] .filter(Boolean) .join(" & ") + " required"} diff --git a/headless-rust/frontend/src/components/FirmwareFlasher.tsx b/headless-rust/frontend/src/components/FirmwareFlasher.tsx index 50db99b..4f8d34e 100644 --- a/headless-rust/frontend/src/components/FirmwareFlasher.tsx +++ b/headless-rust/frontend/src/components/FirmwareFlasher.tsx @@ -338,7 +338,7 @@ export function FirmwareFlasher() { {/* Status badge */} {flashDone && !isFlashing && (

- Flash complete — device is rebooting. + Flash complete - device is rebooting.

)} {flashError && !isFlashing && ( diff --git a/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx b/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx index b2d53af..e85aea6 100644 --- a/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx +++ b/headless-rust/frontend/src/routes/settings/SpeedCameraTab.tsx @@ -168,7 +168,7 @@ export function SpeedCameraTab() { ? lastPongConfig ? "Values synced from device" : "Connect to device to sync values" - : Serial not connected — hardware save disabled} + : Serial not connected - hardware save disabled}

- ) -} -``` - -**Example: preload when feature flag is enabled** - -```tsx -function FlagsProvider({ children, flags }: Props) { - useEffect(() => { - if (flags.editorEnabled && typeof window !== 'undefined') { - void import('./monaco-editor').then(mod => mod.init()) - } - }, [flags.editorEnabled]) - - return - {children} - -} -``` - -The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. - ---- - -## 3. Server-Side Performance - -**Impact: HIGH** - -Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times. - -### 3.1 Authenticate Server Actions Like API Routes - -**Impact: CRITICAL (prevents unauthorized access to server mutations)** - -Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly. - -Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation." - -**Incorrect: no authentication check** - -```typescript -'use server' - -export async function deleteUser(userId: string) { - // Anyone can call this! No auth check - await db.user.delete({ where: { id: userId } }) - return { success: true } -} -``` - -**Correct: authentication inside the action** - -```typescript -'use server' - -import { verifySession } from '@/lib/auth' -import { unauthorized } from '@/lib/errors' - -export async function deleteUser(userId: string) { - // Always check auth inside the action - const session = await verifySession() - - if (!session) { - throw unauthorized('Must be logged in') - } - - // Check authorization too - if (session.user.role !== 'admin' && session.user.id !== userId) { - throw unauthorized('Cannot delete other users') - } - - await db.user.delete({ where: { id: userId } }) - return { success: true } -} -``` - -**With input validation:** - -```typescript -'use server' - -import { verifySession } from '@/lib/auth' -import { z } from 'zod' - -const updateProfileSchema = z.object({ - userId: z.string().uuid(), - name: z.string().min(1).max(100), - email: z.string().email() -}) - -export async function updateProfile(data: unknown) { - // Validate input first - const validated = updateProfileSchema.parse(data) - - // Then authenticate - const session = await verifySession() - if (!session) { - throw new Error('Unauthorized') - } - - // Then authorize - if (session.user.id !== validated.userId) { - throw new Error('Can only update own profile') - } - - // Finally perform the mutation - await db.user.update({ - where: { id: validated.userId }, - data: { - name: validated.name, - email: validated.email - } - }) - - return { success: true } -} -``` - -Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication) - -### 3.2 Avoid Duplicate Serialization in RSC Props - -**Impact: LOW (reduces network payload by avoiding duplicate serialization)** - -RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server. - -**Incorrect: duplicates array** - -```tsx -// RSC: sends 6 strings (2 arrays × 3 items) - -``` - -**Correct: sends 3 strings** - -```tsx -// RSC: send once - - -// Client: transform there -'use client' -const sorted = useMemo(() => [...usernames].sort(), [usernames]) -``` - -**Nested deduplication behavior:** - -```tsx -// string[] - duplicates everything -usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings - -// object[] - duplicates array structure only -users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4) -``` - -Deduplication works recursively. Impact varies by data type: - -- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated - -- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference - -**Operations breaking deduplication: create new references** - -- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]` - -- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())` - -**More examples:** - -```tsx -// ❌ Bad - u.active)} /> - - -// ✅ Good - - -// Do filtering/destructuring in client -``` - -**Exception:** Pass derived data when transformation is expensive or client doesn't need original. - -### 3.3 Avoid Shared Module State for Request Data - -**Impact: HIGH (prevents concurrency bugs and request data leaks)** - -For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response. - -Treat module scope on the server as process-wide shared memory, not request-local state. - -**Incorrect: request data leaks across concurrent renders** - -```tsx -let currentUser: User | null = null - -export default async function Page() { - currentUser = await auth() - return -} - -async function Dashboard() { - return
{currentUser?.name}
-} -``` - -If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`. - -**Correct: keep request data local to the render tree** - -```tsx -export default async function Page() { - const user = await auth() - return -} - -function Dashboard({ user }: { user: User | null }) { - return
{user?.name}
-} -``` - -Safe exceptions: - -- Immutable static assets or config loaded once at module scope - -- Shared caches intentionally designed for cross-request reuse and keyed correctly - -- Process-wide singletons that do not store request- or user-specific mutable data - -For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md). - -### 3.4 Cross-Request LRU Caching - -**Impact: HIGH (caches across requests)** - -`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache. - -**Implementation:** - -```typescript -import { LRUCache } from 'lru-cache' - -const cache = new LRUCache({ - max: 1000, - ttl: 5 * 60 * 1000 // 5 minutes -}) - -export async function getUser(id: string) { - const cached = cache.get(id) - if (cached) return cached - - const user = await db.user.findUnique({ where: { id } }) - cache.set(id, user) - return user -} - -// Request 1: DB query, result cached -// Request 2: cache hit, no DB query -``` - -Use when sequential user actions hit multiple endpoints needing the same data within seconds. - -**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis. - -**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching. - -Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache) - -### 3.5 Hoist Static I/O to Module Level - -**Impact: HIGH (avoids repeated file/network I/O per request)** - -When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation. - -**Incorrect: reads font file on every request** - -```typescript -// app/api/og/route.tsx -import { ImageResponse } from 'next/og' - -export async function GET(request: Request) { - // Runs on EVERY request - expensive! - const fontData = await fetch( - new URL('./fonts/Inter.ttf', import.meta.url) - ).then(res => res.arrayBuffer()) - - const logoData = await fetch( - new URL('./images/logo.png', import.meta.url) - ).then(res => res.arrayBuffer()) - - return new ImageResponse( -
- - Hello World -
, - { fonts: [{ name: 'Inter', data: fontData }] } - ) -} -``` - -**Correct: loads once at module initialization** - -```typescript -// app/api/og/route.tsx -import { ImageResponse } from 'next/og' - -// Module-level: runs ONCE when module is first imported -const fontData = fetch( - new URL('./fonts/Inter.ttf', import.meta.url) -).then(res => res.arrayBuffer()) - -const logoData = fetch( - new URL('./images/logo.png', import.meta.url) -).then(res => res.arrayBuffer()) - -export async function GET(request: Request) { - // Await the already-started promises - const [font, logo] = await Promise.all([fontData, logoData]) - - return new ImageResponse( -
- - Hello World -
, - { fonts: [{ name: 'Inter', data: font }] } - ) -} -``` - -**Correct: synchronous fs at module level** - -```typescript -// app/api/og/route.tsx -import { ImageResponse } from 'next/og' -import { readFileSync } from 'fs' -import { join } from 'path' - -// Synchronous read at module level - blocks only during module init -const fontData = readFileSync( - join(process.cwd(), 'public/fonts/Inter.ttf') -) - -const logoData = readFileSync( - join(process.cwd(), 'public/images/logo.png') -) - -export async function GET(request: Request) { - return new ImageResponse( -
- - Hello World -
, - { fonts: [{ name: 'Inter', data: fontData }] } - ) -} -``` - -**Incorrect: reads config on every call** - -```typescript -import fs from 'node:fs/promises' - -export async function processRequest(data: Data) { - const config = JSON.parse( - await fs.readFile('./config.json', 'utf-8') - ) - const template = await fs.readFile('./template.html', 'utf-8') - - return render(template, data, config) -} -``` - -**Correct: hoists config and template to module level** - -```typescript -import fs from 'node:fs/promises' - -const configPromise = fs - .readFile('./config.json', 'utf-8') - .then(JSON.parse) -const templatePromise = fs.readFile('./template.html', 'utf-8') - -export async function processRequest(data: Data) { - const [config, template] = await Promise.all([ - configPromise, - templatePromise, - ]) - - return render(template, data, config) -} -``` - -When to use this pattern: - -- Loading fonts for OG image generation - -- Loading static logos, icons, or watermarks - -- Reading configuration files that don't change at runtime - -- Loading email templates or other static templates - -- Any static asset that's the same across all requests - -When not to use this pattern: - -- Assets that vary per request or user - -- Files that may change during runtime (use caching with TTL instead) - -- Large files that would consume too much memory if kept loaded - -- Sensitive data that shouldn't persist in memory - -With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties. - -In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled. - -### 3.6 Minimize Serialization at RSC Boundaries - -**Impact: HIGH (reduces data transfer size)** - -The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses. - -**Incorrect: serializes all 50 fields** - -```tsx -async function Page() { - const user = await fetchUser() // 50 fields - return -} - -'use client' -function Profile({ user }: { user: User }) { - return
{user.name}
// uses 1 field -} -``` - -**Correct: serializes only 1 field** - -```tsx -async function Page() { - const user = await fetchUser() - return -} - -'use client' -function Profile({ name }: { name: string }) { - return
{name}
-} -``` - -### 3.7 Parallel Data Fetching with Component Composition - -**Impact: CRITICAL (eliminates server-side waterfalls)** - -React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching. - -**Incorrect: Sidebar waits for Page's fetch to complete** - -```tsx -export default async function Page() { - const header = await fetchHeader() - return ( -
-
{header}
- -
- ) -} - -async function Sidebar() { - const items = await fetchSidebarItems() - return -} -``` - -**Correct: both fetch simultaneously** - -```tsx -async function Header() { - const data = await fetchHeader() - return
{data}
-} - -async function Sidebar() { - const items = await fetchSidebarItems() - return -} - -export default function Page() { - return ( -
-
- -
- ) -} -``` - -**Alternative with children prop:** - -```tsx -async function Header() { - const data = await fetchHeader() - return
{data}
-} - -async function Sidebar() { - const items = await fetchSidebarItems() - return -} - -function Layout({ children }: { children: ReactNode }) { - return ( -
-
- {children} -
- ) -} - -export default function Page() { - return ( - - - - ) -} -``` - -### 3.8 Parallel Nested Data Fetching - -**Impact: CRITICAL (eliminates server-side waterfalls)** - -When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest. - -**Incorrect: a single slow item blocks all nested fetches** - -```tsx -const chats = await Promise.all( - chatIds.map(id => getChat(id)) -) - -const chatAuthors = await Promise.all( - chats.map(chat => getUser(chat.author)) -) -``` - -If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready. - -**Correct: each item chains its own nested fetch** - -```tsx -const chatAuthors = await Promise.all( - chatIds.map(id => getChat(id).then(chat => getUser(chat.author))) -) -``` - -Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others. - -### 3.9 Per-Request Deduplication with React.cache() - -**Impact: MEDIUM (deduplicates within request)** - -Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most. - -**Usage:** - -```typescript -import { cache } from 'react' - -export const getCurrentUser = cache(async () => { - const session = await auth() - if (!session?.user?.id) return null - return await db.user.findUnique({ - where: { id: session.user.id } - }) -}) -``` - -Within a single request, multiple calls to `getCurrentUser()` execute the query only once. - -**Avoid inline objects as arguments:** - -`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits. - -**Incorrect: always cache miss** - -```typescript -const getUser = cache(async (params: { uid: number }) => { - return await db.user.findUnique({ where: { id: params.uid } }) -}) - -// Each call creates new object, never hits cache -getUser({ uid: 1 }) -getUser({ uid: 1 }) // Cache miss, runs query again -``` - -**Correct: cache hit** - -```typescript -const params = { uid: 1 } -getUser(params) // Query runs -getUser(params) // Cache hit (same reference) -``` - -If you must pass objects, pass the same reference: - -**Next.js-Specific Note:** - -In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks: - -- Database queries (Prisma, Drizzle, etc.) - -- Heavy computations - -- Authentication checks - -- File system operations - -- Any non-fetch async work - -Use `React.cache()` to deduplicate these operations across your component tree. - -Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache) - -### 3.10 Use after() for Non-Blocking Operations - -**Impact: MEDIUM (faster response times)** - -Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response. - -**Incorrect: blocks response** - -```tsx -import { logUserAction } from '@/app/utils' - -export async function POST(request: Request) { - // Perform mutation - await updateDatabase(request) - - // Logging blocks the response - const userAgent = request.headers.get('user-agent') || 'unknown' - await logUserAction({ userAgent }) - - return new Response(JSON.stringify({ status: 'success' }), { - status: 200, - headers: { 'Content-Type': 'application/json' } - }) -} -``` - -**Correct: non-blocking** - -```tsx -import { after } from 'next/server' -import { headers, cookies } from 'next/headers' -import { logUserAction } from '@/app/utils' - -export async function POST(request: Request) { - // Perform mutation - await updateDatabase(request) - - // Log after response is sent - after(async () => { - const userAgent = (await headers()).get('user-agent') || 'unknown' - const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous' - - logUserAction({ sessionCookie, userAgent }) - }) - - return new Response(JSON.stringify({ status: 'success' }), { - status: 200, - headers: { 'Content-Type': 'application/json' } - }) -} -``` - -The response is sent immediately while logging happens in the background. - -**Common use cases:** - -- Analytics tracking - -- Audit logging - -- Sending notifications - -- Cache invalidation - -- Cleanup tasks - -**Important notes:** - -- `after()` runs even if the response fails or redirects - -- Works in Server Actions, Route Handlers, and Server Components - -Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after) - ---- - -## 4. Client-Side Data Fetching - -**Impact: MEDIUM-HIGH** - -Automatic deduplication and efficient data fetching patterns reduce redundant network requests. - -### 4.1 Deduplicate Global Event Listeners - -**Impact: LOW (single listener for N components)** - -Use `useSWRSubscription()` to share global event listeners across component instances. - -**Incorrect: N instances = N listeners** - -```tsx -function useKeyboardShortcut(key: string, callback: () => void) { - useEffect(() => { - const handler = (e: KeyboardEvent) => { - if (e.metaKey && e.key === key) { - callback() - } - } - window.addEventListener('keydown', handler) - return () => window.removeEventListener('keydown', handler) - }, [key, callback]) -} -``` - -When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener. - -**Correct: N instances = 1 listener** - -```tsx -import useSWRSubscription from 'swr/subscription' - -// Module-level Map to track callbacks per key -const keyCallbacks = new Map void>>() - -function useKeyboardShortcut(key: string, callback: () => void) { - // Register this callback in the Map - useEffect(() => { - if (!keyCallbacks.has(key)) { - keyCallbacks.set(key, new Set()) - } - keyCallbacks.get(key)!.add(callback) - - return () => { - const set = keyCallbacks.get(key) - if (set) { - set.delete(callback) - if (set.size === 0) { - keyCallbacks.delete(key) - } - } - } - }, [key, callback]) - - useSWRSubscription('global-keydown', () => { - const handler = (e: KeyboardEvent) => { - if (e.metaKey && keyCallbacks.has(e.key)) { - keyCallbacks.get(e.key)!.forEach(cb => cb()) - } - } - window.addEventListener('keydown', handler) - return () => window.removeEventListener('keydown', handler) - }) -} - -function Profile() { - // Multiple shortcuts will share the same listener - useKeyboardShortcut('p', () => { /* ... */ }) - useKeyboardShortcut('k', () => { /* ... */ }) - // ... -} -``` - -### 4.2 Use Passive Event Listeners for Scrolling Performance - -**Impact: MEDIUM (eliminates scroll delay caused by event listeners)** - -Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay. - -**Incorrect:** - -```typescript -useEffect(() => { - const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) - const handleWheel = (e: WheelEvent) => console.log(e.deltaY) - - document.addEventListener('touchstart', handleTouch) - document.addEventListener('wheel', handleWheel) - - return () => { - document.removeEventListener('touchstart', handleTouch) - document.removeEventListener('wheel', handleWheel) - } -}, []) -``` - -**Correct:** - -```typescript -useEffect(() => { - const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) - const handleWheel = (e: WheelEvent) => console.log(e.deltaY) - - document.addEventListener('touchstart', handleTouch, { passive: true }) - document.addEventListener('wheel', handleWheel, { passive: true }) - - return () => { - document.removeEventListener('touchstart', handleTouch) - document.removeEventListener('wheel', handleWheel) - } -}, []) -``` - -**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`. - -**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`. - -### 4.3 Use SWR for Automatic Deduplication - -**Impact: MEDIUM-HIGH (automatic deduplication)** - -SWR enables request deduplication, caching, and revalidation across component instances. - -**Incorrect: no deduplication, each instance fetches** - -```tsx -function UserList() { - const [users, setUsers] = useState([]) - useEffect(() => { - fetch('/api/users') - .then(r => r.json()) - .then(setUsers) - }, []) -} -``` - -**Correct: multiple instances share one request** - -```tsx -import useSWR from 'swr' - -function UserList() { - const { data: users } = useSWR('/api/users', fetcher) -} -``` - -**For immutable data:** - -```tsx -import { useImmutableSWR } from '@/lib/swr' - -function StaticContent() { - const { data } = useImmutableSWR('/api/config', fetcher) -} -``` - -**For mutations:** - -```tsx -import { useSWRMutation } from 'swr/mutation' - -function UpdateButton() { - const { trigger } = useSWRMutation('/api/user', updateUser) - return -} -``` - -Reference: [https://swr.vercel.app](https://swr.vercel.app) - -### 4.4 Version and Minimize localStorage Data - -**Impact: MEDIUM (prevents schema conflicts, reduces storage size)** - -Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. - -**Incorrect:** - -```typescript -// No version, stores everything, no error handling -localStorage.setItem('userConfig', JSON.stringify(fullUserObject)) -const data = localStorage.getItem('userConfig') -``` - -**Correct:** - -```typescript -const VERSION = 'v2' - -function saveConfig(config: { theme: string; language: string }) { - try { - localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)) - } catch { - // Throws in incognito/private browsing, quota exceeded, or disabled - } -} - -function loadConfig() { - try { - const data = localStorage.getItem(`userConfig:${VERSION}`) - return data ? JSON.parse(data) : null - } catch { - return null - } -} - -// Migration from v1 to v2 -function migrate() { - try { - const v1 = localStorage.getItem('userConfig:v1') - if (v1) { - const old = JSON.parse(v1) - saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang }) - localStorage.removeItem('userConfig:v1') - } - } catch {} -} -``` - -**Store minimal fields from server responses:** - -```typescript -// User object has 20+ fields, only store what UI needs -function cachePrefs(user: FullUser) { - try { - localStorage.setItem('prefs:v1', JSON.stringify({ - theme: user.preferences.theme, - notifications: user.preferences.notifications - })) - } catch {} -} -``` - -**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. - -**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. - ---- - -## 5. Re-render Optimization - -**Impact: MEDIUM** - -Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness. - -### 5.1 Calculate Derived State During Rendering - -**Impact: MEDIUM (avoids redundant renders and state drift)** - -If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead. - -**Incorrect: redundant state and effect** - -```tsx -function Form() { - const [firstName, setFirstName] = useState('First') - const [lastName, setLastName] = useState('Last') - const [fullName, setFullName] = useState('') - - useEffect(() => { - setFullName(firstName + ' ' + lastName) - }, [firstName, lastName]) - - return

{fullName}

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

{fullName}

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