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

推荐订阅源

小众软件
小众软件
C
Check Point Blog
Vercel News
Vercel News
Y
Y Combinator Blog
G
Google Developers Blog
P
Proofpoint News Feed
WordPress大学
WordPress大学
MongoDB | Blog
MongoDB | Blog
博客园 - 司徒正美
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
L
LangChain Blog
V
V2EX
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
大猫的无限游戏
大猫的无限游戏
D
DataBreaches.Net
博客园_首页
B
Blog RSS Feed
The Cloudflare Blog
MyScale Blog
MyScale Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Microsoft Security Blog
Microsoft Security Blog

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
Cómo solucionar el error \"Text content does not match se...
Erick Eduardo Ramos · 2026-06-02 · via DEV Community

Erick Eduardo Ramos

Cómo solucionar el error "Text content does not match server-rendered HTML" en Next.js

Este error ocurre cuando el HTML generado en el servidor (SSR) no coincide con el árbol de React que se construye durante la hidratación inicial en el navegador. Es un problema crítico que rompe la experiencia de usuario y puede causar comportamientos impredecibles.

Causa raíz

En tu caso, el error está relacionado con contenido dinámico que varía entre renderizado del servidor y renderizado del cliente, probablemente por:

  • Uso de Date() o new Date() en el renderizado (ej. fechas de eventos como JUN 9, JUN 11, etc.)
  • Uso de typeof window !== 'undefined' o APIs del navegador directamente en el render
  • Metaetiquetas o scripts que modifican el DOM antes de la hidratación (como iOS detectando fechas como enlaces)
  • Configuración incorrecta de librerías CSS-in-JS o Edge/CDN que modifiquen el HTML

Solución definitiva (pasos)

✅ Paso 1: Aisla el contenido dinámico con suppressHydrationWarning

Si el contenido que varía es intencional (como fechas de eventos), envuelve solo el elemento problemático con suppressHydrationWarning={true}:

// app/page.tsx o app/events/page.tsx
export default function EventsPage() {
  const events = [
    { name: 'NEXT.JS NIGHTS', date: new Date('2024-06-09') },
    { name: 'AMS', date: new Date('2024-06-11') },
    { name: 'LDN', date: new Date('2024-06-18') },
  ];

  return (
    <div>
      <h2>VIEW EVENTS</h2>
      <ul>
        {events.map((event, i) => (
          <li key={i}>
            <strong>{event.name}</strong>
            {/* ✅ Solo este elemento usa suppressHydrationWarning */}
            <time 
              dateTime={event.date.toISOString()} 
              suppressHydrationWarning
            >
              {event.date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}
            </time>
          </li>
        ))}
      </ul>
    </div>
  );
}

⚠️ Importante: suppressHydrationWarning solo funciona en el elemento inmediato, no en hijos. Usa span, time, div, etc., no en contenedores grandes.


✅ Paso 2: Evita Date() en el render (si no usas suppressHydrationWarning)

Si prefieres evitar suppressHydrationWarning, genera las fechas en el cliente solo:

// app/page.tsx
'use client';

import { useState, useEffect } from 'react';

export default function EventsPage() {
  const [events, setEvents] = useState<{ name: string; dateStr: string }[]>([]);

  useEffect(() => {
    const now = new Date();
    setEvents([
      { name: 'NEXT.JS NIGHTS', dateStr: 'JUN 9' },
      { name: 'AMS', dateStr: 'JUN 11' },
      { name: 'LDN', dateStr: 'JUN 18' },
    ]);
  }, []);

  return (
    <div>
      <h2>VIEW EVENTS</h2>
      <ul>
        {events.map((event, i) => (
          <li key={i}>
            <strong>{event.name}</strong> <span>{event.dateStr}</span>
          </li>
        ))}
      </ul>
    </div>
  );
}

🔥 Clave: Usa 'use client' y useState/useEffect para evitar que el servidor intente renderizar contenido dinámico.


✅ Paso 3: Deshabilita detección automática de iOS (si aplica)

Agrega esta metaetiqueta en app/layout.tsx para evitar que iOS convierta fechas en enlaces:

// app/layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <head>
        <meta
          name="format-detection"
          content="telephone=no, date=no, email=no, address=no"
        />
      </head>
      <body>{children}</body>
    </html>
  );
}


✅ Paso 4: Verifica configuraciones de Edge/CDN

Si usas Cloudflare, Vercel Edge Functions, o CDN:

  • Cloudflare: Deshabilita Auto Minify (HTML) y Rocket Loader.
  • Vercel: Evita middleware que modifique el HTML (como next.config.js con headers que inyecten scripts).
  • Otros: Asegúrate de que no haya HTML rewriting en el path /app.

Pro-tip: Diagnóstico rápido

  1. Reproduce en modo incógnito (para descartar extensiones).
  2. Busca en el DOM el texto exacto que causa el mismatch (ej. "JUN 9").
  3. Usa console.log(window) dentro de useEffect para confirmar que el código no se ejecuta en SSR.
  4. Activa NEXT_TELEMETRY_DEBUG=1 para ver logs detallados de hidratación.

🛠️ Si el error persiste: Usa suppressHydrationWarning en el elemento más específico posible y nunca en <html>, <body> o <div> grandes.


Solución final recomendada: Usa suppressHydrationWarning en el <time> o <span> que muestra la fecha, y asegúrate de que el atributo dateTime sea estático (ISO 8601). Esto garantiza accesibilidad y evita hidratación sin sacrificar UX.