Add ApolloLink to inject auth headers

This commit is contained in:
Ivan Malison 2024-02-03 18:10:58 -07:00
parent 473d79a32d
commit e69f9dc2d8
2 changed files with 45 additions and 4 deletions

View File

@ -1,5 +1,8 @@
root = true
[*.tsx]
indent_style = tab
[*.json]
end_of_line = lf
charset = utf-8

View File

@ -1,6 +1,7 @@
import React, { ReactNode } from "react";
import React, { ReactNode, createContext, useContext, useState } from "react";
import {
ApolloClient,
ApolloLink,
InMemoryCache,
ApolloProvider,
HttpLink,
@ -12,16 +13,53 @@ type Props = {
children: ReactNode;
};
const AuthHeaderContext = createContext();
export const AuthHeaderProvider = ({ children }) => {
const [authHeader, setAuthHeader] = useState({ key: "", value: "" });
return (
<AuthHeaderContext.Provider value={{ authHeader, setAuthHeader }}>
{children}
</AuthHeaderContext.Provider>
);
};
// Hook to use the auth header context
export const useAuthHeader = () => useContext(AuthHeaderContext);
const ClientProvider: React.FC<Props> = ({ 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 <ApolloProvider client={client}>{children}</ApolloProvider>;
};