Skip to content

Commit beb336d

Browse files
authored
Merge pull request #26 from kahakai/main
Update README
2 parents 1874705 + 4437d00 commit beb336d

File tree

1 file changed

+95
-136
lines changed

1 file changed

+95
-136
lines changed

README.md

+95-136
Original file line numberDiff line numberDiff line change
@@ -6,53 +6,17 @@ Looking for a web alternative? Check out [axios-jwt](https://github.com/jetbridg
66

77
## What does it do?
88

9-
Applies a request interceptor to your axios instance.
9+
Applies a request interceptor to your `axios` instance.
1010

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.
1212
It stores `accessToken` and `refreshToken` in `AsyncStorage` and reads them when needed.
1313

1414
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
1515
refresh and store a new access token is automatically performed before the request proceeds.
1616

1717
## Installation
1818

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)
5620

5721
### 2. Install this library
5822

@@ -70,152 +34,147 @@ yarn add react-native-axios-jwt
7034

7135
## How do I use it?
7236

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.
7842

7943
### Applying the interceptor
8044

8145
```typescript
8246
// api.ts
8347

84-
import { IAuthTokens, TokenRefreshRequest, applyAuthTokenInterceptor } from 'react-native-axios-jwt'
8548
import axios from 'axios'
49+
import {
50+
type AuthTokenInterceptorConfig,
51+
type AuthTokens,
52+
type TokenRefreshRequest,
53+
applyAuthTokenInterceptor,
54+
} from 'react-native-axios-jwt'
8655

8756
const BASE_URL = 'https://api.example.com'
8857

8958
// 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+
})
9162

9263
// 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> => {
9570
// Important! Do NOT use the axios instance that you supplied to applyAuthTokenInterceptor
9671
// 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+
}
9987

100-
return response.data.access_token
88+
const config: AuthTokenInterceptorConfig = {
89+
requestRefresh,
10190
}
10291

10392
// 3. Add interceptor to your axios instance
104-
applyAuthTokenInterceptor(axiosInstance, { requestRefresh })
93+
applyAuthTokenInterceptor(axiosInstance, config)
10594
```
10695

107-
### Login/logout
96+
### Login
10897

10998
```typescript
11099
// login.ts
111100

112-
import { isLoggedIn, setAuthTokens, clearAuthTokens, getAccessToken, getRefreshToken } from 'react-native-axios-jwt'
101+
import { setAuthTokens } from 'react-native-axios-jwt'
102+
113103
import { axiosInstance } from './api'
114104

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 => {
118109
const response = await axiosInstance.post('/auth/login', params)
119110

120-
// save tokens to storage
111+
const {
112+
access_token: accessToken,
113+
refresh_token: refreshToken,
114+
} = response.data
115+
116+
// Save tokens to AsyncStorage.
121117
await setAuthTokens({
122-
accessToken: response.data.access_token,
123-
refreshToken: response.data.refresh_token
118+
accessToken,
119+
refreshToken,
124120
})
125121
}
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))
138122
```
139123

140-
## Configuration
124+
### Usage
141125

142126
```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
183128

184129
import {
185-
isLoggedIn,
186-
setAuthTokens,
187-
clearAuthTokens,
188130
getAccessToken,
189131
getRefreshToken,
132+
isLoggedIn,
190133
} from 'react-native-axios-jwt';
191-
import { axiosInstance } from '../api';
192134

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+
}
197139

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)
203145
}
204146

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()
207150

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)
211152
}
153+
```
154+
155+
### Logout
156+
157+
```typescript
158+
// logout.ts
212159

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'
216161

162+
// 5. Log out by clearing the auth tokens from AsyncStorage.
163+
const logout = async (): void => {
164+
await clearAuthTokens()
165+
}
166+
```
217167

218-
// Now just make all requests using your axiosInstance instance
219-
axiosInstance.get('/api/endpoint/that/requires/login').then(response => { })
168+
## Configuration
220169

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+
})
221176
```
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

Comments
 (0)