Uncategorized

What Is Redis Used For? 7 Real Use Cases in Web Applications Beyond Caching

Short answer: Redis is an in-memory data structure store used as a cache, a database, a message broker and a coordination layer. In real web applications it is most often used for caching, session storage, rate limiting, real-time messaging (pub/sub), leaderboards and counters, background job queues, and distributed locks. Almost every article on this topic stops at “Redis is a fast cache”. That is true, and it is also the least interesting thing about it. If you already have a Postgres or MySQL database, the real question is not what is Redis, it is: which problem on my current backlog does Redis actually solve better than my database? This post answers that. Seven concrete use cases, each with the Redis data structure behind it, a short code snippet, and the trade-offs you should know before shipping it. Redis in 60 seconds: why it is fast and why that matters Redis (REmote DIctionary Server) keeps your data in RAM and serves it over a very simple protocol. Typical response times are sub-millisecond, and a single node routinely handles tens of thousands of operations per second on modest hardware. A Crash Course in Redis tackles the same question from another angle. Three properties explain most of its use cases: In-memory storage: no disk seek on the read path, so lookups are extremely cheap. Atomic commands: each command (and each Lua script or transaction) runs to completion without interleaving, which makes counters, locks and queues safe without you writing locking logic. Rich data structures: it is not just key to string. You get lists, hashes, sets, sorted sets, streams, bitmaps, HyperLogLog, geospatial indexes and vector indexes. That last point is the one developers underuse. Picking the right structure is usually what turns a hard problem into five lines of code. Data structure to problem mapping Redis structure What it is good at Typical use case String Blob storage with TTL, atomic counters Cache entries, feature flags, rate limit counters Hash Objects with field level updates Sessions, user profiles, shopping carts List FIFO / LIFO with blocking reads Simple job queues, activity feeds Set Uniqueness, intersections Online users, tags, deduplication Sorted set (ZSET) Ranking and range queries by score Leaderboards, sliding window rate limits, delayed jobs Pub/Sub channel Fire and forget fan-out WebSocket broadcast across app servers Stream Persistent log with consumer groups Event pipelines, reliable task distribution Vector index Similarity search on embeddings RAG retrieval, semantic caching for LLM apps 1. Caching (the baseline use case, done properly) Yes, caching is the number one answer to “what is Redis used for”. The part most tutorials skip is the policy around it: key naming, TTL, and invalidation. The classic pattern is cache-aside: // Node.js with ioredis async function getProduct(id) { const key = `product:v2:${id}`; const hit = await redis.get(key); if (hit) return JSON.parse(hit); const product = await db.products.findById(id); // 5 minute TTL, always set one await redis.set(key, JSON.stringify(product), ‘EX’, 300); return product; } Practical rules that save you pain later: Always set a TTL. A cache without expiry is a memory leak with extra steps. Version your key prefixes (product:v2:). Changing the serialized shape then becomes a one-line deploy instead of a mass invalidation script. Configure maxmemory and an eviction policy such as allkeys-lru on pure cache instances. Beware of stampedes. When a hot key expires, hundreds of requests may hit the database at once. Add a short lock or a randomized TTL jitter. 2. Session storage for stateless app servers The moment you run more than one application instance behind a load balancer, in-process sessions break: a user logs in on server A and the next request lands on server B. Storing sessions in Redis makes your app servers stateless and disposable. // Express + connect-redis import session from ‘express-session’; import { RedisStore } from ‘connect-redis’; app.use(session({ store: new RedisStore({ client: redis, prefix: ‘sess:’ }), secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, secure: true, sameSite: ‘lax’, maxAge: 86400000 } })); Why Redis beats a database table here: the session TTL is handled natively by Redis (no cron job to clean rows), writes happen on almost every request, and the data is cheap to lose compared to business data. In Spring Boot the equivalent is Spring Session with spring-session-data-redis; in Django it is django.contrib.sessions.backends.cache; in Laravel it is SESSION_DRIVER=redis. Watch out: if your Redis instance is purely a cache with LRU eviction, do not put sessions on it. An eviction becomes a forced logout. Use a separate instance or logical database with noeviction. 3. Rate limiting and abuse protection Rate limiting needs a shared, atomic counter that all your app instances can agree on. That is a textbook fit for Redis. The simplest version is a fixed window with INCR plus EXPIRE, done atomically in Lua so two concurrent requests cannot both skip the expiry: — KEYS[1] = rate:login:ip:1.2.3.4 , ARGV[1] = window seconds local current = redis.call(‘INCR’, KEYS[1]) if current == 1 then redis.call(‘EXPIRE’, KEYS[1], ARGV[1]) end return current # Python, redis-py allowed = 20 count = limiter_script(keys=[f”rate:login:ip:{ip}”], args=[60]) if count > allowed: abort(429) Need something smoother than a fixed window? Use a sorted set as a sliding window log: add one member per request scored by timestamp, drop everything older than the window, then count. ZREMRANGEBYSCORE rate:api:user:42 0 <now_ms – 60000> ZADD rate:api:user:42 <now_ms> <request_id> ZCARD rate:api:user:42 EXPIRE rate:api:user:42 60 Fixed window is cheaper, sliding window is fairer. For very high volume endpoints, a token bucket in Lua gives you burst tolerance with a constant memory footprint. 4. Pub/sub and real-time features across servers You have WebSockets, three Node or Rails processes, and a message that must reach a user connected to a different process. Redis pub/sub is the standard glue. # terminal A (consumer side, one per app instance) SUBSCRIBE room:general # terminal B (whatever process produced the event) PUBLISH room:general ‘{“user”:”amelie”,”text”:”deploy done”}’ // Socket.IO Redis adapter: broadcast works across all instances import { createAdapter } from ‘@socket.io/redis-adapter’; io.adapter(createAdapter(pubClient, subClient)); io.to(‘room:general’).emit(‘message’, payload); Important limitation: classic pub/sub is

What Is Redis Used For? 7 Real Use Cases in Web Applications Beyond Caching Read More »

How to Write a Web Development Project Proposal: Structure, Pricing Sections, and Scope Wording

Most freelancers and small agencies lose projects for one of two reasons: the proposal is vague, or the proposal is a price list. A strong web development project proposal does something different. It proves you understood the problem, it frames the money so the client can say yes without a committee, and it quietly installs the guardrails that stop scope creep before the first line of code is written. This guide breaks down every section a winning proposal needs, in the order it should appear, with sample wording you can adapt. We also cover pricing presentation, payment milestones, and the exact scope-change clauses that protect your margin. Proposal, Quote, SOW, Contract: Know What You Are Sending Before structure, get the terminology right, because mixing these up is how disputes start. Document Purpose Legally binding? Quote / estimate A number and a short description Usually not Web development project proposal Sells the solution, defines scope, price, timeline and terms Becomes binding once countersigned or referenced by the contract Statement of work (SOW) The operational detail: deliverables, acceptance, milestones Yes, as an annex to the contract Master services agreement Liability, IP, confidentiality, termination, governing law Yes For projects under roughly 50k, most small agencies merge the proposal and the SOW into a single signable document, then attach standard terms. That is the model used throughout this article. The Structure: 14 Sections of a Winning Web Development Proposal Aim for 6 to 12 pages. Shorter than that and the client feels you did not listen. Longer and the decision maker skims past the part that matters. # Section Job it does Length 1 Cover page Looks professional, names the project 1 page 2 Discovery summary Proves you listened Half page 3 Goals and success metrics Ties the build to business outcomes Half page 4 Proposed solution and approach Shows how you will build it 1 to 2 pages 5 Scope of work and deliverables Defines exactly what is included 1 to 2 pages 6 Out of scope / exclusions Blocks scope creep Half page 7 Technical stack and hosting Sets expectations and third-party costs Half page 8 Timeline and milestones Answers “when is it live?” 1 page 9 Investment and pricing Makes the number easy to approve 1 page 10 Payment schedule and terms Protects cash flow Half page 11 Change request process Monetises new requests instead of absorbing them Half page 12 Client responsibilities and assumptions Stops delays being your fault Half page 13 Warranty, support and maintenance Creates recurring revenue Half page 14 Validity, next steps, signature Creates urgency and closes Half page Credentials, case studies and team bios go in an appendix. They are reassurance, not argument, and they should never sit between the scope and the price. 1. Cover Page Keep it to the project name, the client name, your company, the date, a version number and a validity date. The version number matters more than people think: when you are on revision three of a proposal, everyone needs to know which document is being signed. Sample wording: Web Development Project Proposal E-commerce Replatform and Checkout Redesign Prepared for: Northfield Supply Ltd. Prepared by: Coding4 Date: 1 October 2026 | Version 1.2 | Valid until: 31 October 2026 2. Discovery Summary: Repeat the Problem in Their Words This is the highest-leverage paragraph in the entire document. Clients buy from the supplier who clearly understood the brief. Summarise what you heard in the discovery call, using their vocabulary, their numbers and their internal terms. Sample wording: During our call on 24 September, you described three pressures on the current site. First, the checkout built in 2019 fails on mobile for roughly 18 percent of sessions, which your analytics team links to an abandoned-cart rate of 74 percent. Second, your product team cannot publish a new category page without a developer, creating a two-week lag on seasonal campaigns. Third, the current hosting contract renews in March 2027 and you want to be off it before then. This proposal addresses all three, with the checkout prioritised in Phase 1. Why this beats a generic intro It makes the rest of the document feel bespoke, not templated. It gives the internal champion a paragraph they can forward to their boss. It anchors the scope: anything not described here is clearly new work later. 3. Goals and Success Metrics Convert the problem into measurable targets. Three to five is plenty. Always attach a measurement method, otherwise “improve performance” becomes an argument at launch. Goal Target Measured by Reduce mobile checkout abandonment From 74% to under 60% GA4 funnel, 30 days post-launch Core Web Vitals LCP under 2.5s on 4G, INP under 200ms Lighthouse CI on five key templates Content autonomy New category page published without developer input UAT task completed by marketing lead Add a short qualifier so targets do not become guarantees: “Targets are shared objectives based on current analytics. They depend on factors outside the build, including traffic quality, pricing and stock availability.” 4. Proposed Solution and Approach Describe the shape of the build, then the phases. Avoid dumping your entire methodology. The client wants to know what happens, in what order, and what they will see at each stage. Suggested phase structure Discovery and technical audit: requirements workshop, content inventory, analytics review, technical specification sign-off. UX and UI design: sitemap, wireframes for key templates, high-fidelity designs for agreed page types. Build: front-end templates, CMS configuration, integrations, custom modules. Content and data migration: defined volume of pages, products and redirects. QA, UAT and accessibility checks: cross-browser testing, device matrix, WCAG 2.2 AA review. Launch and handover: DNS cutover, monitoring, documentation, training session. Name the exact page templates. “Responsive website” is unbounded. “Nine unique templates: home, category, product, cart, checkout, blog index, blog article, contact, and a flexible content page” is bounded, and that boundary is worth real money when template number ten gets requested in week six. 5. Scope of Work and Deliverables Deliverables must be countable nouns. If a line

How to Write a Web Development Project Proposal: Structure, Pricing Sections, and Scope Wording Read More »

GDPR Compliance Checklist for Web Developers: 18 Technical Requirements to Implement

Most GDPR articles are written for lawyers and compliance officers. They tell you that you need a “lawful basis” and that data must be “processed securely”, then leave you staring at your codebase wondering which migration, which cron job and which middleware you are supposed to write on Monday morning. This GDPR compliance checklist for developers takes the opposite approach. Every item below answers three questions: what to build, where it usually breaks in real projects, and how to verify it before launch. No legal theory, no fine-print recitals. Just the technical work that regulators, auditors and your own security team will eventually ask about. Note: this is engineering guidance, not legal advice. Your DPO or legal counsel still decides your lawful bases and retention periods. Your job is to implement them correctly. The 18 requirements at a glance # Requirement Layer Typical effort 1 Personal data inventory generated from the schema Data model 1 to 2 days 2 Lawful basis recorded per processing activity Config Half a day 3 Transparency at the point of collection Frontend 1 day 4 Block non-essential scripts before consent Frontend 2 to 4 days 5 Consent UI with symmetric accept and reject Frontend 1 to 2 days 6 Versioned consent proof storage Backend 1 day 7 Data minimization in forms, APIs and logs Full stack Ongoing 8 Encryption in transit, HSTS, secure cookie flags Infra Half a day 9 Encryption at rest with managed keys Infra / DB 2 to 5 days 10 Pseudonymization, hashing and IP truncation Backend 1 to 3 days 11 Automated retention and purge jobs Backend 3 to 5 days 12 Data export endpoint (access and portability) Backend 3 to 5 days 13 Right to erasure endpoint with cascade rules Backend 5 to 10 days 14 Rectification and restriction of processing Backend 2 to 3 days 15 Audit logging of personal data access Backend 3 to 5 days 16 Least privilege access and clean non-prod data Infra / process 2 to 5 days 17 Processor register, DPAs and transfer safeguards Process 1 to 2 days 18 Breach detection and 72 hour notification readiness Ops 2 to 4 days Part 1: Know what you actually hold 1. Generate a personal data inventory from your schema What to build. A machine-readable map of every column, document field, log stream and cache key that contains personal data. Do not maintain it in a spreadsheet that dies after two sprints. Annotate it in the code itself so it stays in sync. Related reading: The Only GDPR Compliance Checklist You’ll Ever Need. # data_classification.yml users: email: { pii: true, category: contact, retention: account_lifetime + 30d } password_hash:{ pii: true, category: credential, retention: account_lifetime } last_login_ip:{ pii: true, category: network, retention: 90d } locale: { pii: false } orders: shipping_address: { pii: true, category: contact, retention: 10y_legal_invoice } Where it breaks. Teams map the primary database and forget the periphery: Redis sessions, Elasticsearch indexes, S3 uploads, webhook payloads stored for debugging, CSV exports in a shared drive, and the analytics warehouse that quietly replicates everything. How to verify. Run a grep for email-like patterns across your object storage and log aggregator. If you find personal data in a system that is not in your inventory, the inventory is wrong. Add a CI check that fails when a new migration adds a column without a classification entry. 2. Record a lawful basis for every processing activity What to build. Each feature that touches personal data should be tied to one of the six lawful bases (consent, contract, legal obligation, vital interests, public task, legitimate interests). Keep it as configuration next to the feature, not in a Confluence page. This matters technically because the basis determines the code path: Consent requires a consent check before execution and a full withdrawal path. Contract requires no consent gate but strict purpose limitation. Legal obligation usually overrides deletion requests, so your erasure logic must know about it. Where it breaks. Marketing emails sent under “legitimate interests” while the frontend still shows a consent checkbox, producing two contradictory sources of truth. Or a soft-deleted user who keeps receiving newsletters because the mailing list lives in a third-party tool. How to verify. Pick three features at random and trace the lawful basis from the config file to the actual runtime check. If the check does not exist in code, it does not exist. 3. Put transparency at the point of collection What to build. Every form that collects personal data needs a visible, contextual explanation of purpose and retention, linked to the full privacy notice. Version your privacy notice and expose the version in the page markup so you can correlate it with stored consent. Where it breaks. The signup form is compliant, but the newsletter modal, the support chat widget, the abandoned-cart email capture and the in-app survey are not. Each was shipped by a different team. How to verify. Crawl your own site and list every <form> and third-party widget that accepts input. Match each one against your inventory. Anything unmatched is a gap. Part 2: Cookie consent that actually holds up 4. Block non-essential scripts before consent, not after This is the single most common failure in real audits. A banner that appears while Google Analytics, Meta Pixel and a heatmap tool have already fired is not consent, it is decoration. What to build. Load tags in a blocked state and release them only on an explicit opt-in event. <!– Blocked by default: type is not executable –> <script type=”text/plain” data-consent-category=”analytics” src=”https://cdn.example.com/analytics.js”></script> <script> window.addEventListener(‘consent:updated’, (e) => { const granted = e.detail.categories; // [‘necessary’,’analytics’] document .querySelectorAll(‘script[type=”text/plain”][data-consent-category]’) .forEach((node) => { if (!granted.includes(node.dataset.consentCategory)) return; const s = document.createElement(‘script’); if (node.src) s.src = node.src; else s.textContent = node.textContent; node.replaceWith(s); }); }); </script> If you use a tag manager, drive everything through consent signals and make the default state denied for analytics, ad storage and personalization. Where it breaks. Server-side rendered pages inject tracking in the HTML head before hydration. Embedded YouTube, Google Maps

GDPR Compliance Checklist for Web Developers: 18 Technical Requirements to Implement Read More »

How to Add Google Analytics 4 to a React Single Page Application: Tracking Route Changes Correctly

You added the GA4 snippet to your React app, deployed it, opened the Realtime report and saw exactly one page view. Then you clicked through five routes and… nothing. Welcome to the most common problem with Google Analytics in a React single page application: GA4 measures document loads, and a SPA only loads the document once. This tutorial shows you exactly why that happens and how to fix it properly with gtag.js, React Router and a reusable usePageTracking hook. We also cover the two things most tutorials skip: debugging with DebugView and avoiding duplicate page_view counts that silently inflate your traffic numbers. Why GA4 misses page views in a React SPA How gtag.js behaves on a classic website On a traditional multi-page website, every navigation triggers a full browser document load. The GA4 snippet is executed again, the config command runs, and gtag.js automatically sends a page_view event. One document load equals one page view. Nothing else to do. What breaks in React A React SPA served by React Router uses the History API (pushState / replaceState). The URL in the address bar changes, the component tree re-renders, but: the document is never reloaded, the GA4 snippet is never executed again, no automatic page_view is sent after the very first load. Result: GA4 attributes 100% of the session to your landing route, your bounce rate looks artificially perfect, engagement time is glued to a single page, and funnel or path reports are useless. For the wider picture, see Track Single Page Applications with GTM and GA4. Isn’t enhanced measurement supposed to handle this? GA4 data streams ship with an enhanced measurement option called “Page changes based on browser history events”. It listens to History API changes and fires a page_view automatically. It works, but it is not reliable enough for a production React app: It fires before React has updated document.title, so your page titles are wrong (usually the previous page’s title). It cannot wait for data loaders, suspense boundaries or auth redirects to finish. It fires on replaceState calls too, which many routers and filter UIs use for query-string updates, generating noise. It gives you zero control over extra parameters (route pattern, logged-in state, content group). And the classic trap: if you leave it ON and you also send manual events, every navigation is counted twice. The clean approach for React is: turn the automatic behaviour off and send page_view yourself, at the exact moment you decide. Step 1: prepare the GA4 property and data stream In Google Analytics, go to Admin > Data collection and modification > Data streams and open (or create) your Web stream. Copy the Measurement ID (format G-XXXXXXXXXX). Click Enhanced measurement > the gear icon. Expand Page views and uncheck “Page changes based on browser history events”. Leave the main “Page views” toggle ON (it covers the initial document load if you ever re-enable it). Save. Why this matters: this single checkbox is responsible for most “my GA4 numbers are doubled” tickets in React projects. Step 2: install gtag.js with send_page_view disabled Add the snippet to index.html (Vite, CRA) or to your root document. The key is the send_page_view: false flag: it tells gtag.js “load, create the session, but let me decide when a page view happens”. <!– index.html –> <script async src=”https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX”></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){ dataLayer.push(arguments); } gtag(‘js’, new Date()); gtag(‘config’, ‘G-XXXXXXXXXX’, { send_page_view: false }); </script> If you prefer to keep the ID out of your HTML, load the script dynamically from React using an environment variable. With Vite: // src/analytics/loadGtag.ts export function loadGtag(measurementId: string) { if (!measurementId || document.getElementById(‘ga4-script’)) return; const script = document.createElement(‘script’); script.id = ‘ga4-script’; script.async = true; script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`; document.head.appendChild(script); window.dataLayer = window.dataLayer || []; window.gtag = function gtag() { window.dataLayer.push(arguments); }; window.gtag(‘js’, new Date()); window.gtag(‘config’, measurementId, { send_page_view: false }); } Store the ID in .env as VITE_GA_MEASUREMENT_ID=G-XXXXXXXXXX (or REACT_APP_GA_MEASUREMENT_ID with Create React App). Step 3: create a tiny typed analytics wrapper Never call window.gtag directly from your components. A thin wrapper gives you TypeScript safety, a single place to add consent checks, and the ability to no-op in development. // src/analytics/index.ts declare global { interface Window { dataLayer: unknown[]; gtag?: (…args: unknown[]) => void; } } export const GA_ID = import.meta.env.VITE_GA_MEASUREMENT_ID as string | undefined; const ENABLED = Boolean(GA_ID) && import.meta.env.PROD; export function pageview(path: string, title?: string) { if (!ENABLED || !window.gtag) return; window.gtag(‘event’, ‘page_view’, { page_title: title ?? document.title, page_location: window.location.origin + path, page_path: path, send_to: GA_ID }); } export function trackEvent(name: string, params: Record<string, unknown> = {}) { if (!ENABLED || !window.gtag) return; window.gtag(‘event’, name, params); } export {}; Which parameters should you send? Parameter Required? Notes page_location Yes Full URL including origin. If omitted, GA4 keeps the URL of the initial load. page_title Strongly recommended Must be read after React updated the title, otherwise reports show the previous page. page_path Optional Not a native GA4 dimension but handy as a custom dimension. page_referrer Optional Set it to the previous in-app URL to rebuild real navigation paths. send_to Optional Useful when several destinations (Ads, second GA4 property) share the page. Step 4: the usePageTracking custom hook This is the heart of the setup. The hook listens to React Router location changes and fires exactly one page_view per real navigation. // src/analytics/usePageTracking.ts import { useEffect, useRef } from ‘react’; import { useLocation } from ‘react-router-dom’; // ‘react-router’ in v7 import { pageview } from ‘./index’; export function usePageTracking() { const location = useLocation(); const lastTrackedRef = useRef<string | null>(null); useEffect(() => { const path = location.pathname + location.search; // Guard against React 18/19 StrictMode double effects and re-renders if (lastTrackedRef.current === path) return; lastTrackedRef.current = path; // Let React commit the new document.title before reading it const timer = window.setTimeout(() => { pageview(path); }, 0); return () => window.clearTimeout(timer); }, [location.pathname, location.search]); } Three details that make this hook production ready The ref guard prevents the double fire caused by <StrictMode> in development and by any parent re-render.

How to Add Google Analytics 4 to a React Single Page Application: Tracking Route Changes Correctly Read More »

How to Optimize Core Web Vitals in WordPress: Fix LCP, INP, and CLS Step by Step

Most WordPress “speed” guides tell you to buy better hosting, install a cache plugin and compress your images. That advice is not wrong, but it will not tell you why your LCP is 4.1 seconds, why your INP spikes on mobile menus, or why your layout jumps when an ad loads. This guide takes the opposite approach. We diagnose each metric separately using real field data, then apply targeted fixes with concrete plugin settings and copy-paste code snippets. If you want to optimize Core Web Vitals in WordPress without guessing, work through the three sections in order: LCP, then INP, then CLS. The three metrics and the targets you must hit Google evaluates the 75th percentile of real user visits over a rolling 28-day window, split between mobile and desktop. Passing means all three metrics are in the “good” range. Metric What it measures Good Needs work Poor LCP (Largest Contentful Paint) Loading speed of the main visual element ≤ 2.5 s 2.5 s – 4 s > 4 s INP (Interaction to Next Paint) Responsiveness to clicks, taps and key presses ≤ 200 ms 200 ms – 500 ms > 500 ms CLS (Cumulative Layout Shift) Visual stability during the whole page lifespan ≤ 0.1 0.1 – 0.25 > 0.25 A useful secondary metric is TTFB (Time to First Byte). Keep it under 800 ms, because every millisecond of TTFB is added directly to LCP. Step 0: Diagnose with field data, not with a lab score The number one mistake is optimizing for the Lighthouse performance score in the browser. Lighthouse is a simulated lab test on a throttled connection. Google ranks on field data collected from real Chrome users (the Chrome UX Report, or CrUX). 1. PageSpeed Insights: read the top block only, first Open pagespeed.web.dev and enter your URL. The top section, “Discover what your real users are experiencing”, is CrUX field data. Do this: Switch between Mobile and Desktop. Mobile is almost always the failing one. Toggle between this URL and this origin. If the URL has no data, it means low traffic, and Google falls back to origin-level data. Open the LCP subparts breakdown: TTFB, resource load delay, resource load duration, element render delay. This single view tells you which of the four LCP fixes you actually need. 2. Search Console: find failing URL groups Go to Experience > Core Web Vitals in Google Search Console. Google groups similar URLs together, so you usually get patterns like “all single posts” or “all product pages”. Fix one representative template and the whole group improves. 3. Chrome UX Report for a wider view Use the CrUX Vis tool or the CrUX History API to see 25 weeks of trends per origin. This is how you prove a deployment helped, instead of trusting a single PSI run. For low-traffic sites, origin-level CrUX plus your own RUM script is the realistic combination. 4. Collect your own RUM data (5 minutes of work) Field data with attribution tells you exactly which element and which script caused the problem. Add this to your theme footer or via a code snippet plugin: <script type=”module”> import {onLCP, onINP, onCLS} from ‘https://unpkg.com/web-vitals@5/attribution?module’; function report(metric) { // Send to your endpoint, GA4 or just log while debugging console.log(metric.name, metric.value, metric.attribution); } onLCP(report); onINP(report); onCLS(report); </script> With attribution enabled you get the LCP element selector, the INP target element and interaction type, and the largest shift source for CLS. That is the difference between guessing and fixing. 5. Local debugging tools Chrome DevTools > Performance: record, then read the Core Web Vitals lane. It marks the LCP element and highlights long tasks. Web Vitals Chrome extension: live overlay of LCP, INP and CLS while you browse your own site. Query Monitor: server-side plugin, shows slow database queries, slow hooks and which plugin loads which script. DevTools > Rendering > Layout Shift Regions: visually flashes every element that shifts. Step 1: Fix LCP in WordPress LCP is made of four parts. Find your dominant part in PSI, then apply only the matching fixes. LCP subpart Typical WordPress cause Fix TTFB Shared hosting, no page cache, uncached admin-ajax, old PHP Full page cache, CDN, PHP 8.3+, Redis object cache Resource load delay Hero image lazy-loaded, injected by JS, or a CSS background Preload + fetchpriority=”high”, remove lazy loading Resource load duration 2 MB uncompressed JPEG, no srcset, no CDN WebP/AVIF, correct sizes, image CDN Element render delay Render-blocking CSS/JS, web fonts, slider or page builder JS Critical CSS, defer JS, font-display: swap 1.1 Make the LCP resource discoverable in the HTML If the browser cannot find your hero image in the initial HTML, it cannot start downloading it early. Three WordPress patterns break this: lazy-loaded featured images, sliders that build markup with JavaScript, and hero images set as CSS backgrounds. First, stop WordPress from lazy loading the images above the fold: // Do not lazy-load the first 2 in-content images add_filter( ‘wp_omit_loading_attr_threshold’, function () { return 2; } ); Then push the first image to high priority: add_filter( ‘wp_get_attachment_image_attributes’, function ( $attr ) { static $done = false; if ( $done || is_admin() ) { return $attr; } $done = true; $attr[‘loading’] = ‘eager’; $attr[‘fetchpriority’] = ‘high’; unset( $attr[‘decoding’] ); return $attr; }, 10, 1 ); If your hero is a CSS background (very common with Elementor, Divi and WPBakery sections), the browser only discovers it after CSS parsing. Preload it explicitly: add_action( ‘wp_head’, function () { if ( ! is_front_page() ) { return; } echo ‘<link rel=”preload” as=”image” fetchpriority=”high” ‘ . ‘href=”https://example.com/wp-content/uploads/hero-1280.webp” ‘ . ‘imagesrcset=”https://example.com/wp-content/uploads/hero-768.webp 768w, ‘ . ‘https://example.com/wp-content/uploads/hero-1280.webp 1280w” ‘ . ‘imagesizes=”100vw”>’; }, 1 ); Important: preload only one resource per page and only the real LCP element. Preloading five images is the same as preloading nothing, because you dilute bandwidth priority. Related reading: How to Improve Core Web Vitals on WordPress. 1.2 Keep the LCP image small Serve WebP or AVIF. Plugins: ShortPixel, Imagify, EWWW, Converter for Media. Do not serve a 2560px image

How to Optimize Core Web Vitals in WordPress: Fix LCP, INP, and CLS Step by Step Read More »

Responsive Design Breakpoints: Which Values to Use and Why in 2026

Most codebases we audit at coding4.net contain the same five numbers: 576, 768, 992, 1200, 1400. They were copied from a CSS framework years ago, nobody remembers why, and half of them never actually trigger a meaningful layout change. That is the problem with responsive design breakpoints today: they are inherited, not decided. This guide gives you a defensible set of values for the 2026 device landscape, shows the media queries to write in a mobile-first codebase, explains where container queries replace breakpoints entirely, and ends with a testing routine you can run in fifteen minutes. Quick answer: the breakpoint values we use in 2026 If you need a starting scale today, this is the one we ship on client projects. It is intentionally smaller than Bootstrap’s and expressed in em so it survives browser zoom. Name Value (px) Value (em) What it is actually for Base 320 and up no query Single column, the default everything inherits sm 480 30em Large phones: 2-up cards, bigger type, side-by-side form fields md 768 48em Tablet portrait: real two-column layouts, visible nav items lg 1024 64em Tablet landscape and small laptops: sidebars, full horizontal nav xl 1280 80em Laptops and most desktops: 3 to 4 column grids, wider gutters 2xl 1600 100em Large and ultrawide screens: cap the container, add breathing room Five breakpoints maximum. If your project needs a sixth, it usually means one component needs a container query, not a global viewport rule. What a breakpoint really is (and what it is not) A breakpoint is the width at which your layout stops looking good and needs a new set of rules. That is the whole definition. It is not a device, and it never was. Chasing devices was already a losing game in 2015. In 2026 it is absurd: Common phone viewports sit at 360, 390, 393, 402, 412, 430 and 440 CSS pixels, and none of them match a framework number. Foldables change viewport mid-session: roughly 344 to 400px folded, 673 to 884px unfolded. Tablets report 768, 810, 834, 1024 and 1133 depending on model and orientation. A 1920px laptop at 125% OS scaling reports 1536 CSS pixels to your CSS. At 150% it reports 1280. Desktop browser windows are frequently not maximized, so any width between 700 and 2000 is normal. The only sane conclusion: pick breakpoints where your content breaks, then verify the values fall in gaps between common device widths rather than right on top of them. Why copy-pasted Bootstrap breakpoints hurt you Framework breakpoints are not wrong, they are just generic. They were designed to be acceptable for every possible site, which means they are optimal for none. Three concrete problems: 576px is a phantom. Very few real devices sit between 540 and 600px. Many teams write rules there that almost never fire, then debug them for hours. 992px cuts the iPad landscape audience. A 1024px tablet gets the desktop layout, including hover-only interactions, with no pointer check. Pixel-based queries ignore zoom. Users who zoom to 200% get a different experience than users on a small screen, even though the reading conditions are similar. Em-based queries handle both. If you are on Bootstrap or Tailwind, you do not need to abandon the framework. You need to override the scale in the config so it matches your design, and delete the tiers you never use. Mobile-first CSS: the media queries to write Mobile-first means your base styles need no media query at all. Every query then adds capability as space becomes available. Less code, fewer overrides, easier debugging. Declare the scale once with custom properties /* tokens.css */ :root { –bp-sm: 30em; /* 480px */ –bp-md: 48em; /* 768px */ –bp-lg: 64em; /* 1024px */ –bp-xl: 80em; /* 1280px */ –bp-2xl: 100em; /* 1600px */ } /* Custom media queries via PostCSS, if your build supports it */ @custom-media –md (width >= 48em); @custom-media –lg (width >= 64em); Use the modern range syntax Range syntax is supported in every current browser and reads like the intent behind it. No more max-width: 767.98px hacks. /* Old */ @media (min-width: 768px) and (max-width: 1023.98px) { … } /* 2026 */ @media (48em <= width < 64em) { … } A realistic mobile-first component .card-grid { display: grid; gap: 1rem; grid-template-columns: 1fr; } @media (width >= 30em) { .card-grid { grid-template-columns: repeat(2, 1fr); } } @media (width >= 64em) { .card-grid { grid-template-columns: repeat(3, 1fr); gap: 1.5rem; } } @media (width >= 100em) { .card-grid { grid-template-columns: repeat(4, 1fr); } } Write fewer breakpoints with intrinsic layout Before adding a query, ask whether CSS can solve it without one. These three patterns remove most breakpoints from a typical project: /* 1. Auto-responsive grid, zero media queries */ .auto-grid { display: grid; gap: 1.5rem; grid-template-columns: repeat(auto-fit, minmax(min(18rem, 100%), 1fr)); } /* 2. Fluid type between two breakpoints */ h1 { font-size: clamp(2rem, 1.2rem + 3.2vw, 4rem); } /* 3. Fluid spacing and a capped container */ .container { width: min(100% – 2rem, 75rem); margin-inline: auto; } Rule of thumb: a breakpoint should change the structure of a layout. Anything that only changes a size or spacing value is usually a job for clamp() or minmax(). How to find your own content-driven breakpoints Here is the exact procedure we run on every new interface. It takes about twenty minutes per page template. Build the page at 320px wide with no media queries at all. This is your baseline and it must be usable. Open DevTools responsive mode and drag the handle slowly to the right. Watch for the first point of failure: a line of text longer than about 75 characters, a card so wide it looks empty, a nav with a huge gap, an image growing past its useful size. Note the width where it fails. That number is your breakpoint, not 768. Round it to the nearest value on a sane scale (480, 640, 768, 1024, 1280, 1600) so your codebase stays consistent. Add the query, fix

Responsive Design Breakpoints: Which Values to Use and Why in 2026 Read More »

SwiftUI vs UIKit in 2026: Which to Use for a New iOS Project

Every new iOS project starts with the same fork in the road: SwiftUI vs UIKit. Most articles answer with “SwiftUI is the future” and stop there. That is true, but it is not a decision. A decision needs constraints: your minimum deployment target, your animation requirements, the SDKs you are forced to integrate, and the people who will maintain the code in three years. This guide is written for the person who has to sign off on the architecture, not for someone choosing a tutorial. Here is the short version, then the reasoning behind it. The short answer (2026 edition) Default to SwiftUI for any new app that can target iOS 17 or later. It is the fastest path to a shipping product and it is where Apple invests every single year. Keep UIKit in your toolbox, not as the foundation but as an escape hatch. You will need it, and that is fine. Go UIKit-first only if you fall into one of a small number of categories: very low deployment targets, heavy custom drawing and timeline editing, deeply interruptible custom transitions, or an existing codebase with hundreds of screens. The realistic answer for most teams is “both”, with SwiftUI as the default layer and UIKit wrapped behind representable types. SwiftUI vs UIKit at a glance Criterion SwiftUI UIKit Paradigm Declarative, state driven Imperative, event driven Speed to first screen Very fast Slower, more boilerplate Layout model Parent proposes, child chooses Auto Layout constraints and frames Fine grained control Good, with occasional walls Total Backward compatibility Tied to OS version, API gaps below iOS 17 Stable back to very old targets Third party SDK support Improving, many still UIKit under the hood Universal Hiring pool Large and growing, skewed junior to mid Smaller, skewed senior Apple platform reach iOS, iPadOS, macOS, watchOS, tvOS, visionOS, widgets iOS, iPadOS, tvOS (AppKit on macOS) Debuggability of layout Harder, opaque view tree Mature tooling, view hierarchy debugger 1. Layout systems: the real difference nobody explains People describe SwiftUI as “a prettier way to write UIKit code”. That is misleading. The layout engines work on opposite principles, and this is where teams get hurt when they migrate mentally without migrating conceptually. UIKit: you place things Auto Layout is a constraint solver. You describe relationships, the engine resolves a single valid solution, and you can inspect the result at any time. If two constraints conflict, the console tells you exactly which ones. You can always ask a view “what is your frame right now” and get an answer. For the wider picture, see Use SwiftUI with AppKit and UIKit. The cost is verbosity, constraint spaghetti in long-lived screens, and the eternal risk of a broken layout that only appears on one device size. SwiftUI: the parent proposes, the child decides There is no constraint solver. A parent proposes a size, the child returns the size it actually wants, and the parent positions it. That is the entire model. It makes 90% of layouts trivial and makes the remaining 10% feel like magic tricks you have to learn one by one: fixedSize, layoutPriority, GeometryReader, custom Layout conformances, and alignment guides. Practical takeaway: if your designs are made of stacks, lists, forms, cards and adaptive grids, SwiftUI will cut your layout code by half or more. If your designs are made of overlapping, pixel anchored, measurement dependent compositions (audio waveforms, timelines, seating charts, canvas editors), UIKit or a custom Layout will save you pain. The topic gets a thorough treatment elsewhere. 2. Animation and gesture control This is the section where UIKit veterans dig in, and they have a point, although a smaller one than in 2022. What SwiftUI does better State driven animation. Change a value inside withAnimation and everything that depends on it animates. No manual teardown. Transitions and matched geometry. matchedGeometryEffect and the newer zoom navigation transitions give you hero animations in a handful of lines. Spring physics by default, with interruptible, velocity preserving behaviour that used to require serious UIKit work. Phase and keyframe animators for multi stage sequences without nested completion blocks. What UIKit still does better Direct manipulation at high frequency. In UIKit you can mutate a layer transform on every gesture callback with zero indirection. SwiftUI routes everything through state and a re-evaluation of body, which is fast in recent releases but is still an extra layer between finger and pixel. Fully custom, interruptible navigation transitions with percent driven interaction. SwiftUI has improved a lot here but UIKit still gives you the complete control surface. Core Animation access. Anything involving CAEmitterLayer, custom CALayer subclasses, layer masks driven per frame, or CADisplayLink synchronised drawing is simply more natural in UIKit. Note that this is not an all or nothing choice. A single screen can be SwiftUI while a gesture heavy canvas inside it is a UIViewRepresentable. 3. Backward compatibility: the constraint that decides for you SwiftUI is bundled with the OS, so your minimum deployment target defines which SwiftUI you actually get. This is the single most decisive factor in the SwiftUI vs UIKit debate, and it is a business question more than a technical one. Minimum target What you get Recommendation iOS 18 and later Modern navigation, Observation, mature scrolling APIs, refined transitions, strong concurrency story SwiftUI first, no hesitation iOS 17 @Observable, scroll position APIs, solid NavigationStack SwiftUI first, expect a few availability checks iOS 16 Workable, but you lose Observation and several scroll and layout refinements SwiftUI is viable, budget for polyfills iOS 15 or lower Missing modern navigation, plenty of behavioural bugs, heavy if #available branching UIKit first, or raise the target With UIKit, an API added in iOS 13 behaves the same on iOS 18 as it did on day one. With SwiftUI, the same code can render differently across OS versions because the framework itself changed. That is the hidden tax of declarative UI, and you pay it in QA time. Rule of thumb: check your own analytics before you argue about this. If under

SwiftUI vs UIKit in 2026: Which to Use for a New iOS Project Read More »

How to Set Up a Node.js Server from Scratch: HTTP Module, Express, and Environment Config

Most tutorials teach you to build a Node.js server from scratch by pasting six lines of Express and calling it a day. You end up with a running process and zero understanding of what is actually happening. This guide takes the opposite route: we start with the native http module, hit its limits on purpose, and only then bring in Express 5 so you can see exactly what the framework abstracts away. By the end you will have a working API, a clean environment configuration layer, auto-restart during development, and a folder structure you can actually deploy. The mental model: what a Node.js server really is Before writing a single line of code, internalise this: a Node.js server is a long-running process that keeps a TCP socket open on a port and runs a callback every time bytes arrive on it. That is the whole idea. Three consequences follow, and they explain 90% of the confusion beginners have: The process does not exit. A normal Node script runs and terminates. A server stays alive because the listening socket keeps the event loop busy. That is why your terminal “hangs” after you start it, and that is correct behaviour. One process, one thread, one event loop. Node handles thousands of concurrent connections not by creating threads, but by never blocking. Any synchronous CPU-heavy work you write freezes every other request. State lives in RAM until you restart. Variables declared at module level are shared across all requests and are wiped on every restart or deploy. Express, Fastify, Koa and friends are not servers. They are request handlers that plug into the same http module you are about to use directly. Prerequisites and version check As of September 2026, use Node.js 24 LTS (Active LTS) for anything you intend to run in production. Node.js 26 is the current release line and becomes LTS in October 2026, so it is fine for experimenting but not yet the default choice for a production API. Check what you have: node -v npm -v If node -v prints something older than v22, upgrade. Everything in this tutorial relies on modern features (ES modules, the global fetch, node –watch, –env-file) that assume a recent runtime. Use nvm or fnm so you can switch versions per project instead of installing Node globally once and suffering for two years. Step 1: Initialise the project Create the folder and generate a package.json: mkdir node-server-scratch cd node-server-scratch npm init -y Now open package.json and add one crucial line: { “name”: “node-server-scratch”, “version”: “1.0.0”, “type”: “module”, “main”: “src/server.js”, “scripts”: { “start”: “node src/server.js” } } “type”: “module” switches the project to ES modules, so you write import instead of require. This is the default style for new Node projects in 2026 and it avoids the mixed-syntax mess you find in older tutorials. Create the source folder: mkdir src touch src/server.js Step 2: Your first server with the native http module No dependencies. Nothing installed. Just Node. Put this in src/server.js: import http from ‘node:http’; const PORT = 3000; const server = http.createServer((req, res) => { res.writeHead(200, { ‘Content-Type’: ‘text/plain; charset=utf-8’ }); res.end(‘Hello from a raw Node.js server’); }); server.listen(PORT, () => { console.log(`Server listening on http://localhost:${PORT}`); }); Run it: npm start Open http://localhost:3000 in a browser, or from a second terminal: curl -i http://localhost:3000 Stop it with Ctrl + C. What each piece does Element Role node:http Built-in module. The node: prefix makes it explicit that this is a core module, not an npm package with the same name. createServer(cb) Creates the server object and registers the callback fired on every incoming request. req A readable stream carrying method, URL, headers and body. res A writable stream. Nothing is sent to the client until you write to it, and the connection stays open until res.end(). listen(PORT) Binds the socket. This is the line that turns a script into a server process. Notice what is missing: there is no routing. Every URL, every HTTP method, every path returns the same plain text. That is the honest baseline. Step 3: Add routing by hand Let’s build a tiny API with the raw module: a health endpoint, a users endpoint that accepts JSON, and a proper 404. import http from ‘node:http’; const PORT = 3000; const server = http.createServer((req, res) => { const url = new URL(req.url, `http://${req.headers.host}`); const json = (status, payload) => { res.writeHead(status, { ‘Content-Type’: ‘application/json’ }); res.end(JSON.stringify(payload)); }; if (req.method === ‘GET’ && url.pathname === ‘/api/health’) { return json(200, { status: ‘ok’, uptime: process.uptime() }); } if (req.method === ‘POST’ && url.pathname === ‘/api/users’) { let raw = ”; req.on(‘data’, (chunk) => { raw += chunk; if (raw.length > 1e6) req.destroy(); }); req.on(‘end’, () => { try { const body = JSON.parse(raw); if (!body.name) return json(422, { error: ‘name is required’ }); return json(201, { id: crypto.randomUUID(), name: body.name }); } catch { return json(400, { error: ‘Invalid JSON body’ }); } }); return; } json(404, { error: ‘Not found’, path: url.pathname }); }); server.listen(PORT, () => { console.log(`Server listening on http://localhost:${PORT}`); }); Test the POST route: curl -X POST http://localhost:3000/api/users \ -H “Content-Type: application/json” \ -d ‘{“name”:”Ada”}’ This works. It is also where the pain starts: You are reading the request body chunk by chunk, manually, on every route that needs a body. Route matching is a growing chain of if statements. Add URL parameters like /api/users/42 and you are writing regular expressions. There is no shared logic layer. Want logging, CORS, or auth on 12 routes? Copy and paste 12 times. A thrown error inside a callback crashes the whole process instead of returning a 500. Serving a static file means reading from disk, guessing MIME types and handling stream errors yourself. Every single one of those items is a feature Express gives you. Now you know why it exists instead of just believing it. What Express actually abstracts away Task Native http module Express Routing Manual if / switch on method and pathname app.get(‘/users/:id’, handler) URL parameters

How to Set Up a Node.js Server from Scratch: HTTP Module, Express, and Environment Config Read More »

What Is Database Indexing? How Indexes Work and When to Add Them in PostgreSQL

Most articles explain database indexing with the same book analogy: an index is like the index at the back of a book. That is true, and it is also where most explanations stop. It does not tell you why your query still takes 400 ms after you added an index, why an index on a boolean column does nothing, or why your nightly import got twice as slow after a “quick optimization”. This guide takes a different route. We run the same query on the same PostgreSQL table, first without an index and then with one, and we read the actual EXPLAIN ANALYZE output line by line. Then we look at composite indexes, partial indexes, covering indexes, and the very real cost indexes add to every INSERT, UPDATE and DELETE. What is database indexing? Database indexing is the practice of building an additional, ordered data structure on top of a table so the database engine can locate rows without reading the whole table. The index stores the indexed column values plus a pointer to the physical row location, and it keeps those values sorted (in the case of a B-tree, the default in PostgreSQL). upsun.com makes the same point with more data. Three consequences follow from that single sentence, and they drive every decision in this article: Reads get faster because the engine can jump straight to matching rows instead of scanning millions of them. Writes get slower because every insert, delete and (sometimes) update has to maintain the extra structure. Storage grows because the index is a real object on disk, often 10% to 40% of the table size per index. An index is therefore not a setting you turn on. It is a trade you make, and the only way to know if the trade is worth it is to measure it. Our sample table Everything below was run on PostgreSQL 18 with a synthetic orders table of 5 million rows. You can reproduce it locally in about a minute. CREATE TABLE orders ( id bigserial PRIMARY KEY, customer_id integer NOT NULL, status text NOT NULL, country_code char(2) NOT NULL, total_cents integer NOT NULL, created_at timestamptz NOT NULL ); INSERT INTO orders (customer_id, status, country_code, total_cents, created_at) SELECT (random() * 100000)::int, (ARRAY[‘pending’,’paid’,’shipped’,’cancelled’])[1 + (random() * 3)::int], (ARRAY[‘FR’,’BE’,’CA’,’US’,’DE’])[1 + (random() * 4)::int], (random() * 50000)::int, now() – (random() * interval ‘900 days’) FROM generate_series(1, 5000000); VACUUM ANALYZE orders; The table weighs roughly 450 MB. The only index that exists so far is the one PostgreSQL created automatically for the primary key. Important: the primary key already gives you one index A PRIMARY KEY or a UNIQUE constraint creates a B-tree index behind the scenes. That is why SELECT * FROM orders WHERE id = 4210993 is already instant. Foreign keys, on the other hand, do not create an index on the referencing column, which is one of the most common sources of slow deletes in production. Step 1: the query without an index We want all orders from one customer. Let us ask PostgreSQL what it actually does, with timings and buffer counts. EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM orders WHERE customer_id = 84213; Gather (cost=1000.00..76432.10 rows=49 width=42) (actual time=0.395..212.884 rows=53 loops=1) Workers Planned: 2 Workers Launched: 2 Buffers: shared hit=1088 read=57063 -> Parallel Seq Scan on orders (cost=0.00..75427.20 rows=20 width=42) (actual time=0.121..198.402 rows=18 loops=3) Filter: (customer_id = 84213) Rows Removed by Filter: 1666649 Buffers: shared hit=1088 read=57063 Planning Time: 0.094 ms Execution Time: 212.943 ms Read the important lines: Parallel Seq Scan: PostgreSQL reads the entire table, splitting the work across three processes. There is no shortcut available. Rows Removed by Filter: 1666649 per worker, so roughly 5 million rows examined to return 53. Buffers: shared read=57063: about 445 MB pulled through the buffer cache for 53 rows. Execution Time: 212.943 ms, and that is with a warm cache and two extra CPU workers helping. The ratio here is the whole story of database indexing: we touched 5,000,000 rows to return 53. That is a selectivity of 0.001%. This is exactly the situation an index was designed for. Step 2: the same query with a B-tree index CREATE INDEX idx_orders_customer_id ON orders (customer_id); ANALYZE orders; Same query, same data, same machine: Index Scan using idx_orders_customer_id on orders (cost=0.43..192.31 rows=49 width=42) (actual time=0.041..0.196 rows=53 loops=1) Index Cond: (customer_id = 84213) Buffers: shared hit=53 read=4 Planning Time: 0.158 ms Execution Time: 0.241 ms The difference, side by side: Metric No index With B-tree index Plan node Parallel Seq Scan Index Scan Rows examined ~5,000,000 53 Buffers touched 58,151 57 Execution time 212.9 ms 0.24 ms CPU workers used 3 1 Roughly 880 times faster, and it frees two CPU workers for other sessions. On a busy API endpoint called 200 times per second, that is the difference between a healthy database and a saturated one. What actually happens inside a B-tree index A B-tree (balanced tree) index in PostgreSQL is a set of 8 KB pages organised in levels: The root page holds a small number of separator values and pointers to the level below. Internal pages repeat that pattern, narrowing the search range at each level. Leaf pages hold the actual indexed values in sorted order, each with a TID (tuple identifier: block number plus offset) pointing to the row in the table heap. Leaf pages are linked to their neighbours, which is why range scans such as BETWEEN or ORDER BY are cheap once the entry point is found. A 5 million row B-tree on an integer column is typically only 3 levels deep. Finding a value means reading 3 index pages plus 1 heap page: 4 page reads instead of 58,000. That is the entire magic, and it also explains what indexes are bad at. For the wider picture, see Indexing in Databases. The two things that break the magic Low selectivity. If a value matches 30% of the table, the planner will walk the index and then jump back to the heap hundreds of thousands

What Is Database Indexing? How Indexes Work and When to Add Them in PostgreSQL Read More »

How to Set Up Automated Testing in a React Project: Vitest, React Testing Library, and Playwright

Adding automated testing to a React project is one of those tasks that stays in the backlog for months, mostly because the tooling advice online is fragmented: one article covers Jest, another covers Cypress, and none of them show how the pieces fit together in a real codebase. This tutorial fixes that. In a single afternoon you will bolt a complete, production-grade testing stack onto an existing React app: Vitest for unit tests, React Testing Library for component tests, MSW for API mocking, and Playwright for end-to-end tests, all wired into GitHub Actions with coverage thresholds that actually fail the build. Every snippet below is copy-paste ready. We build two real test suites that mirror what you have in almost every app: a signup form (validation, submission, pending state) and an API-driven list (loading, success, empty, error). The testing stack at a glance Automated testing in a React project works best as layers. Each layer answers a different question, runs at a different speed, and breaks for a different reason. Layer Tool What it verifies Typical speed Share of your suite Static analysis TypeScript + ESLint Types, dead code, bad hooks usage Seconds Always on Unit Vitest Pure functions, reducers, validators, hooks Milliseconds ~50% Component / integration Vitest + React Testing Library + MSW Rendered UI, user interactions, network states Tens of ms ~40% End-to-end Playwright Critical user journeys in a real browser Seconds per test ~10% Why Vitest instead of Jest in 2026 Jest still works and is still everywhere, but if your React app is built with Vite (the default for most new projects since Create React App was deprecated), Vitest is the lower-friction choice. Criterion Vitest Jest Config Reuses your existing vite.config.ts (aliases, env, plugins) Separate config plus a transform (babel-jest, ts-jest or SWC) TypeScript and ESM Native Workable, but ESM still needs care Watch mode speed Very fast, module-graph aware Good, slower cold start API compatibility Jest-compatible (describe, it, expect, mocks) The reference API Browser-mode component tests Built in (real browser, no jsdom) Not available Migrating an existing Jest suite? Most files run unchanged once you replace jest.fn() with vi.fn() and jest.mock() with vi.mock(). Keep Jest if you are on Next.js with a heavy Babel setup and you have no pain today; the rest of this guide still applies almost line for line, since React Testing Library, MSW and Playwright are runner-agnostic. reactjs.org makes the same point with more data. Prerequisites An existing React 19 app scaffolded with Vite (TypeScript recommended) Node.js 22 LTS or newer A package manager: npm, pnpm or yarn (commands below use npm) Roughly 3 hours of uninterrupted time Step 1: Install the unit and component testing layer npm install -D vitest @vitest/coverage-v8 jsdom \ @testing-library/react @testing-library/dom @testing-library/user-event \ @testing-library/jest-dom msw What each package does: vitest: the test runner and assertion library @vitest/coverage-v8: coverage reporting via the V8 engine jsdom: a DOM implementation so components can render in Node @testing-library/react: render components and query them the way a user sees them @testing-library/user-event: realistic typing, clicking, tabbing and pasting @testing-library/jest-dom: DOM matchers such as toBeVisible() and toHaveAccessibleName() msw: intercepts network requests at the HTTP layer instead of mocking fetch Step 2: Configure Vitest Import defineConfig from vitest/config so the test key is typed. Note the exclude entry: without it, Vitest will try to run your Playwright specs and fail. // vite.config.ts import { defineConfig } from ‘vitest/config’ import react from ‘@vitejs/plugin-react’ export default defineConfig({ plugins: [react()], test: { globals: true, environment: ‘jsdom’, setupFiles: ‘./src/test/setup.ts’, css: true, include: [‘src/**/*.{test,spec}.{ts,tsx}’], exclude: [‘**/node_modules/**’, ‘**/dist/**’, ‘**/e2e/**’], clearMocks: true, restoreMocks: true, coverage: { provider: ‘v8’, reporter: [‘text’, ‘html’, ‘lcov’], include: [‘src/**/*.{ts,tsx}’], exclude: [ ‘src/**/*.{test,spec}.{ts,tsx}’, ‘src/test/**’, ‘src/main.tsx’, ‘src/**/*.d.ts’, ], thresholds: { lines: 80, functions: 80, branches: 70, statements: 80, }, }, }, }) The setup file This single file registers the DOM matchers, cleans the DOM between tests, and starts the MSW server for the whole suite. // src/test/setup.ts import ‘@testing-library/jest-dom/vitest’ import { cleanup } from ‘@testing-library/react’ import { afterAll, afterEach, beforeAll } from ‘vitest’ import { server } from ‘./msw/server’ beforeAll(() => server.listen({ onUnhandledRequest: ‘error’ })) afterEach(() => { cleanup() server.resetHandlers() }) afterAll(() => server.close()) Important: onUnhandledRequest: ‘error’ is what turns MSW into a safety net. If a component starts calling an endpoint nobody mocked, the test fails loudly instead of silently hanging. Mock handlers and MSW server // src/test/msw/handlers.ts import { http, HttpResponse } from ‘msw’ export const handlers = [ http.get(‘/api/users’, () => HttpResponse.json([ { id: 1, name: ‘Ada Lovelace’, email: ‘[email protected]’ }, { id: 2, name: ‘Alan Turing’, email: ‘[email protected]’ }, ]), ), http.post(‘/api/signup’, () => HttpResponse.json({ id: 42 }, { status: 201 }), ), ] // src/test/msw/server.ts import { setupServer } from ‘msw/node’ import { handlers } from ‘./handlers’ export const server = setupServer(…handlers) Add the scripts // package.json (excerpt) { “scripts”: { “dev”: “vite”, “build”: “tsc -b && vite build”, “preview”: “vite preview”, “lint”: “eslint .”, “test”: “vitest”, “test:run”: “vitest run”, “test:coverage”: “vitest run –coverage”, “test:e2e”: “playwright test”, “test:e2e:ui”: “playwright test –ui”, “test:all”: “npm run test:run && npm run test:e2e” } } Run npm test now. Vitest should start in watch mode and report that no tests were found. That is your green light. Step 3: Component test number one, the signup form Forms are where most regressions hide: validation rules, disabled buttons, double submits, error announcements. Here is the component under test. // src/components/SignupForm.tsx import { useState, type FormEvent } from ‘react’ type Values = { email: string; password: string } type Props = { onSubmit: (values: Values) => Promise<void> | void } type Errors = { email?: string; password?: string } export function SignupForm({ onSubmit }: Props) { const [email, setEmail] = useState(”) const [password, setPassword] = useState(”) const [errors, setErrors] = useState<Errors>({}) const [pending, setPending] = useState(false) async function handleSubmit(event: FormEvent<HTMLFormElement>) { event.preventDefault() const next: Errors = {} const cleanEmail = email.trim() if (!/^\S+@\S+\.\S+$/.test(cleanEmail)) next.email = ‘Enter a valid email address’ if (password.length < 8) next.password = ‘Password must be at least 8 characters’ setErrors(next) if (Object.keys(next).length > 0)

How to Set Up Automated Testing in a React Project: Vitest, React Testing Library, and Playwright Read More »