Obake Engineer Blog

Apollo Clientでリクエストヘッダーに認証トークンを付与する方法

2023/04/19

使用バージョン "@apollo/client": "^3.7.12"

書き方

ApolloLinkを使用することで実現できる。

import {
  ApolloClient,
  ApolloLink,
  HttpLink,
  InMemoryCache,
} from "@apollo/client";

// それぞれのリクエストのヘッダーに認証トークンを追加する
// https://www.apollographql.com/docs/react/api/link/introduction#stateless-links
const authLink = new ApolloLink((operation, forward) => {
  operation.setContext(({ headers }) => ({
    headers: {
      authorization: <your access_token>,
      ...headers,
    },
  }));
  return forward(operation);
});

const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql",
});

const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: ApolloLink.from([authLink, httpLink]),
});

エラーが出る場合

TypeError: forward is not a functionError: You are calling concat on a terminating link, which will have no effectなどのエラーが出る場合、ApolloClientのoptionの設定を見直す必要がありそう。

linkのオプションを指定している場合は、uriの指定をHttpLinkを使用したリンクチェーンから設定する必要がある。 公式にも以下のように書いてある。

Note that if you provide a link chain to the ApolloClient constructor, you don't provide the uri option. Instead, you provide your server's URL to your HttpLink.

これはNG

const client = new ApolloClient({
  uri: "http://localhost:4000/graphql"
  cache: new InMemoryCache(),
  link: ApolloLink.from([authLink]),
});

参考

/post-17

Apollo Clientでリクエストヘッダーに認証トークンを付与するときの注意点

obake
Obake Engineer Blog