You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js客户端组件href不匹配:首页mailto显示undefined问题排查

问题:首页邮箱链接悬停显示mailto:undefined,二级页面正常

我在页脚使用以下EmailLink客户端组件时,首页悬停显示mailto:undefined,浏览器控制台出现警告:

hook.js:608 Warning: Prop href did not match. Server: "mailto:support@myapp.com" Client: "mailto:undefined" Error Component Stack

但二级页面无此问题,该组件用于实现邮箱地址隐藏功能,不清楚为何仅在二级页面正常工作。

组件代码:

"use client";

import { useState } from "react";

export default function EmailLink() {
  const [emailVisible, setEmailVisible] = useState(false);
  const email = process.env.SMTP_USER;
  
  return (
    <a 
      href={`mailto:${email}`} 
      className="hover:text-accent"
      onMouseEnter={() => {console.log('onMouseEnter'); setEmailVisible(true) } }
      onMouseLeave={() =>  {console.log('onMouseLeave'); setEmailVisible(false) } }
    >
      <img 
        src="/email.png" 
        alt={emailVisible ? email : "Email Support"} 
        className="inline-block" 
      />
    </a>
  );
}
解决方案

这个问题的核心是服务端渲染(SSR)与客户端 hydration 阶段环境变量不一致:

  • 服务端渲染时,process.env.SMTP_USER能正确读取到值,生成的href是mailto:support@myapp.com
  • 客户端hydration时,首页因Next.js静态生成(SSG)或增量静态再生(ISR)机制,客户端无法获取到未暴露的环境变量,导致email为undefined,出现不匹配警告

解决步骤:

  1. 将环境变量暴露给客户端
    Next.js中只有前缀为NEXT_PUBLIC_的环境变量会被注入客户端代码。在.env文件中修改变量名:
NEXT_PUBLIC_SMTP_USER=support@myapp.com
  1. 更新组件中的变量引用
    把组件里的process.env.SMTP_USER替换为process.env.NEXT_PUBLIC_SMTP_USER:
const email = process.env.NEXT_PUBLIC_SMTP_USER;
  1. 可选:添加空值兜底
    为避免环境变量未设置的极端情况,可添加默认值:
const email = process.env.NEXT_PUBLIC_SMTP_USER || 'support@myapp.com';

为什么二级页面正常?

二级页面通常是通过next/link做客户端路由跳转,页面在客户端动态渲染时,环境变量已正确加载;而首页是服务端预渲染,hydration阶段客户端未拿到对应环境变量,才出现不匹配问题。

内容的提问来源于stack exchange,提问作者user994165

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 17:45:03