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

Nuxt3 Apollo查询/突变时仅支持单个认证头的问题

解决Nuxt3+Nuxt Apollo同时传递WooCommerce会话头与JWT认证头的冲突问题

问题核心

你当前的矛盾点在于Nuxt Apollo模块的默认配置和自定义Apollo链接的认证逻辑冲突:

  • 全局apollo配置项会自动生成认证链接,覆盖你自定义的authLink逻辑
  • 同时配置全局认证和自定义链接时,请求头会被相互覆盖,导致只能生效一种认证方式

解决方案

核心思路是完全交由自定义Apollo链接处理所有请求头逻辑,清空nuxt.config.ts中所有自动生成认证头的配置项,避免模块默认逻辑干扰。

步骤1:修改nuxt.config.ts

移除全局authType、authHeader等配置,只保留客户端的基础连接设置:

import { defineNuxtConfig } from 'nuxt/config';

export default defineNuxtConfig({
  // 其他配置...

  apollo: {
    clients: {
      default: {
        httpEndpoint: process.env.PUBLIC_GRAPHQL_URL,
        httpLinkOptions: {
          credentials: 'include'
        }
        // 移除所有auth相关配置,交由自定义插件处理
      }
    }
  }
});

步骤2:调整apollo.js插件

移除冲突的apollo:auth钩子,确保自定义authLink同时传递两个请求头,并且正确处理会话更新:

import {
  createHttpLink,
  ApolloLink,
  from,
  InMemoryCache,
  ApolloClient
} from '@apollo/client/core';
import { setContext } from '@apollo/client/link/context';
import { provideApolloClient } from '@vue/apollo-composable';

export default defineNuxtPlugin((nuxtApp) => {
  const wooJWT = useCookie('woo-jwt');
  const wooSession = useCookie('woo-session', {
    maxAge: 86_400,
    sameSite: 'lax'
  });

  const config = useRuntimeConfig();

  // WordPress后端GraphQL链接
  const httpLink = createHttpLink({
    uri: config.public.graphqlURL
  });

  // 自定义认证头逻辑:同时传递JWT和会话头
  const authLink = setContext((_, { headers }) => {
    const authHeaders = { ...headers };
    
    // 添加JWT认证头(如果存在)
    if (wooJWT.value) {
      authHeaders['authorization'] = `Bearer ${wooJWT.value}`;
    }
    
    // 添加WooCommerce会话头(如果存在)
    if (wooSession.value) {
      authHeaders['woocommerce-session'] = `Session ${wooSession.value}`;
    }

    return { headers: authHeaders };
  });

  // 处理响应中的会话更新
  const afterware = new ApolloLink((operation, forward) =>
    forward(operation).map((response) => {
      const context = operation.getContext();
      const sessionHeader = context.response.headers.get('woocommerce-session');

      if (process.client && sessionHeader) {
        if (sessionHeader !== wooSession.value) {
          wooSession.value = sessionHeader;
        }
      }

      return response;
    })
  );

  // 缓存配置
  const cache = new InMemoryCache();

  // 创建Apollo客户端,链接顺序:认证头 -> 响应处理 -> HTTP链接
  const apolloClient = new ApolloClient({
    link: from([authLink, afterware, httpLink]),
    cache
  });

  provideApolloClient(apolloClient);

  // 移除apollo:auth钩子,避免和自定义authLink冲突
});

关键说明

  • 移除nuxt.config.ts中的全局认证配置后,Nuxt Apollo模块不会自动生成认证链接,完全由你的自定义链接控制请求头
  • authLink中会根据cookie的存在情况,动态添加对应的请求头,不会出现空值覆盖的问题
  • 保留afterware逻辑,确保访客会话更新后能同步到cookie中

这样修改后,访客购物车的会话头和登录用户的JWT认证头就能同时正常传递,两个功能可以并行生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 18:53:13