11---
2- title : Context Link
2+ title : SetContextLink
33description : Easily set a context on your operation, which is used by other links further down the chain.
44---
55
6- ## Overview
6+ <DocBlock
7+ canonicalReference = " @apollo/client/link/context!SetContextLink:class"
8+ customOrder = { [" summary" , " remarks" , " example" ]}
9+ />
710
8- The ` setContext ` function accepts a function that returns either an object or a promise, which then returns an object to set the new context of a request. It receives two arguments: the GraphQL request being executed, and the previous context. This link makes it easy to perform the asynchronous lookup of things like authentication tokens and more.
11+ ## Constructor signature
912
10- ``` js
11- import { setContext } from " @apollo/client/link/context" ;
12-
13- const setAuthorizationLink = setContext ((request , previousContext ) => ({
14- headers: { authorization: " 1234" },
15- }));
16-
17- const asyncAuthLink = setContext (
18- (request ) =>
19- new Promise ((success , fail ) => {
20- // do some async lookup here
21- setTimeout (() => {
22- success ({ token: " async found token" });
23- }, 10 );
24- })
25- );
13+ ``` ts
14+ constructor (
15+ setter : SetContextLink .ContextSetter
16+ ): SetContextLink
17+ ```
18+
19+ ## Usage examples
20+
21+ ### Authentication
22+
23+ The most common use case is adding authentication headers to requests:
24+
25+ ``` ts
26+ const authLink = new SetContextLink ((prevContext , operation ) => {
27+ const token = getAuthToken ();
28+
29+ return {
30+ headers: {
31+ ... prevContext .headers ,
32+ authorization: token ? ` Bearer ${token } ` : " " ,
33+ },
34+ };
35+ });
36+ ```
37+
38+ ### Asynchronous token lookup
39+
40+ You can also perform asynchronous operations to fetch tokens or other data:
41+
42+ ``` ts
43+ const asyncAuthLink = new SetContextLink (async (prevContext , operation ) => {
44+ const token = await fetchAuthToken ();
45+
46+ return {
47+ headers: {
48+ ... prevContext .headers ,
49+ authorization: ` Bearer ${token } ` ,
50+ },
51+ };
52+ });
2653```
2754
2855## Caching lookups
@@ -33,19 +60,30 @@ Take for example a user auth token being found, cached, then removed on a 401 re
3360
3461``` js
3562import { ServerError } from " @apollo/client" ;
36- import { setContext } from " @apollo/client/link/context" ;
37- import { ErrorLink } from " @apollo/client/link/error" ;
63+ import { SetContextLink } from " @apollo/client/link/context" ;
64+ import { onError } from " @apollo/client/link/error" ;
3865
3966// cached storage for the user token
4067let token;
41- const withToken = setContext (( ) => {
68+ const withToken = new SetContextLink ( async ( prevContext , operation ) => {
4269 // if you have a cached value, return it immediately
43- if (token) return { token };
70+ if (token) {
71+ return {
72+ headers: {
73+ ... prevContext .headers ,
74+ authorization: ` Bearer ${ token} ` ,
75+ },
76+ };
77+ }
4478
45- return AsyncTokenLookup ().then ((userToken ) => {
46- token = userToken;
47- return { token };
48- });
79+ const userToken = await AsyncTokenLookup ();
80+ token = userToken;
81+ return {
82+ headers: {
83+ ... prevContext .headers ,
84+ authorization: ` Bearer ${ token} ` ,
85+ },
86+ };
4987});
5088
5189const resetToken = new ErrorLink (({ error }) => {
@@ -57,3 +95,25 @@ const resetToken = new ErrorLink(({ error }) => {
5795
5896const authFlowLink = withToken .concat (resetToken);
5997```
98+
99+ ## Types
100+
101+ <FunctionDetails
102+ canonicalReference = " @apollo/client/link/context!SetContextLink.SetContextLinkDocumentationTypes.ContextSetter:function(1)"
103+ headingLevel = { 3 }
104+ result = { false }
105+ displayName = " SetContextLink.ContextSetter"
106+ />
107+
108+ ### ` SetContextLink.SetContextOperation `
109+
110+ <DocBlock canonicalReference = " @apollo/client/link/context!SetContextLink.SetContextOperation:type" />
111+
112+ #### Signature
113+
114+ ``` ts
115+ type SetContextOperation = Omit <
116+ ApolloLink .Operation ,
117+ " getContext" | " setContext"
118+ >;
119+ ```
0 commit comments