@@ -6,53 +6,17 @@ Looking for a web alternative? Check out [axios-jwt](https://github.com/jetbridg
6
6
7
7
## What does it do?
8
8
9
- Applies a request interceptor to your axios instance.
9
+ Applies a request interceptor to your ` axios ` instance.
10
10
11
- The interceptor automatically adds an access token header (default: ` Authorization ` ) to all requests.
11
+ The interceptor automatically adds a header (default: ` Authorization ` ) with an access token to all requests.
12
12
It stores ` accessToken ` and ` refreshToken ` in ` AsyncStorage ` and reads them when needed.
13
13
14
14
It parses the expiration time of your access token and checks to see if it is expired before every request. If it has expired, a request to
15
15
refresh and store a new access token is automatically performed before the request proceeds.
16
16
17
17
## Installation
18
18
19
- ### 1. Install async-storage
20
-
21
- #### Install package
22
-
23
- With npm:
24
-
25
- ``` bash
26
- npm install @react-native-async-storage/async-storage
27
- ```
28
-
29
- With Yarn:
30
-
31
- ``` bash
32
- yarn add @react-native-async-storage/async-storage
33
- ```
34
-
35
- With Expo CLI:
36
-
37
- ``` bash
38
- expo install @react-native-async-storage/async-storage
39
- ```
40
-
41
- #### Link Android & iOS packages
42
-
43
- - ** React Native 0.60+**
44
-
45
- ``` bash
46
- npx pod-install
47
- ```
48
-
49
- - ** React Native <= 0.59**
50
-
51
- ``` bash
52
- react-native link @react-native-async-storage/async-storage
53
- ```
54
-
55
- Please follow the [ async-storage installation instructions] ( https://react-native-async-storage.github.io/async-storage/docs/install/ ) if you encounter any problems while installing async-storage
19
+ ### 1. Install [ React Native Async Storage] ( https://github.com/react-native-async-storage/async-storage )
56
20
57
21
### 2. Install this library
58
22
@@ -70,152 +34,147 @@ yarn add react-native-axios-jwt
70
34
71
35
## How do I use it?
72
36
73
- 1 . Create an axios instance
74
- 2 . Define a token refresh function
75
- 3 . Configure the interceptor
76
- 4 . Store tokens on login with ` setAuthTokens() `
77
- 5 . Clear tokens on logout with ` clearAuthTokens() `
37
+ 1 . Create an ` axios ` instance.
38
+ 2 . Define a token refresh function.
39
+ 3 . Configure the interceptor.
40
+ 4 . Store tokens on login with ` setAuthTokens ` function.
41
+ 5 . Clear tokens on logout with ` clearAuthTokens ` function.
78
42
79
43
### Applying the interceptor
80
44
81
45
``` typescript
82
46
// api.ts
83
47
84
- import { IAuthTokens , TokenRefreshRequest , applyAuthTokenInterceptor } from ' react-native-axios-jwt'
85
48
import axios from ' axios'
49
+ import {
50
+ type AuthTokenInterceptorConfig ,
51
+ type AuthTokens ,
52
+ type TokenRefreshRequest ,
53
+ applyAuthTokenInterceptor ,
54
+ } from ' react-native-axios-jwt'
86
55
87
56
const BASE_URL = ' https://api.example.com'
88
57
89
58
// 1. Create an axios instance that you wish to apply the interceptor to
90
- export const axiosInstance = axios .create ({ baseURL: BASE_URL })
59
+ export const axiosInstance = axios .create ({
60
+ baseURL: BASE_URL ,
61
+ })
91
62
92
63
// 2. Define token refresh function.
93
- const requestRefresh: TokenRefreshRequest = async (refreshToken : string ): Promise <string > => {
94
-
64
+ // It is an async function that takes a refresh token and returns a promise
65
+ // that resolves in fresh access token and refresh token.
66
+ // You can also return only an access token in a case when a refresh token stays the same.
67
+ const requestRefresh: TokenRefreshRequest = async (
68
+ refreshToken : string ,
69
+ ): Promise <AuthTokens > => {
95
70
// Important! Do NOT use the axios instance that you supplied to applyAuthTokenInterceptor
96
71
// because this will result in an infinite loop when trying to refresh the token.
97
- // Use the global axios client or a different instance
98
- const response = await axios .post (` ${BASE_URL }/auth/refresh_token ` , { token: refreshToken })
72
+ // Use the global axios client or a different instance.
73
+ const response = await axios .post (` ${BASE_URL }/auth/refresh_token ` , {
74
+ token: refreshToken ,
75
+ })
76
+
77
+ const {
78
+ access_token : newAccessToken,
79
+ refresh_token : newRefreshToken,
80
+ } = response .data
81
+
82
+ return {
83
+ accessToken: newAccessToken ,
84
+ refreshToken: newAccessToken ,
85
+ }
86
+ }
99
87
100
- return response .data .access_token
88
+ const config: AuthTokenInterceptorConfig = {
89
+ requestRefresh ,
101
90
}
102
91
103
92
// 3. Add interceptor to your axios instance
104
- applyAuthTokenInterceptor (axiosInstance , { requestRefresh } )
93
+ applyAuthTokenInterceptor (axiosInstance , config )
105
94
```
106
95
107
- ### Login/logout
96
+ ### Login
108
97
109
98
``` typescript
110
99
// login.ts
111
100
112
- import { isLoggedIn , setAuthTokens , clearAuthTokens , getAccessToken , getRefreshToken } from ' react-native-axios-jwt'
101
+ import { setAuthTokens } from ' react-native-axios-jwt'
102
+
113
103
import { axiosInstance } from ' ./api'
114
104
115
- // 4. Log in by POST-ing the email and password and get tokens in return
116
- // and call setAuthTokens with the result.
117
- const login = async (params : ILoginRequest ) => {
105
+ // 4. Log in with POST request with the email and password.
106
+ // Get access token and refresh token in response.
107
+ // Call `setAuthTokens` with the tokens.
108
+ const login = async (params : LoginRequestParams ): void => {
118
109
const response = await axiosInstance .post (' /auth/login' , params )
119
110
120
- // save tokens to storage
111
+ const {
112
+ access_token : accessToken,
113
+ refresh_token : refreshToken,
114
+ } = response .data
115
+
116
+ // Save tokens to AsyncStorage.
121
117
await setAuthTokens ({
122
- accessToken: response . data . access_token ,
123
- refreshToken: response . data . refresh_token
118
+ accessToken ,
119
+ refreshToken ,
124
120
})
125
121
}
126
-
127
- // 5. Log out by clearing the auth tokens from AsyncStorage
128
- const logout = () => clearAuthTokens ()
129
-
130
- // Check if refresh token exists
131
- if (isLoggedIn ()) {
132
- // assume we are logged in because we have a refresh token
133
- }
134
-
135
- // Get access to tokens
136
- const accessToken = getAccessToken ().then (accessToken => console .log (accessToken ))
137
- const refreshToken = getRefreshToken ().then (refreshToken => console .log (refreshToken ))
138
122
```
139
123
140
- ## Configuration
124
+ ### Usage
141
125
142
126
``` typescript
143
- applyAuthTokenInterceptor (axiosInstance , {
144
- requestRefresh , // async function that takes a refreshToken and returns a promise the resolves in a fresh accessToken
145
- header = " Authorization" , // header name
146
- headerPrefix = " Bearer " , // header value prefix
147
- })
148
- ```
149
-
150
- ## Caveats
151
-
152
- - Your backend should allow a few seconds of leeway between when the token expires and when it actually becomes unusable.
153
-
154
- ## Non-TypeScript implementation
155
-
156
- ``` javascript
157
- // api.js
158
-
159
- import { applyAuthTokenInterceptor } from ' react-native-axios-jwt' ;
160
- import axios from ' axios' ;
161
-
162
- const BASE_URL = ' https://api.example.com'
163
-
164
- // 1. Create an axios instance that you wish to apply the interceptor to
165
- export const axiosInstance = axios .create ({ baseURL: BASE_URL })
166
-
167
- // 2. Define token refresh function.
168
- const requestRefresh = async (refresh ) => {
169
- // Notice that this is the global axios instance, not the axiosInstance!
170
- const response = await axios .post (` ${ BASE_URL } /auth/refresh_token` , { refresh })
171
-
172
- return response .data .access_token
173
- };
174
-
175
- // 3. Apply interceptor
176
- // Notice that this uses the axiosInstance instance.
177
- applyAuthTokenInterceptor (axiosInstance, { requestRefresh });
178
- ```
179
- ### Login/logout
180
-
181
- ``` javascript
182
- // login.js
127
+ // usage.ts
183
128
184
129
import {
185
- isLoggedIn ,
186
- setAuthTokens ,
187
- clearAuthTokens ,
188
130
getAccessToken ,
189
131
getRefreshToken ,
132
+ isLoggedIn ,
190
133
} from ' react-native-axios-jwt' ;
191
- import { axiosInstance } from ' ../api' ;
192
134
193
- // 4. Log in by POST-ing the email and password and get tokens in return
194
- // and call setAuthTokens with the result.
195
- const login = async ( params ) => {
196
- const response = await axiosInstance . post ( ' /auth/login ' , params)
135
+ // Check if the user is logged in.
136
+ if ( isLoggedIn ()) {
137
+ // Assume the user is logged in because we have a refresh token stored in AsyncStorage.
138
+ }
197
139
198
- // save tokens to storage
199
- await setAuthTokens ( {
200
- accessToken: response . data . access_token ,
201
- refreshToken : response . data . refresh_token
202
- } )
140
+ // Use access token.
141
+ const doSomethingWithAccessToken = async () : void => {
142
+ const accessToken = await getAccessToken ()
143
+
144
+ console . log ( accessToken )
203
145
}
204
146
205
- // 5. Log out by clearing the auth tokens from AsyncStorage
206
- const logout = () => clearAuthTokens ()
147
+ // Use refresh token.
148
+ const doSomethingWithRefreshToken = async (): void => {
149
+ const refreshToken = await getRefreshToken ()
207
150
208
- // Check if refresh token exists
209
- if (isLoggedIn ()) {
210
- // assume we are logged in because we have a refresh token
151
+ console .log (refreshToken )
211
152
}
153
+ ```
154
+
155
+ ### Logout
156
+
157
+ ``` typescript
158
+ // logout.ts
212
159
213
- // Get access to tokens
214
- const accessToken = getAccessToken ().then (accessToken => console .log (accessToken))
215
- const refreshToken = getRefreshToken ().then (refreshToken => console .log (refreshToken))
160
+ import { clearAuthTokens } from ' react-native-axios-jwt'
216
161
162
+ // 5. Log out by clearing the auth tokens from AsyncStorage.
163
+ const logout = async (): void => {
164
+ await clearAuthTokens ()
165
+ }
166
+ ```
217
167
218
- // Now just make all requests using your axiosInstance instance
219
- axiosInstance .get (' /api/endpoint/that/requires/login' ).then (response => { })
168
+ ## Configuration
220
169
170
+ ``` typescript
171
+ applyAuthTokenInterceptor (axiosInstance , {
172
+ header = ' Authorization' , // header name
173
+ headerPrefix = ' Bearer ' , // header value prefix
174
+ requestRefresh , // async function that resolves in fresh access token (and refresh token)
175
+ })
221
176
```
177
+
178
+ ## Caveats
179
+
180
+ - Your backend should allow a few seconds of leeway between when the token expires and when it actually becomes unusable.
0 commit comments