惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Troy Hunt's Blog
Blog — PlanetScale
Blog — PlanetScale
Engineering at Meta
Engineering at Meta
F
Full Disclosure
Recorded Future
Recorded Future
The GitHub Blog
The GitHub Blog
Microsoft Security Blog
Microsoft Security Blog
GbyAI
GbyAI
博客园_首页
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Hacker News: Front Page
人人都是产品经理
人人都是产品经理
The Cloudflare Blog
博客园 - 司徒正美
Webroot Blog
Webroot Blog
Google DeepMind News
Google DeepMind News
Help Net Security
Help Net Security
Cloudbric
Cloudbric
PCI Perspectives
PCI Perspectives
有赞技术团队
有赞技术团队
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
量子位
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tailwind CSS Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
P
Proofpoint News Feed
N
News and Events Feed by Topic
罗磊的独立博客
T
Threat Research - Cisco Blogs
Schneier on Security
Schneier on Security
T
Tor Project blog
IT之家
IT之家
M
MIT News - Artificial intelligence
S
Security @ Cisco Blogs
O
OpenAI News
AI
AI
S
Securelist
Simon Willison's Weblog
Simon Willison's Weblog
The Last Watchdog
The Last Watchdog
月光博客
月光博客
Security Archives - TechRepublic
Security Archives - TechRepublic
L
LINUX DO - 热门话题

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Optimizing Next.js App Router for Core Web Vitals — A Practical Guide
Aon infotech · 2026-06-23 · via DEV Community

Core Web Vitals have been a ranking factor for a while, but App Router introduced new patterns that affect how you optimize for them. Some old approaches don't apply. Some new ones are surprisingly easy to miss.

Here's what actually moves the needle for LCP, CLS, and INP in a Next.js App Router application — from lessons building a production app — the same patterns power the free AI image generator high quality output at pixova.io.


The Three Metrics — What Changed in App Router

LCP (Largest Contentful Paint): The largest visible element loading fast. In App Router, Server Components help here because content can start streaming before JavaScript loads. But images are still the most common LCP element and need explicit attention.

CLS (Cumulative Layout Shift): Visual stability — elements not jumping around as the page loads. App Router's streaming model can actually make CLS worse if you're not careful about skeleton sizing.

INP (Interaction to Next Paint): Replaced FID as a metric in 2024. Measures responsiveness to user interactions. React's concurrent rendering in App Router helps here, but heavy Client Components can still block the main thread.


LCP — The Image Problem

The most common LCP failure in Next.js applications: images that load too slowly, or that aren't identified as the LCP element.

Step 1 — Identify your LCP element

Open Chrome DevTools → Performance → record a page load → look for the LCP marker. In most content-heavy pages, it's an image. In App Router applications, it might be a server-rendered text block.

Step 2 — Add priority to your LCP image

// Without priority — image loads lazily (wrong for LCP)
<Image src={heroImage} alt="Hero" width={1200} height={630} />

// With priority — image preloaded immediately (correct for LCP)
<Image 
  src={heroImage} 
  alt="Hero" 
  width={1200} 
  height={630}
  priority  // Only use on above-the-fold LCP images
/>

priority tells Next.js to preload this image and skip lazy loading. Only use it on the single LCP element — adding it to multiple images defeats the purpose.

Step 3 — Preconnect to external image domains

// app/layout.js
export default function RootLayout({ children }) {
  return (
    <html>
      <head>
        <link rel="preconnect" href="https://your-cdn.com" />
        <link rel="dns-prefetch" href="https://your-cdn.com" />
      </head>
      <body>{children}</body>
    </html>
  );
}

This starts the connection to your image CDN before the image request fires, saving DNS lookup and TLS handshake time.

Step 4 — Use proper sizes attribute

// Wrong — browser downloads full-size image for mobile
<Image src={image} alt="" width={1200} height={630} />

// Right — browser downloads appropriate size for viewport
<Image 
  src={image} 
  alt=""
  fill
  sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>

The sizes attribute tells the browser what size the image will be rendered at, letting it download the appropriately sized version instead of always downloading the full-size image.


CLS — The Streaming Problem

App Router's streaming with Suspense is excellent for performance, but introduces a CLS risk: if Suspense boundaries don't have sized fallbacks, content below them shifts when they resolve.

// CLS problem — unsized fallback causes layout shift
<Suspense fallback={<div>Loading...</div>}>
  <UserProfile />
</Suspense>

// CLS fixed — fallback matches expected content size
<Suspense fallback={<UserProfileSkeleton />}>
  <UserProfile />
</Suspense>

// UserProfileSkeleton — must match UserProfile dimensions exactly
function UserProfileSkeleton() {
  return (
    <div className="flex items-center gap-3 p-4">
      <div className="w-10 h-10 rounded-full bg-neutral-200 animate-pulse" />
      <div className="flex flex-col gap-2">
        <div className="h-4 w-32 bg-neutral-200 rounded animate-pulse" />
        <div className="h-3 w-24 bg-neutral-200 rounded animate-pulse" />
      </div>
    </div>
  );
}

The rule: Every Suspense boundary fallback must be dimensionally identical to what it's replacing. Any size difference between fallback and resolved content = CLS.


CLS — Font Loading

Custom fonts are another common CLS source. Text renders in the fallback font, then shifts when the custom font loads.

// app/layout.js
import { Inter } from 'next/font/google';

const inter = Inter({ 
  subsets: ['latin'],
  display: 'swap',     // Show fallback font immediately
  preload: true,       // Preload font files
  // Optional: reduce FOUT with size-adjust
  adjustFontFallback: true,
});

export default function RootLayout({ children }) {
  return (
    <html className={inter.className}>
      <body>{children}</body>
    </html>
  );
}

next/font handles font optimization automatically — it self-hosts Google Fonts, eliminates the network request to Google's servers, and generates size-adjust CSS to reduce the visual shift when the font loads.


INP — Client Component Optimization

INP measures how quickly the page responds to user input. Long tasks on the main thread cause high INP. In App Router, the main culprits:

Heavy Client Components loading too early:

// Loads everything upfront — heavy JS bundle blocks INP
import { HeavyEditor } from '@/components/HeavyEditor';

// Better — loads only when needed
import dynamic from 'next/dynamic';
const HeavyEditor = dynamic(() => import('@/components/HeavyEditor'), {
  loading: () => <EditorSkeleton />,
  ssr: false, // Client-only component
});

Event handlers doing too much synchronously:

// INP problem — blocks main thread for 200ms
function handleClick() {
  const result = heavyComputation(); // Blocks
  setResult(result);
}

// Better — defer non-urgent work
function handleClick() {
  // Immediate UI feedback
  setIsLoading(true);

  // Defer heavy work
  setTimeout(() => {
    const result = heavyComputation();
    setResult(result);
    setIsLoading(false);
  }, 0);
}


Measuring Progress

Don't rely on Lighthouse scores alone — they're simulated and don't reflect real user experience. Use these alongside:

PageSpeed Insights — runs Lighthouse but also shows field data from Chrome UX Report (real users, not simulation).

Google Search Console → Core Web Vitals — actual performance data from your real visitors, segmented by mobile/desktop.

Web Vitals library for in-app measurement:

import { onLCP, onCLS, onINP } from 'web-vitals';

onLCP(metric => sendToAnalytics(metric));
onCLS(metric => sendToAnalytics(metric));
onINP(metric => sendToAnalytics(metric));

Simulate → measure in field → fix → repeat. Lab scores that don't match field data usually mean the simulation is missing something about your real environment.


The Checklist

  • [ ] LCP image has priority prop
  • [ ] LCP image has correct sizes attribute
  • [ ] CDN domain has preconnect link
  • [ ] All Suspense fallbacks match resolved content dimensions
  • [ ] Fonts use next/font (not <link> to Google Fonts)
  • [ ] Heavy Client Components are dynamically imported
  • [ ] Event handlers don't block the main thread
  • [ ] Measuring with field data, not just Lighthouse Most Core Web Vitals improvements come from fixing one or two specific issues, not broad optimization. Identify the actual problem in field data first, then fix that.

Common Mistakes I Made (And Fixed)

Mistake 1: priority on every above-fold image

I added priority to four images thinking "more is better." It broke the preload order — the browser couldn't prioritize when everything claimed priority. Fixed: priority on one LCP image only.

Mistake 2: Suspense fallbacks that were too short

A Suspense boundary with a one-line "Loading..." fallback replaced a card that was 200px tall. The 190px shift when content resolved was catastrophic for CLS. Fixed: skeleton components that exactly match resolved component dimensions.

Mistake 3: Measuring only with Lighthouse

Lighthouse showed a 90 performance score. Real users on mobile 4G were seeing 4+ second LCP. The simulation doesn't model real network conditions accurately. Fixed: monitoring with Search Console field data as the source of truth.

Mistake 4: Importing all icons at component level

// Wrong — imports entire icon library
import * as Icons from 'react-icons/all';

// Right — imports only what's needed
import { FiDownload, FiShare } from 'react-icons/fi';

Tree-shaking requires named imports. Default imports of entire libraries bypass tree-shaking and bloat the bundle significantly.


Real Numbers

After working through this checklist on a production application:

  • LCP improved from 4.2s to 1.8s (mobile, 75th percentile field data)
  • CLS dropped from 0.18 to 0.02 (CLS threshold is 0.1)
  • INP improved from 340ms to 95ms The LCP improvement came entirely from priority + preconnect. The CLS fix was entirely skeleton sizing. The INP improvement was dynamic importing of a heavy client component.

Three fixes, significant results. Core Web Vitals optimization is usually like this — find the specific bottleneck, fix it precisely, measure the improvement.