10LOC

Short, dense posts for intermediate-to-advanced developers. Every post centers on ~10 lines of React, Node.js, TypeScript, Bun, web platform, or Chrome API code — what it does, why it matters, how to use it.

Web Platformintermediate

Use URL.canParse for safer URL handling

export const parseValidUrls = (candidates: string[], base?: string): URL[] =>
  candidates.filter((candidate) => URL.canParse(candidate, base)).map((candidate) => new URL(candidate, base));

export const isSameOriginRedirect = (target: string, currentOrigin: string): boolean => {
  if (!URL.canParse(target, currentOrigin)) return false;

Validate URLs before you build or parse them with the built-in URL API.

Chrome APIsadvanced

Shared Storage: privacy-preserving experiments, now being retired

type SharedStorage = {
  worklet: { addModule: (url: string) => Promise<void> };
  set: (key: string, value: string, options?: { ignoreIfPresent?: boolean }) => Promise<void>;
  run: (operation: string, options?: { data?: Record<string, unknown> }) => Promise<void>;
};

How the Shared Storage API worked for cross-site experiments without third-party cookies — and why Chrome is deprecating and removing it.

Web Platformintermediate

Use requestVideoFrameCallback for smooth animation timing

type RvfcVideo = HTMLVideoElement & {
  requestVideoFrameCallback: (cb: (now: number, meta: { mediaTime: number }) => void) => number;
  cancelVideoFrameCallback: (handle: number) => void;
};

Schedule visual work with the browser's video frame callback for smoother rendering.

Chrome APIsadvanced

Periodic Background Sync for resilient refresh jobs

type PeriodicSyncRegistration = ServiceWorkerRegistration & {
  periodicSync: { register: (tag: string, options: { minInterval: number }) => Promise<void> };
};

export const schedulePeriodicRefresh = async (tag: string, minIntervalMs: number): Promise<boolean> => {

Schedule light refresh work that can survive transient network loss.

Web Platformintermediate

Persist storage with navigator.storage.persist

export const ensurePersistentStorage = async (): Promise<boolean> => {
  if (!navigator.storage?.persist) return false;
  if (await navigator.storage.persisted()) return true;
  return navigator.storage.persist();
};

Ask the browser for persistent storage so your app can keep data around longer.

Node.jsadvanced

Use stream.finished for reliable cleanup

import { createReadStream, createWriteStream } from "node:fs";
import { finished } from "node:stream/promises";

export const copyWithCleanup = async (src: string, dest: string, signal?: AbortSignal) => {
  const read = createReadStream(src);

Wait for a stream to finish and clean up resources without ad-hoc listeners.

Chrome APIsadvanced

The File Handling API for browser file access

type LaunchParams = { files: FileSystemFileHandle[] };
type LaunchQueue = { setConsumer: (consumer: (params: LaunchParams) => void) => void };

export const handleLaunchedFiles = (onFiles: (files: File[]) => void): void => {
  const launchQueue = (window as { launchQueue?: LaunchQueue }).launchQueue;

Open and work with files directly from the browser with the File Handling API.

Web Platformintermediate

CompressionStream for browser-side gzip

export const gzipEncode = async (text: string): Promise<Uint8Array> => {
  const stream = new Blob([text]).stream().pipeThrough(new CompressionStream("gzip"));
  const buffer = await new Response(stream).arrayBuffer();
  return new Uint8Array(buffer);
};

Compress and decompress data in the browser with native Web Streams APIs.

Bunintermediate

Use Bun.write for zero-dependency file output

import { write } from "bun";

export const saveJsonReport = (path: string, report: Record<string, unknown>) =>
  write(path, JSON.stringify(report, null, 2) + "\n");

Write files in Bun without extra dependencies or shelling out.

TypeScriptadvanced

Use NoInfer to keep generic inference predictable

export const createMethodGuard = <M extends string>(allowed: M[], fallback: NoInfer<M>) => {
  const allowedSet = new Set<string>(allowed);
  return (method: string): M => (allowedSet.has(method) ? (method as M) : fallback);
};

Prevent TypeScript from widening generic arguments when you need stable inference.

Node.jsadvanced

Bridge Node streams to web streams

import { createReadStream } from "node:fs";
import { Readable } from "node:stream";

export const compressedFileResponse = (path: string) => {
  const nodeStream = createReadStream(path, { highWaterMark: 64 * 1024 });

Turn a Node Readable into a web-compatible stream with Readable.toWeb().

Reactintermediate

A tiny useLocalStorage hook

import { useState, useEffect } from "react";

export const useLocalStorage = <T>(key: string, initialValue: T) => {
  const [value, setValue] = useState<T>(() => {
    const stored = localStorage.getItem(key);

Sync a single piece of state to localStorage with a small, focused hook.

Chrome APIsintermediate

Background Sync for offline-friendly actions

type SyncRegistration = ServiceWorkerRegistration & { sync: { register: (tag: string) => Promise<void> } };

export const scheduleOfflineAction = async (tag: string, replayNow: () => Promise<void>): Promise<void> => {
  const registration = await navigator.serviceWorker.ready;
  const canBackgroundSync = "sync" in registration;

Replay user actions later when connectivity returns with Background Sync.

Bunintermediate

A tiny Bun test fixture helper

import { beforeEach, afterEach, test, expect } from "bun:test";
import { file } from "bun";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

Keep Bun tests small by extracting repeated setup into a fixture helper.

TypeScriptintermediate

Extract and Exclude in a tiny parser helper

type Assignment = { kind: "assign"; key: string; value: string };
type Flag = { kind: "flag"; key: string };
type Token = Assignment | Flag | { kind: "comment"; text: string };

const tokenize = (line: string): Token => {

Use utility conditional types to parse and narrow a small input grammar.

Node.jsintermediate

Use fs.cp for simple directory copies

import { cp } from "node:fs/promises";

export const copyDirectory = (src: string, dest: string, options: { overwrite?: boolean } = {}) =>
  cp(src, dest, {
    recursive: true,

Copy directories in Node without shelling out to cp.

Reactintermediate

Use React's use hook for promises and context

import { use, Suspense, createContext } from "react";

const ThemeContext = createContext("light");
const greetingCache = new Map<string, Promise<string>>();

Read promises and context directly during render with React's built-in use hook.

Chrome APIsadvanced

The Speculation Rules API to prerender the next likely page

const injectedUrls = new Set<string>();

export const prerenderOnHoverIntent = (link: HTMLAnchorElement, dwellMs = 200) => {
  if (!(globalThis as any).HTMLScriptElement?.supports?.("speculationrules")) return;
  let timer = 0;

A dynamically-injected <script type=speculationrules> can prerender a hovered link in the background, so the click lands on an already-rendered page.

TypeScriptadvanced

Narrowing with in and tagged interfaces for a plugin system

interface LoggerPlugin { kind: "logger"; log(message: string): void }
interface CachePlugin { kind: "cache"; get(key: string): unknown }

export type AppPlugin = LoggerPlugin | CachePlugin;

Narrow a plugin union by checking which method it has, instead of switching on a kind tag, so adding a capability-only plugin needs no tag.

Node.jsintermediate

Server-Sent Events (SSE) with plain res.write, no socket.io

import { createServer, type ServerResponse } from "node:http";

const clients = new Set<ServerResponse>();

const server = createServer((req, res) => {

A live event stream over plain HTTP using res.write and text/event-stream — no WebSocket library, no socket.io, and free auto-reconnect in the browser.

Reactadvanced

A stable latest-callback ref to kill effect dependency churn

import { useRef, useEffect, useCallback } from "react";

export const useLatestCallback = <Args extends unknown[], R>(callback: (...args: Args) => R) => {
  const callbackRef = useRef(callback);

Wrap a fast-changing callback in a ref so effects can call the latest version without listing it as a dependency and re-firing every render.

Chrome APIsintermediate

console.table and console.time power tricks for real debugging

type Row = { id: number; status: string; durationMs: number };

export const logBatchResult = async (rows: Row[], errors: { field: string; message: string }[]) => {
  console.table(rows, ["id", "status", "durationMs"]);

console.table renders records as a sortable grid instead of a collapsed tree, and console.time/timeLog/count turn ad-hoc timing into two-line instrumentation.

Web Platformadvanced

Transferable objects with postMessage for zero-copy worker handoff

const { port1, port2 } = new MessageChannel();

port2.onmessage = (event: MessageEvent<ArrayBuffer>) => {
  console.log("received", event.data.byteLength, "bytes, zero-copy");
};

Passing an ArrayBuffer in postMessage's transfer list hands off ownership instead of cloning it — the sender's reference goes to byteLength 0.

Bunadvanced

On-the-fly TS/JSX transforms with Bun.Transpiler

const transpiler = new Bun.Transpiler({ loader: "tsx" });

const source = `
  interface Props { name: string }
  export const Greeting = (props: Props) => <h1>Hello, {props.name}!</h1>;

Bun.Transpiler exposes Bun's own TS/JSX-to-JS compiler as a callable class, for transforming source strings at runtime without shelling out to a build step.

TypeScriptadvanced

A fluent builder pattern typed with generics

export class QueryBuilder<Shape extends Record<string, unknown> = Record<string, never>> {
  private constructor(private readonly clauses: Shape) {}

  static create(): QueryBuilder<Record<string, never>> {
    return new QueryBuilder({});

Make each .where() call widen the builder's tracked return type by exactly the key and value just added, so build() is never underspecified.

Node.jsadvanced

A zero-dependency LRU cache built on Map's insertion order

export const createLRUCache = <K, V>(capacity: number) => {
  const cache = new Map<K, V>();

  const get = (key: K) => {
    if (!cache.has(key)) return undefined;

A Map already tracks insertion order — re-inserting on access is enough to get real LRU eviction for free, no library needed.

Reactintermediate

A form calling a Server Action directly, no client fetch

const subscribers = new Set<string>();

async function subscribeToNewsletter(formData: FormData) {
  "use server";

Wire a form straight to a Server Action with the action prop, skipping the client fetch, JSON body, and API route entirely.

Chrome APIsintermediate

content-visibility: auto to skip render cost offscreen

.long-page section {
  content-visibility: auto;
  contain-intrinsic-size: auto 480px;
}

content-visibility: auto skips layout, style, and paint for an off-screen subtree — near-free virtualization that keeps find-in-page and anchors working.

Web Platformintermediate

Page Visibility API to pause work in a backgrounded tab

export const pauseWhenHidden = (start: () => () => void) => {
  let stop = start();

  document.addEventListener("visibilitychange", () => {
    if (document.visibilityState === "hidden") {

Stop polling, ticking, or rendering the instant a tab goes to the background, and resume with the same start function when it comes back.

Bunadvanced

Parallel work with Bun's Worker

export const countPrimesOnWorker = (from: number, to: number) => {
  const workerCode = `
    self.onmessage = ({ data: [from, to] }) => {
      let count = 0;
      for (let n = from; n < to; n++) {

Bun's Worker API uses real OS threads, so CPU-bound work can be split across workers created from an in-memory blob: URL, with no separate worker file needed.

TypeScriptintermediate

as const plus a lookup object as a lighter enum

export const Status = { Pending: "pending", Active: "active", Done: "done" } as const;

export type Status = (typeof Status)[keyof typeof Status];

export const describe = (status: Status): string => {

Get enum-like values and a matching type from one object literal, without the runtime overhead or the awkward reverse-mapping of enum.

Node.jsintermediate

A debounced fs.watch file watcher, no chokidar

import { watch } from "node:fs";

export const watchDebounced = (path: string, onChange: (eventType: string) => void, waitMs = 200) => {
  let timer: NodeJS.Timeout | undefined;

fs.watch fires multiple times for a single logical change; debouncing it with a plain setTimeout gets you chokidar's core behavior for free.

Reactadvanced

useOptimistic for instant UI feedback before the server confirms

import { useOptimistic, useTransition } from "react";

type Post = { id: string; likedByMe: boolean; likeCount: number };

export const LikeButton = ({ post, toggleLike }: { post: Post; toggleLike: (id: string) => Promise<void> }) => {

Show the result of an action immediately and let React reconcile it with the real state once the server responds, success or failure.

Chrome APIsadvanced

WebCodecs for low-level video frame processing

// @types/dom-webcodecs isn't installed in this repo, so VideoDecoder/VideoFrame/
// EncodedVideoChunk aren't typed here — cast to `any` rather than pretend otherwise.
export const decodeFrames = (chunks: any[], onFrame: (frame: any) => void): Promise<void> => {
  const Decoder = (globalThis as any).VideoDecoder;
  const decoder = new Decoder({

VideoDecoder exposes the browser's own hardware decoder as a queue: feed chunks in, get real VideoFrame objects out — no ffmpeg.wasm, no <video> polling.

Web Platformadvanced

The Cache API for direct HTTP response caching

const CACHE_NAME = "api-cache-v1";

export const fetchWithCache = async (url: string, maxAgeMs: number) => {
  const cache = await caches.open(CACHE_NAME);
  const cached = await cache.match(url);

Cache real Response objects by URL from plain page scripts, with a manual max-age check, no service worker required.

Bunintermediate

Benchmarking Bun's cold start against Node with performance.now()

const measureColdStart = (cmd: string[]) => {
  const start = performance.now();
  Bun.spawnSync(cmd);
  return performance.now() - start;
};

Bun.spawnSync plus performance.now() around each call turns a cold-start comparison against Node into a five-line, dependency-free benchmark.

TypeScriptadvanced

Function overloads vs one generic signature — when each wins

export function parseValue(input: string): string;
export function parseValue(input: number): number;
export function parseValue(input: string | number): string | number {
  return typeof input === "string" ? input.trim() : Math.round(input);
}

Same function, two type-safe shapes: distinct return types per input type via overloads, versus one T-preserving signature via a generic.

Node.jsintermediate

Retrying a flaky async call with exponential backoff

export const retryWithBackoff = async <T>(fn: () => Promise<T>, maxAttempts = 5, baseDelayMs = 200): Promise<T> => {
  for (let attempt = 1; ; attempt++) {
    try {
      return await fn();
    } catch (err) {

Retry a failing async call with a delay that doubles each attempt plus random jitter, so retries don't pile onto a struggling service in lockstep.

Reactadvanced

Compound components with context instead of Children.map

import { createContext, useContext, useState, type ReactNode } from "react";

type TabsState = { activeTab: string; setActiveTab: (id: string) => void };
const TabsContext = createContext<TabsState | null>(null);

Build a Tabs component whose parts talk through context instead of cloning and inspecting children, so consumers can nest and reorder freely.

Chrome APIsintermediate

URLPattern for route matching without a regex library

// TypeScript hasn't bundled URLPattern into its DOM types yet, so this repo's tsconfig
// doesn't know about it either. One cast at the constructor keeps everything below fully
// typed instead of leaking `any` through the rest of the file.
type UrlMatch = { pathname: { groups: Record<string, string | undefined> } };
type UrlPatternLike = { exec: (input: { pathname: string }) => UrlMatch | null };

URLPattern standardizes the :param/wildcard matching every router library reinvents — built into the browser and, increasingly, server runtimes too.

Web Platformadvanced

Intl.Segmenter for emoji-safe text truncation

const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });

export const truncateGraphemes = (text: string, maxLength: number) => {
  const graphemes = Array.from(segmenter.segment(text), (s) => s.segment);
  if (graphemes.length <= maxLength) return text;

Truncate user text to N visible characters without splitting a multi-codepoint emoji or accented letter in half.

Bunintermediate

A static file router that falls back to Bun.file

import { serve, file } from "bun";

const PUBLIC_DIR = `${import.meta.dir}/public`;

const server = serve({

A fetch handler can serve API routes first and fall back to Bun.file for anything else, building a static file server without a separate static-file middleware.

TypeScriptintermediate

Awaited<T> and unwrapping nested promise types

type Nested = Promise<Promise<Promise<string>>>;
type Flat = Awaited<Nested>;

export async function loadUser(): Promise<{ id: string; name: string }> {
  return { id: "1", name: "Ada" };

Unwrap Promise<Promise<Promise<T>>> down to T in one step, the way await does at runtime, using TypeScript's built-in recursive helper.

Node.jsadvanced

A token-bucket rate limiter in 10 lines

export const createTokenBucket = (capacity: number, refillPerSecond: number) => {
  let tokens = capacity;
  let lastRefill = performance.now();

  return (cost = 1): boolean => {

A token bucket that refills lazily based on elapsed time, so it needs no background timer to stay accurate.

Reactintermediate

useId for stable, SSR-safe unique ids

import { useId } from "react";

export const PasswordField = () => {
  const id = useId();

Generate ids that match between server and client render, so aria-describedby and label associations survive hydration without a mismatch.

Chrome APIsintermediate

text-wrap: balance for balanced headlines with no JS

h1, h2, .card-title {
  text-wrap: balance;
  max-width: 40ch;
}

text-wrap: balance redistributes a heading's line breaks evenly instead of greedy fill — computed by the layout engine, re-balanced on every resize.

Web Platformintermediate

requestIdleCallback for scheduling non-urgent work

type IdleCallback = (deadline: IdleDeadline) => void;

const runOnNextTick = (callback: IdleCallback) => {
  const start = performance.now();
  setTimeout(() => callback({ didTimeout: false, timeRemaining: () => Math.max(0, 50 - (performance.now() - start)) }), 1);

Run analytics, prefetching, or cache warming only when the browser has real spare time, with a fallback for the one major browser that never shipped this API.

Bunadvanced

Calling a C function from Bun via bun:ffi

import { dlopen, FFIType, suffix } from "bun:ffi";

const path = `libsqlite3.${suffix}`;

const { symbols } = dlopen(path, {

bun:ffi's dlopen loads a shared library and JIT-compiles a JS-to-native binding for each symbol, letting Bun call C functions directly with no N-API glue code.

TypeScriptintermediate

A recursive type for JSON-safe values

type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };

const isJsonValue = (value: unknown): value is JsonValue => {
  if (value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean") return true;
  if (Array.isArray(value)) return value.every(isJsonValue);

Define exactly what JSON.stringify can round-trip, recursively, and use it to reject values like undefined, functions, and Dates.

Node.jsintermediate

Readable.from() to turn any async iterable into a stream

import { Readable } from "node:stream";

async function* paginatedResults(pageCount: number) {
  for (let page = 1; page <= pageCount; page++) {
    await new Promise((resolve) => setTimeout(resolve, 10)); // simulate a network call

Readable.from() wraps any (async) generator or iterable in a real Readable stream, so it can be piped anywhere a stream is expected.

Reactadvanced

Suspense data fetching with a thrown promise cache

type Resource<T> = { read: () => T };

const cache = new Map<string, Resource<unknown>>();

export const getResource = <T,>(key: string, fetchData: () => Promise<T>): Resource<T> => {

Build the tiny promise cache that makes Suspense-based data fetching work: throw while pending, cache the result, return it once resolved.

Chrome APIsadvanced

Declarative Shadow DOM for server-rendered web components

<user-card>
  <template shadowrootmode="open">
    <style>
      :host { display: block; border: 1px solid #ddd; border-radius: 8px; padding: 1rem; }
      .name { font-weight: 600; margin: 0; }

A <template shadowrootmode> is parsed straight into a real shadow root by the HTML parser — a web component's shadow tree, fully rendered before any JS runs.

Web Platformadvanced

A minimal cache-first offline service worker

const CACHE_NAME = "app-shell-v1";
const PRECACHE_URLS = ["/", "/styles.css", "/app.js", "/offline.html"];

self.addEventListener("install", (event) => {
  (event as Event & { waitUntil: (p: Promise<unknown>) => void }).waitUntil(

Precache the app shell on install and serve every request from cache first, falling back to the network only on a cache miss.

Bunintermediate

Bun's automatic .env loading vs the dotenv package

declare module "bun" {
  interface Env {
    DATABASE_URL: string;
    DEBUG?: string;
  }

Bun parses .env, .env.local, and .env.production automatically before your code runs, so import 'dotenv/config' is not just unnecessary but dead weight.

TypeScriptintermediate

Assertion functions (asserts x is T) for runtime-checked narrowing

export function assertIsString(value: unknown, name: string): asserts value is string {
  if (typeof value !== "string") {
    throw new TypeError(`${name} must be a string, got ${typeof value}`);
  }
}

Narrow a value by throwing instead of branching, so the rest of the function can assume the checked type without an extra if.

Node.jsadvanced

child_process to fan work out across CPU cores

import { fork } from "node:child_process";
import { cpus } from "node:os";
import { once } from "node:events";
import { fileURLToPath } from "node:url";

Fork one child process per CPU core, split a CPU-bound range across them, and aggregate results over IPC — using one self-contained file.

Reactintermediate

Portals for rendering a modal outside the DOM hierarchy

import { useEffect, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";

export const Modal = ({ children, onClose }: { children: ReactNode; onClose: () => void }) => {
  const [container] = useState(() => document.createElement("div"));

Render a modal into its own DOM node with createPortal, so its stacking context and layout escape a clipped or transformed ancestor.

Chrome APIsintermediate

The inert attribute to trap focus outside a modal

export const openModal = (modalRoot: HTMLElement) => {
  const siblings = Array.from(document.body.children).filter(
    (el): el is HTMLElement => el !== modalRoot && el instanceof HTMLElement,
  );
  siblings.forEach((el) => {

Setting .inert on everything outside a custom modal removes it from tab order, clicks, and the a11y tree in one line — no focus-trap library.

Web Platformadvanced

A tiny promise-based wrapper around IndexedDB

const dbPromise = new Promise<IDBDatabase>((resolve, reject) => {
  const request = indexedDB.open("app-cache", 1);
  request.onupgradeneeded = () => request.result.createObjectStore("kv");
  request.onsuccess = () => resolve(request.result);
  request.onerror = () => reject(request.error);

Turn IndexedDB's callback-and-event API into two functions, idbGet and idbSet, that behave like a normal async key-value store.

Bunintermediate

Hot-reloading a dev server with bun --hot

declare global {
  var server: ReturnType<typeof Bun.serve> | undefined;
  var reloadCount: number;
}

bun --hot re-evaluates changed files without restarting the process, so an HTTP server's listener survives a save instead of dropping every open connection.

TypeScriptintermediate

unknown plus a type guard instead of any for safe parsing

type ApiUser = { id: string; email: string };

const isApiUser = (value: unknown): value is ApiUser =>
  typeof value === "object" &&
  value !== null &&

Accept untyped input like JSON.parse's output without any, by narrowing it through a type predicate before touching its fields.

Node.jsintermediate

performance.now() / hrtime.bigint() for accurate micro-benchmarks

import { performance } from "node:perf_hooks";

const benchmark = (fn: () => void, iterations = 100_000) => {
  const start = process.hrtime.bigint();
  for (let i = 0; i < iterations; i++) fn();

process.hrtime.bigint() gives nanosecond integer precision for micro-benchmarks; performance.now() is ms-resolution and good enough for most cases.

Reactintermediate

A 10-line useDebouncedValue custom hook

import { useState, useEffect } from "react";

export const useDebouncedValue = <T,>(value: T, delayMs: number): T => {
  const [debounced, setDebounced] = useState(value);

Debounce a fast-changing value, like search input, without redefining a timer effect in every component that needs one.

Chrome APIsintermediate

CSS @starting-style for entry animations with no JS

.toast {
  display: none;
  opacity: 0;
  translate: 0 12px;
  transition: opacity 0.2s ease, translate 0.2s ease, display 0.2s allow-discrete;

@starting-style supplies the missing before-state so a CSS transition can animate an element's first render — no class-added-next-frame trick, no library.

Web Platformintermediate

navigator.clipboard for real copy/paste, no execCommand

export const copyToClipboard = (text: string) =>
  navigator.clipboard.writeText(text).then(() => true).catch(() => false);

export const pasteFromClipboard = () =>
  navigator.clipboard.readText().then((text) => text).catch(() => null);

Copy text, read it back, and copy raw image data to the system clipboard with a promise-based API — no hidden textarea, no execCommand.

Bunadvanced

Piped-stdio subprocesses with Bun.spawn

const proc = Bun.spawn(["bun", "-e", "console.log((await Bun.stdin.text()).toUpperCase())"], {
  stdin: "pipe",
});

proc.stdin.write("hello from the parent\n");

Bun.spawn's stdin/stdout are a FileSink and a ReadableStream, so you can write to a child process incrementally and read its output as it streams back.

TypeScriptadvanced

A type-safe event emitter keyed by an event-name-to-payload map

type EventMap = Record<string, unknown>;

export class TypedEmitter<Events extends EventMap> {
  private listeners: { [K in keyof Events]?: Array<(payload: Events[K]) => void> } = {};

Make on() and emit() reject mismatched event names and payloads at compile time, from one map type instead of per-event overloads.

Node.jsintermediate

events.once() to await a single event without a listener callback

import { EventEmitter, once } from "node:events";

export const waitForReady = (emitter: EventEmitter) => once(emitter, "ready");

const bus = new EventEmitter();

events.once() turns a single EventEmitter event into an awaitable promise, replacing a one-shot .on() + manual .off() with one line.

Reactadvanced

useReducer with a discriminated-union action type

type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; error: string };

Model a fetch state machine as a discriminated union so an exhaustiveness check fails to compile the moment a reducer case is missing.

Chrome APIsadvanced

A minimal WebGPU compute shader

// No @webgpu/types in this repo's tsconfig, so these casts stand in for the
// missing ambient types. Swap them for the real types in a project that has
// @webgpu/types installed.
export const doubleOnGpu = async (input: Float32Array): Promise<Float32Array> => {
  const gpu = (navigator as any).gpu;

WebGPU's compute pipeline runs a WGSL kernel across GPU threads in parallel from a buffer you own — general-purpose GPU compute, not just triangles.

Web Platformintermediate

The Web Share API for a native share sheet

export const shareOrCopy = async (data: ShareData) => {
  if (!navigator.canShare?.(data)) {
    await navigator.clipboard.writeText(data.url ?? data.text ?? "");
    return "copied";
  }

Open the OS-native share sheet on a button click, and fall back to copying the link on browsers — Firefox desktop included — that don't support it.

Bunintermediate

A WebSocket server using Bun.serve's built-in upgrade

export const wsServer = Bun.serve({
  fetch(req, server) {
    return server.upgrade(req) ? undefined : new Response("Upgrade failed", { status: 500 });
  },
  websocket: {

Bun.serve() upgrades an HTTP request to a WebSocket in the fetch handler and reuses one handler object across every connection, no ws package needed.

TypeScriptadvanced

Building DeepPartial<T> from scratch

export type DeepPartial<T> = T extends readonly unknown[]
  ? T
  : T extends object
    ? { [K in keyof T]?: DeepPartial<T[K]> }
    : T;

Make every property optional at every nesting level, for patch-style updates, without touching arrays element by element.

Node.jsadvanced

Streaming a large JSON array without loading it into memory

import type { Writable } from "node:stream";

export const streamJsonArray = async (rows: AsyncIterable<unknown>, out: Writable) => {
  out.write("[");
  let first = true;

Write a large JSON array to a stream item by item as it's produced, instead of building the whole array in memory before calling JSON.stringify.

Reactadvanced

Context selector pattern to stop re-rendering every consumer

import { createContext, useContext, useSyncExternalStore } from "react";

type State = { count: number; user: { name: string } };
type Listener = () => void;

Build a selector hook on useSyncExternalStore so components only re-render when the slice of context state they read actually changes.

Chrome APIsadvanced

The File System Access API for native file read/write

// TypeScript's DOM lib has FileSystemFileHandle but not window.showOpenFilePicker
// itself yet -- narrow cast for just the missing entry point.
type ShowOpenFilePicker = (opts: {
  types: { description: string; accept: Record<string, string[]> }[];
}) => Promise<FileSystemFileHandle[]>;

showOpenFilePicker and createWritable read and overwrite a real file on disk from the browser — Chromium only, no Firefox or Safari support.

Web Platformintermediate

Container queries for component-level responsive design

.card-wrapper {
  container: card / inline-size;
}

.card {

Let a card switch to a two-column layout based on its own wrapper's width, not the viewport, so it works the same in a sidebar or a full-width column.

Bunadvanced

Bundling programmatically with Bun.build()

try {
  const result = await Bun.build({
    entrypoints: ["./src/index.ts"],
    outdir: "./dist",
    minify: true,

Bun.build() is the bun build CLI as a JS function, returning artifacts you can inspect, write, or serve directly instead of shelling out.

TypeScriptadvanced

const type parameters to preserve literal inference in generics

const asConstTuple = <const T extends readonly string[]>(...values: T): T => values;

export const statuses = asConstTuple("pending", "active", "done");

export type Status = (typeof statuses)[number];

Stop a generic function from widening ['pending','active'] to string[] on the way in, without forcing every caller to write as const.

Node.jsintermediate

Graceful shutdown: draining connections on SIGTERM

import { createServer } from "node:http";

const server = createServer((_req, res) => {
  setTimeout(() => res.end("ok"), 50); // pretend this request takes a moment
});

Stop accepting new connections on SIGTERM, let in-flight requests finish, and force-exit if draining takes too long.

Reactintermediate

useLayoutEffect vs useEffect: measuring the DOM before paint

import { useRef, useState, useLayoutEffect } from "react";

export const Tooltip = ({ text }: { text: string }) => {
  const [height, setHeight] = useState(0);
  const ref = useRef<HTMLDivElement>(null);

Use useLayoutEffect to measure a DOM node and apply the result before the browser paints, avoiding the flicker useEffect leaves behind.

Chrome APIsadvanced

The Navigation API for SPA routing without a router library

// TypeScript's DOM lib has neither URLPattern nor the Navigation API yet --
// narrow casts for just the shapes this snippet actually uses.
type UrlMatch = { pathname: { groups: Record<string, string | undefined> } };
type UrlPatternLike = { test: (i: { pathname: string }) => boolean; exec: (i: { pathname: string }) => UrlMatch | null };
const URLPattern = (globalThis as any).URLPattern as new (init: { pathname: string }) => UrlPatternLike;

navigation.addEventListener('navigate', ...) intercepts every link click and history change from one place — the primitive most routers wrap.

Web Platformintermediate

CSS :has() for parent-based styling logic

.empty-state {
  display: none;
}

.results:not(:has(li)) + .empty-state {

Style a table row from its checkbox and swap in an empty-state message when a list has no items, with zero JavaScript.

Bunintermediate

Password hashing with Bun.password, no bcrypt dependency

export const hashPassword = (password: string) =>
  Bun.password.hash(password, { algorithm: "argon2id", memoryCost: 19456, timeCost: 2 });

export const verifyPassword = (password: string, hash: string) => Bun.password.verify(password, hash);

Bun.password.hash and .verify wrap argon2 and bcrypt natively, so hashing a password needs no bcrypt or argon2 npm package at all.

TypeScriptintermediate

Branded types to stop mixing UserId and OrderId

type Brand<T, Name extends string> = T & { readonly __brand: Name };

export type UserId = Brand<string, "UserId">;
export type OrderId = Brand<string, "OrderId">;

Give two string IDs distinct types so passing one where the other belongs is a compile error, at zero runtime cost.

Node.jsadvanced

AsyncLocalStorage for request-scoped trace IDs across async calls

import { AsyncLocalStorage } from "node:async_hooks";
import { createServer } from "node:http";
import { randomUUID } from "node:crypto";

const requestContext = new AsyncLocalStorage<string>();

Thread a trace ID through every async call of a request, without passing it as an argument through every function in between.

Reactintermediate

React.lazy + Suspense with an error boundary fallback

import { lazy, Suspense, Component, type ReactNode } from "react";

// In a real app, SettingsPanelImpl would live in its own file and this
// would be lazy(() => import("./SettingsPanel")) instead -- this snippet
// is one self-contained file, so it wraps an inline component the same

Code-split a component with React.lazy and catch its load failures with an error boundary, so a flaky chunk load does not blank the page.

Chrome APIsadvanced

scheduler.postTask to yield to the main thread under load

type TaskPriority = "user-blocking" | "user-visible" | "background";
type PostTask = (cb: () => void, opts?: { priority?: TaskPriority }) => Promise<void>;

const postTask = (globalThis as { scheduler?: { postTask: PostTask } }).scheduler?.postTask;

scheduler.postTask breaks a long loop into prioritized chunks with real cancellation — a purpose-built replacement for setTimeout(fn, 0).

Web Platformintermediate

BroadcastChannel for cross-tab messaging

const channel = new BroadcastChannel("auth");

export const broadcastLogout = (reason: string) => channel.postMessage({ type: "logout", reason });

channel.addEventListener("message", (event: MessageEvent<{ type: string; reason: string }>) => {

Log out in one tab and every other open tab reacts instantly, with a plain publish/subscribe API and no polling or server round trip.

Bunintermediate

Snapshot testing with bun:test in 10 lines

import { test, expect } from "bun:test";

const formatInvoice = (id: number, cents: number) => ({
  id,
  total: `$${(cents / 100).toFixed(2)}`,

toMatchSnapshot() saves a value's serialized shape on first run and diffs it on every run after, catching output changes you didn't write assertions for.

TypeScriptadvanced

Conditional types + infer to extract a function's return type

type AsyncReturnType<Fn extends (...args: never[]) => unknown> = Fn extends (
  ...args: never[]
) => Promise<infer R>
  ? R
  : Fn extends (...args: never[]) => infer R

Build a return-type extractor that also unwraps the Promise, so async and sync functions land on the same resolved type.

Node.jsintermediate

The built-in node:test runner in 10 lines

import { test } from "node:test";
import assert from "node:assert/strict";

const add = (a: number, b: number) => a + b;

node:test plus node:assert/strict gives you a working test suite with zero dependencies and zero config files.

Reactadvanced

useImperativeHandle to expose an imperative API via ref

import { useRef, useImperativeHandle, type Ref } from "react";

export type VideoHandle = { play: () => void; pause: () => void; seekTo: (seconds: number) => void };

export const VideoPlayer = ({ src, ref }: { src: string; ref?: Ref<VideoHandle> }) => {

Expose a small, deliberate imperative API (play, pause, seekTo) from a component, instead of leaking raw DOM nodes through a ref.

Chrome APIsintermediate

<dialog> for an accessible modal with zero JS libraries

<button id="delete-trigger">Delete project</button>

<dialog id="confirm-dialog" closedby="any" aria-labelledby="confirm-title">
  <form method="dialog">
    <h2 id="confirm-title">Delete this project?</h2>

showModal(), ::backdrop, and closedby give a modal focus-trapping, Esc-to-close, and light-dismiss — no react-modal, no focus-trap package.

Web Platformadvanced

The Web Locks API to coordinate work across browser tabs

export const getFreshAuthToken = () =>
  navigator.locks.request("auth-token-refresh", async () => {
    const expiresAt = Number(localStorage.getItem("auth-token-expires-at") ?? 0);
    if (Date.now() < expiresAt) return localStorage.getItem("auth-token")!;

Stop every open tab from refreshing the same auth token at once — let one tab do the network call while the rest wait and reuse its result.

Bunintermediate

Bun.$ shell scripting for cross-platform build scripts

import { $ } from "bun";

await $`rm -rf dist`;
await $`mkdir dist`;

Bun's $ template literal runs a small bash-like shell with no /bin/sh dependency, so build scripts behave identically on Windows, macOS, and Linux.

TypeScriptadvanced

Mapped types with key remapping via as

type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

export const toGetters = <T extends object>(obj: T): Getters<T> => {

Turn a plain object type into a matching set of getter methods, renaming every key to getX without writing each one by hand.

Node.jsintermediate

structuredClone for a true deep copy, no JSON hacks

type Session = { id: string; startedAt: Date; roles: Set<string>; meta: Map<string, number> };

export const cloneSession = (session: Session): Session => structuredClone(session);

const original: Session = {

structuredClone() deep-copies Dates, Maps, Sets, and circular references correctly — JSON.parse(JSON.stringify()) silently mangles all four.

Reactintermediate

React.memo with a custom comparator for deep-equal props

import { memo } from "react";

type Props = { user: { id: string; name: string; tags: string[] } };

const isEqual = (prev: Props, next: Props) =>

Skip re-renders when props are structurally equal but not referentially equal, using memo second argument instead of a deep-equal library.

Web Platformintermediate

ResizeObserver for a responsive component with no resize listener

const setLayout = (el: HTMLElement, width: number) => {
  el.classList.toggle("is-wide", width >= 560);
  el.classList.toggle("is-compact", width < 320);
};

Give a component its own width-based breakpoints, driven by its actual box size instead of the window's, with no global resize listener at all.

Bunintermediate

Streaming a file response with Bun.file(), no extra deps

import { serve, file } from "bun";

const server = serve({
  async fetch(req) {
    const pathname = new URL(req.url).pathname;

Bun.file() returns a lazy file handle that streams straight into a Response, so serving a large file never buffers it fully in memory.

TypeScriptadvanced

Template literal types for typed route strings

type ParamNames<Path extends string> = Path extends `${string}:${infer Param}/${infer Rest}`
  ? Param | ParamNames<Rest>
  : Path extends `${string}:${infer Param}`
    ? Param
    : never;

Extract :param names out of a route string at the type level, so a route's caller must supply exactly the params that route needs.

Node.jsadvanced

worker_threads for CPU-bound work off the main thread

import { Worker, isMainThread, parentPort, workerData } from "node:worker_threads";

const fibonacci = (n: number): number => (n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2));

if (isMainThread) {

Offload a genuinely CPU-heavy computation to a worker_threads Worker so it stops blocking the event loop, using one self-contained file.

Reactintermediate

useTransition to keep input responsive during expensive updates

import { useState, useTransition } from "react";

export const FilterableList = ({ items }: { items: string[] }) => {
  const [text, setText] = useState("");
  const [visible, setVisible] = useState(items);

Mark an expensive state update as a transition so React keeps typing responsive and only shows the update once it is ready.

Chrome APIsintermediate

The Popover API for a dismissible popover, no positioning library

// togglePopover's { source } option is current spec but not yet in TypeScript's DOM lib.
type TogglePopover = (options?: { source?: HTMLElement; force?: boolean }) => void;
const menu = document.querySelector<HTMLElement>("#user-menu")!;
const trigger = document.querySelector<HTMLButtonElement>("#user-menu-trigger")!;

popover="auto" gives light-dismiss, Esc-to-close, and top-layer stacking for free — no click-outside listener, no z-index fights.

Web Platformintermediate

IntersectionObserver for lazy-loaded images in 10 lines

const observer = new IntersectionObserver((entries, obs) => {
  for (const entry of entries) {
    if (!entry.isIntersecting) continue;
    const img = entry.target as HTMLImageElement;
    img.src = img.dataset.src ?? "";

Load images only when they're about to enter the viewport, using one shared observer instead of a scroll listener per image.

Bunintermediate

Querying bun:sqlite, Bun's built-in embedded database

import { Database } from "bun:sqlite";

const db = new Database(":memory:");
db.exec(`CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)`);

bun:sqlite ships inside the Bun binary with a synchronous, prepared-statement API, so a local database needs zero npm installs.

TypeScriptintermediate

satisfies to validate shape while keeping literal types

type RGB = readonly [red: number, green: number, blue: number];

const palette = {
  primary: [15, 98, 254],
  danger: [220, 38, 38],

Check an object against a type without widening it to that type, so autocomplete and literal inference on the value survive the check.

Node.jsadvanced

Piping a Readable through a Transform stream with backpressure

import { createReadStream, createWriteStream } from "node:fs";
import { pipeline } from "node:stream/promises";
import { Transform } from "node:stream";

const upperCaseChunks = new Transform({

Use stream/promises pipeline() to move data through a Transform without ever buffering more than the stream can hold.

Reactintermediate

useDeferredValue for a jank-free typeahead search

import { useState, useDeferredValue, useMemo } from "react";

const filterItems = (items: string[], query: string) =>
  items.filter((item) => item.toLowerCase().includes(query.toLowerCase()));

Defer expensive list re-renders behind fast keystrokes with useDeferredValue, and show a stale-content hint while it catches up.

Chrome APIsintermediate

The View Transitions API for animated state changes

export const swapView = (activeEl: HTMLElement, render: () => void) => {
  if (!document.startViewTransition) {
    render();
    return;
  }

document.startViewTransition animates a DOM update with a browser-computed crossfade or morph — no keyframes, no FLIP technique, no library.

Web Platformintermediate

AbortSignal.any() to combine multiple abort signals into one

const routeChangeController = new AbortController();
window.addEventListener("pagehide", () => routeChangeController.abort(), { once: true });

export const search = (query: string) => {
  const requestController = new AbortController();

Cancel a fetch when any of several unrelated conditions fires — a timeout, a route change, an explicit cancel — without hand-rolling a signal merger.

Bunintermediate

Bun.serve() with a routes object: a zero-dependency HTTP server

export const app = Bun.serve({
  routes: {
    "/api/health": new Response("ok"),
    "/api/users/:id": (req) => Response.json({ id: req.params.id }),
    "/api/users": {

Bun.serve()'s routes option matches paths, HTTP methods, and :params natively, replacing a router dependency for most REST APIs.

TypeScriptintermediate

Discriminated unions with an exhaustive switch and a never check

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; side: number }
  | { kind: "rectangle"; width: number; height: number };

Make adding a new union case a compile error, not a silent runtime bug, using a switch that assigns the leftover case to never.

Node.jsintermediate

AbortController to cancel a fetch cleanly after a timeout

export const fetchWithTimeout = async (url: string, timeoutMs: number) => {
  const signal = AbortSignal.timeout(timeoutMs);
  try {
    const response = await fetch(url, { signal });
    return await response.text();

Use AbortSignal.timeout() to cancel a fetch after N milliseconds and tell a timeout apart from every other kind of failure.

Reactadvanced

useSyncExternalStore for tearing-free external store subscriptions

import { useSyncExternalStore } from "react";

const EVENTS = ["online", "offline"] as const;

const subscribe = (onStoreChange: () => void) => {

Subscribe a component to state that lives outside React, like navigator.onLine, without ever showing a torn snapshot mid-render.