Next.js 13如何通过next/headers获取带协议的完整Host地址
解决Next.js 13中Apollo Client获取带协议的完整GraphQL API地址问题
方案一:利用反向代理请求头自动识别协议
主流托管平台(如Vercel、Netlify)会在转发请求时添加x-forwarded-proto头,标识当前请求使用的协议(http/https)。本地开发时该头不存在,直接默认使用http即可。
修改后的代码:
import { HttpLink } from "@apollo/client"; import { headers } from "next/headers"; import { NextSSRInMemoryCache, NextSSRApolloClient, } from "@apollo/experimental-nextjs-app-support/ssr"; import { registerApolloClient } from "@apollo/experimental-nextjs-app-support/rsc"; export const { getClient } = registerApolloClient(() => { const headersList = headers(); const host = headersList.get("host"); // 优先读取反向代理传递的协议头,本地默认http const protocol = headersList.get("x-forwarded-proto") || "http"; const uri = `${protocol}://${host}/api/graphql`; return new NextSSRApolloClient({ cache: new NextSSRInMemoryCache(), link: new HttpLink({ uri }), }); });
方案二:通过环境变量手动指定协议
如果需要更可控的协议配置,可以在环境变量中设置协议类型,本地和生产环境分别配置:
- 在项目根目录创建
.env.local文件,添加:
NEXT_PUBLIC_APP_PROTOCOL=http
- 生产环境(如Vercel控制台)设置环境变量:
NEXT_PUBLIC_APP_PROTOCOL=https
- 修改Apollo客户端配置代码:
import { HttpLink } from "@apollo/client"; import { headers } from "next/headers"; import { NextSSRInMemoryCache, NextSSRApolloClient, } from "@apollo/experimental-nextjs-app-support/ssr"; import { registerApolloClient } from "@apollo/experimental-nextjs-app-support/rsc"; export const { getClient } = registerApolloClient(() => { const headersList = headers(); const host = headersList.get("host"); // 读取环境变量中的协议,默认http const protocol = process.env.NEXT_PUBLIC_APP_PROTOCOL || "http"; const uri = `${protocol}://${host}/api/graphql`; return new NextSSRApolloClient({ cache: new NextSSRInMemoryCache(), link: new HttpLink({ uri }), }); });
补充说明
- 若部署在自定义Nginx反向代理环境,需要在Nginx配置中添加
proxy_set_header X-Forwarded-Proto $scheme;,确保x-forwarded-proto头能正确传递到Next.js服务。 - 本地开发时Next.js默认使用http协议,无需额外配置即可正常访问
http://localhost:3000/api/graphql。
内容的提问来源于stack exchange,提问作者Đặng Hoàng Anh Quân
相关产品推荐
相关产品推荐

