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

推荐订阅源

Security Latest
Security Latest
D
DataBreaches.Net
The Register - Security
The Register - Security
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
F
Full Disclosure
Engineering at Meta
Engineering at Meta
The GitHub Blog
The GitHub Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Proofpoint News Feed
D
Docker
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
G
Google Developers Blog
I
InfoQ
H
Help Net Security
MongoDB | Blog
MongoDB | Blog
Recent Announcements
Recent Announcements
L
Lohrmann on Cybersecurity
T
The Exploit Database - CXSecurity.com
Recorded Future
Recorded Future
G
GRAHAM CLULEY
Microsoft Security Blog
Microsoft Security Blog
WordPress大学
WordPress大学
L
LINUX DO - 热门话题
阮一峰的网络日志
阮一峰的网络日志
The Cloudflare Blog
Help Net Security
Help Net Security
雷峰网
雷峰网
W
WeLiveSecurity
GbyAI
GbyAI
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
T
Tailwind CSS Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
V
Vulnerabilities – Threatpost
V
V2EX
Application and Cybersecurity Blog
Application and Cybersecurity Blog
M
MIT News - Artificial intelligence
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
Last Week in AI
Last Week in AI
Hugging Face - Blog
Hugging Face - Blog
Cisco Talos Blog
Cisco Talos Blog
Webroot Blog
Webroot Blog
AI
AI
S
Security @ Cisco Blogs
Jina AI
Jina AI
The Last Watchdog
The Last Watchdog
Google DeepMind News
Google DeepMind News

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
How to Fix Core Web Vitals in a MERN Stack App (Complete Guide)
Amar Kumar · 2026-05-31 · via DEV Community

Why Most MERN Apps Fail Core Web Vitals

You built a beautiful React app. It works perfectly on your machine. You push it live, run Lighthouse, and see this:

  • LCP: 4.8s ❌
  • CLS: 0.32 ❌
  • INP: 380ms ❌

Sound familiar?

The problem isn't your code quality — it's that MERN apps have unique performance challenges that generic tutorials don't cover:

  1. JavaScript-heavy React bundles slow down First Contentful Paint
  2. MongoDB queries with no indexing destroy Time to First Byte (TTFB)
  3. Unoptimized images blow up Largest Contentful Paint (LCP)
  4. Dynamic content injections cause Cumulative Layout Shift (CLS)

In this guide, I'll walk through real fixes with actual code — the same approach we use at Kraviona when optimizing client MERN apps for Technical SEO.


Understanding the 3 Core Web Vitals

Before fixing, let's understand what Google actually measures:

Metric What It Measures Good Score
LCP (Largest Contentful Paint) How fast the main content loads < 2.5s
INP (Interaction to Next Paint) How fast the page responds to clicks < 200ms
CLS (Cumulative Layout Shift) How much layout jumps around < 0.1

Fix #1 — Reduce LCP with Code Splitting

The biggest React mistake: shipping one giant JavaScript bundle.

❌ Bad (Default Setup)

// App.jsx — Everything loads at once
import Dashboard from './pages/Dashboard';
import Analytics from './pages/Analytics';
import Settings from './pages/Settings';
import Reports from './pages/Reports';

function App() {
  return (
    <Router>
      <Route path="/dashboard" element={<Dashboard />} />
      <Route path="/analytics" element={<Analytics />} />
      <Route path="/settings" element={<Settings />} />
      <Route path="/reports" element={<Reports />} />
    </Router>
  );
}

Enter fullscreen mode Exit fullscreen mode

This loads ALL pages even when user visits only /dashboard. Bundle size = 800KB+.

✅ Fix — React Lazy + Suspense

// App.jsx — Load only what's needed
import { lazy, Suspense } from 'react';

const Dashboard = lazy(() => import('./pages/Dashboard'));
const Analytics = lazy(() => import('./pages/Analytics'));
const Settings = lazy(() => import('./pages/Settings'));
const Reports = lazy(() => import('./pages/Reports'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div className="skeleton-loader" />}>
        <Route path="/dashboard" element={<Dashboard />} />
        <Route path="/analytics" element={<Analytics />} />
        <Route path="/settings" element={<Settings />} />
        <Route path="/reports" element={<Reports />} />
      </Suspense>
    </Router>
  );
}

Enter fullscreen mode Exit fullscreen mode

Result: Initial bundle drops from 800KB → ~120KB. LCP improves by 1.5–2s easily.


Fix #2 — Fix TTFB from Node.js/Express

LCP also depends on how fast your server responds. Slow MongoDB queries = slow TTFB = bad LCP.

❌ Bad — No Indexes, No Caching

// routes/products.js
router.get('/products', async (req, res) => {
  const products = await Product.find({ category: req.query.category });
  res.json(products);
});

Enter fullscreen mode Exit fullscreen mode

Every request hits MongoDB with a full collection scan. With 50K documents = 800ms+ response.

✅ Fix — Add Indexes + Redis Cache

// models/Product.js — Add indexes
const productSchema = new Schema({
  name: String,
  category: { type: String, index: true }, // ← Add index
  price: Number,
  createdAt: { type: Date, index: true }
});

// routes/products.js — Add Redis caching
import redis from 'redis';
const client = redis.createClient();

router.get('/products', async (req, res) => {
  const cacheKey = `products:${req.query.category}`;

  // Check cache first
  const cached = await client.get(cacheKey);
  if (cached) {
    return res.json(JSON.parse(cached));
  }

  // Fetch from DB
  const products = await Product.find({ 
    category: req.query.category 
  }).lean(); // .lean() returns plain objects, 2x faster

  // Store in cache for 5 minutes
  await client.setEx(cacheKey, 300, JSON.stringify(products));

  res.json(products);
});

Enter fullscreen mode Exit fullscreen mode

Result: Response time drops from 800ms → 15ms on cached requests. TTFB goes green instantly.


Fix #3 — Fix LCP with Next.js Image Optimization

If you're using Next.js (which I recommend for SEO), never use raw <img> tags.

❌ Bad

<img 
  src="/hero-banner.jpg" 
  alt="Hero Banner"
  style={{ width: '100%' }}
/>

Enter fullscreen mode Exit fullscreen mode

Problems: No lazy loading, no WebP conversion, no size optimization.

✅ Fix — next/image

import Image from 'next/image';

// For above-the-fold images (hero, banners)
<Image
  src="/hero-banner.jpg"
  alt="Hero Banner"
  width={1200}
  height={600}
  priority={true}        // ← Preload this image (critical!)
  quality={85}
  placeholder="blur"     // ← Show blur while loading
  blurDataURL="data:image/jpeg;base64,/9j/4AAQ..."
/>

// For below-the-fold images
<Image
  src="/product.jpg"
  alt="Product"
  width={400}
  height={300}
  loading="lazy"         // ← Default, but explicit is better
/>

Enter fullscreen mode Exit fullscreen mode

Key rule: Add priority={true} only to the hero image visible above the fold. This tells the browser to preload it immediately.

Result: LCP score typically improves by 30–50%.


Fix #4 — Fix CLS (Layout Shift)

CLS happens when elements move after page load. Most common causes in React apps:

Cause 1: Images without dimensions

// ❌ Bad — No dimensions = layout shift when image loads
<img src="/banner.jpg" alt="Banner" />

// ✅ Fix — Always define width/height
<img 
  src="/banner.jpg" 
  alt="Banner"
  width={1200}
  height={400}
  style={{ aspectRatio: '3/1' }}
/>

Enter fullscreen mode Exit fullscreen mode

Cause 2: Dynamic content injection (ads, toasts, banners)

// ❌ Bad — Content jumps when cookie banner appears
function App() {
  const [showBanner, setShowBanner] = useState(false);

  useEffect(() => {
    setShowBanner(true); // This causes layout shift!
  }, []);

  return (
    <div>
      {showBanner && <CookieBanner />}
      <MainContent />
    </div>
  );
}

// ✅ Fix — Reserve space upfront
function App() {
  return (
    <div>
      {/* Always render, just hide/show */}
      <div style={{ minHeight: '60px' }}>
        <CookieBanner />
      </div>
      <MainContent />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Cause 3: Custom fonts causing FOUT

/* In your CSS / globals.css */
@font-face {
  font-family: 'Inter';
  src: url('/fonts/inter.woff2') format('woff2');
  font-display: swap; /* ← Prevents invisible text, reduces CLS */
}

Enter fullscreen mode Exit fullscreen mode

Also add font preloading in your <head>:

<link 
  rel="preload" 
  href="/fonts/inter.woff2" 
  as="font" 
  type="font/woff2" 
  crossorigin
/>

Enter fullscreen mode Exit fullscreen mode


Fix #5 — Improve INP (Interaction to Next Paint)

INP replaced FID in 2024. It measures all interactions, not just the first click.

Common Culprit: Heavy onClick handlers

// ❌ Bad — Blocking the main thread
function SearchBar() {
  const [results, setResults] = useState([]);

  const handleSearch = (query) => {
    // This runs synchronously, blocking UI
    const filtered = hugeDataArray.filter(item => 
      item.name.toLowerCase().includes(query.toLowerCase())
    );
    setResults(filtered);
  };

  return <input onChange={(e) => handleSearch(e.target.value)} />;
}

// ✅ Fix 1 — Debounce the handler
import { useMemo } from 'react';
import debounce from 'lodash/debounce';

function SearchBar() {
  const [results, setResults] = useState([]);

  const handleSearch = useMemo(
    () => debounce((query) => {
      const filtered = hugeDataArray.filter(item =>
        item.name.toLowerCase().includes(query.toLowerCase())
      );
      setResults(filtered);
    }, 300),
    []
  );

  return <input onChange={(e) => handleSearch(e.target.value)} />;
}

// ✅ Fix 2 — Use Web Worker for heavy computation
// searchWorker.js
self.onmessage = ({ data: { query, items } }) => {
  const filtered = items.filter(item =>
    item.name.toLowerCase().includes(query.toLowerCase())
  );
  self.postMessage(filtered);
};

// SearchBar.jsx
const worker = new Worker('/searchWorker.js');
worker.onmessage = ({ data }) => setResults(data);

const handleSearch = (query) => {
  worker.postMessage({ query, items: hugeDataArray });
};

Enter fullscreen mode Exit fullscreen mode


Quick Wins Checklist

Before diving deep into optimization, run through these quick wins first:

  • [ ] Enable Gzip/Brotli compression in Express
  • [ ] Add Cache-Control headers for static assets
  • [ ] Use CDN for images (Cloudflare, Vercel Edge)
  • [ ] Enable HTTP/2 on your server
  • [ ] Remove unused npm packages (npm-check)
  • [ ] Enable tree shaking in Webpack/Vite config
  • [ ] Use React DevTools Profiler to find re-render bottlenecks

Enable Compression in Express (30 seconds)

npm install compression

Enter fullscreen mode Exit fullscreen mode

// server.js
import compression from 'compression';
app.use(compression()); // ← Add before routes

Enter fullscreen mode Exit fullscreen mode

This alone can reduce response size by 60–70%.


How to Measure Your Progress

Use these tools in order:

  1. Google Search Console → Core Web Vitals report (real user data)
  2. PageSpeed Insights → pagespeed.web.dev (lab + field data)
  3. Chrome DevTools → Performance tab (local profiling)
  4. Lighthouse CI → Automated testing in your CI/CD pipeline

Lighthouse CI Setup (GitHub Actions)

# .github/workflows/lighthouse.yml
name: Lighthouse CI
on: [push]

jobs:
  lighthouse:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - name: Run Lighthouse CI
        uses: treosh/lighthouse-ci-action@v10
        with:
          urls: |
            https://your-domain.com
          budgetPath: ./lighthouse-budget.json
          uploadArtifacts: true

Enter fullscreen mode Exit fullscreen mode

// lighthouse-budget.json
{
  "performance": 90,
  "accessibility": 95,
  "best-practices": 90,
  "seo": 95
}

Enter fullscreen mode Exit fullscreen mode

Now every PR automatically checks if your changes hurt performance. ✅


Summary — What to Fix First

Priority Fix Impact Time
🔴 High Code splitting with React.lazy LCP -2s 1 hour
🔴 High MongoDB indexes + Redis cache TTFB -700ms 2 hours
🟡 Medium next/image for all images LCP -30% 1 hour
🟡 Medium Reserve space for dynamic content CLS fix 30 min
🟢 Low Debounce heavy handlers INP fix 30 min
🟢 Low Gzip compression Size -60% 5 min

Final Thoughts

Core Web Vitals aren't just a Google ranking signal — they directly impact user experience, bounce rate, and conversions. A 1-second improvement in LCP can increase conversions by up to 8%.

The fixes above are the exact optimizations we apply when building and auditing MERN Stack applications. Start with code splitting and MongoDB indexing — those two alone will push most apps from failing to passing.

If you're building a production MERN app and want a free Technical SEO audit, feel free to check out what we do at Kraviona Tech Solutions.

Happy optimizing! 🚀


Got questions or found a better approach? Drop it in the comments — always happy to learn from the community.

Tags: #webdev #javascript #react #node #seo #performance