From e69f9dc2d8a30540a936988b831576c42c6f33dd Mon Sep 17 00:00:00 2001 From: Ivan Malison Date: Sat, 3 Feb 2024 18:10:58 -0700 Subject: [PATCH] Add ApolloLink to inject auth headers --- .editorconfig | 3 +++ graphql/client.tsx | 46 ++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/.editorconfig b/.editorconfig index c4bd5fb..cbaf2ef 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,5 +1,8 @@ root = true +[*.tsx] +indent_style = tab + [*.json] end_of_line = lf charset = utf-8 diff --git a/graphql/client.tsx b/graphql/client.tsx index 6d271a4..2c503ed 100644 --- a/graphql/client.tsx +++ b/graphql/client.tsx @@ -1,6 +1,7 @@ -import React, { ReactNode } from "react"; +import React, { ReactNode, createContext, useContext, useState } from "react"; import { ApolloClient, + ApolloLink, InMemoryCache, ApolloProvider, HttpLink, @@ -12,17 +13,54 @@ type Props = { children: ReactNode; }; +const AuthHeaderContext = createContext(); + +export const AuthHeaderProvider = ({ children }) => { + const [authHeader, setAuthHeader] = useState({ key: "", value: "" }); + + return ( + + {children} + + ); +}; + +// Hook to use the auth header context +export const useAuthHeader = () => useContext(AuthHeaderContext); + const ClientProvider: React.FC = ({ children }) => { const httpLink = new HttpLink({ uri: API_URI, }); const cache = new InMemoryCache({}); - const client = new ApolloClient({ - link: from([httpLink]), - cache: cache, + const { authHeader } = useAuthHeader(); + + const authMiddleware = new ApolloLink((operation, forward) => { + // Retrieve auth key and value from context + const { key, value } = authHeader; + + if (key && value) { + operation.setContext({ + headers: { + [key]: value, + }, + }); + } + + return forward(operation); }); + // We use useMemo to avoid recreating the client on every render + const client = useMemo( + () => + new ApolloClient({ + link: from([authMiddleware, httpLink]), // Chain the middleware with the httpLink + cache: new InMemoryCache(), + }), + [authHeader], + ); + return {children}; };