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

如何在Next.js 14服务端组件中访问window.location.origin?

在Next.js 14服务端组件中获取origin的方法

服务端组件运行在服务器环境,不存在浏览器的window对象,所以无法直接访问window.location.origin。针对Next.js 14,你可以用以下几种方案解决:

  • 通过headers() API获取
    在服务端组件中,调用Next.js提供的headers()函数获取请求头里的host字段,再结合协议拼接出origin:

    import { headers } from 'next/headers';
    
    export default function ServerComponent() {
      const headersList = headers();
      const host = headersList.get('host');
      // 生产环境可根据部署环境调整协议,或通过反向代理头获取
      const protocol = headersList.get('x-forwarded-proto') || 'http';
      const origin = `${protocol}://${host}`;
    
      return <div>Origin: {origin}</div>;
    }
    

    注:部署在Vercel、Netlify等平台时,x-forwarded-proto头会返回当前请求的真实协议(http/https),比直接判断环境更准确。

  • 使用环境变量配置
    如果应用部署地址固定,可在.env文件中直接配置origin:

    NEXT_PUBLIC_APP_ORIGIN=https://your-domain.com
    

    然后在服务端组件中直接读取:

    const origin = process.env.NEXT_PUBLIC_APP_ORIGIN;
    

    这种方式无需依赖请求头,适合部署地址固定的场景。

  • 客户端获取后传递给服务端组件
    若必须从客户端获取origin,可先在客户端组件中拿到window.location.origin,再通过props传递给服务端组件:

    // 客户端组件 ClientComponent.js
    'use client';
    
    import ServerComponent from './ServerComponent';
    
    export default function ClientComponent() {
      const origin = window.location.origin;
      return <ServerComponent origin={origin} />;
    }
    
    // 服务端组件 ServerComponent.js
    export default function ServerComponent({ origin }) {
      return <div>Origin from client: {origin}</div>;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:27:02