Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
1--- 2title: '@urql/exchange-auth' 3order: 10 4--- 5 6# Authentication Exchange 7 8> **Note:** These API docs are deprecated as we now keep TSDocs in all published packages. 9> You can view TSDocs while using these packages in your editor, as long as it supports the 10> TypeScript Language Server. 11> We're planning to replace these API docs with a separate web app soon. 12 13The `@urql/exchange-auth` package contains an addon `authExchange` for `urql` that aims to make it 14easy to implement complex authentication and reauthentication flows as are typically found with JWT 15token based API authentication. 16 17## Installation and Setup 18 19First install `@urql/exchange-auth` alongside `urql`: 20 21```sh 22yarn add @urql/exchange-auth 23# or 24npm install --save @urql/exchange-auth 25``` 26 27You'll then need to add the `authExchange`, that this package exposes to your `Client`. The 28`authExchange` is an asynchronous exchange, so it must be placed in front of all `fetchExchange`s 29but after all other synchronous exchanges, like the `cacheExchange`. 30 31```js 32import { createClient, cacheExchange, fetchExchange } from 'urql'; 33import { authExchange } from '@urql/exchange-auth'; 34 35const client = createClient({ 36 url: 'http://localhost:3000/graphql', 37 exchanges: [ 38 cacheExchange, 39 authExchange(async utils => { 40 return { 41 /* config... */ 42 }; 43 }), 44 fetchExchange, 45 ], 46}); 47``` 48 49The `authExchange` accepts an initialization function. This function is called when your exchange 50and `Client` first start up, and must return an object of options wrapped in a `Promise`, which is 51used to configure how your authentication method works. 52 53You can use this function to first retrieve your authentication state from a kind 54of local storage, or to call your API to validate your authentication state first. 55 56The relevant configuration options, returned to the `authExchange`, then determine 57how the `authExchange` behaves: 58 59- `addAuthToOperation` must be provided to tell `authExchange` how to add authentication information 60 to an operation, e.g. how to add the authentication state to an operation's fetch headers. 61- `willAuthError` may be provided to detect expired tokens or tell whether an operation will likely 62 fail due to an authentication error. 63- `didAuthError` may be provided to let the `authExchange` detect authentication errors from the 64 API on results. 65- `refreshAuth` is called when an authentication error occurs and gives you an opportunity to update 66 your authentication state. Afterwards, the `authExchange` will retry your operation. 67 68[Read more examples in the documentation given here.](../advanced/authentication.md)