}>{content})
137 |
138 | await waitFor(() => expect(screen.getByText(content)).toBeInTheDocument())
139 | })
140 | })
141 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-query-auth
2 |
3 | [](https://www.npmjs.com/package/react-query-auth)
4 |
5 | Authenticate your react applications easily with [React Query](https://tanstack.com/query/v4/docs/react).
6 |
7 | ## Introduction
8 |
9 | Using React Query has allowed us to significantly reduce the size of our codebase by caching server state. However, we still need to consider where to store user data, which is a type of global application state that we need to access from many parts of the app, but is also a server state since it is obtained from a server. This library makes it easy to manage user authentication, and can be adapted to work with any API or authentication method.
10 |
11 | ## Installation
12 |
13 | ```
14 | $ npm install @tanstack/react-query react-query-auth
15 | ```
16 |
17 | Or if you use Yarn:
18 |
19 | ```
20 | $ yarn add @tanstack/react-query react-query-auth
21 | ```
22 |
23 | ## Usage
24 |
25 | To use this library, you will need to provide it with functions for fetching the current user, logging in, registering, and logging out. You can do this using the `configureAuth` function:
26 |
27 | ```ts
28 | import { configureAuth } from 'react-query-auth';
29 |
30 | const { useUser, useLogin, useRegister, useLogout } = configureAuth({
31 | userFn: () => api.get('/me'),
32 | loginFn: (credentials) => api.post('/login', credentials),
33 | registerFn: (credentials) => api.post('/register', credentials),
34 | logoutFn: () => api.post('/logout'),
35 | });
36 | ```
37 |
38 | With these hooks, you can then add authentication functionality to your app. For example, you could use the `useUser` hook to access the authenticated user in a component.
39 |
40 | You can also use the `useLogin`, `useRegister`, and `useLogout` hooks to allow users to authenticate and log out.
41 |
42 | ```tsx
43 | function UserInfo() {
44 | const user = useUser();
45 | const logout = useLogout();
46 |
47 | if (user.isLoading) {
48 | return
Loading ...
;
49 | }
50 |
51 | if (user.error) {
52 | return
{JSON.stringify(user.error, null, 2)}
;
53 | }
54 |
55 | if (!user.data) {
56 | return
Not logged in
;
57 | }
58 |
59 | return (
60 |
61 |
Logged in as {user.data.email}
62 |
65 |
66 | );
67 | }
68 | ```
69 |
70 | The library also provides the `AuthLoader` component that can be used to handle loading states when fetching the authenticated user. You can use it like this:
71 |
72 | ```tsx
73 | function MyApp() {
74 | return (
75 |
Loading ...
}
77 | renderUnauthenticated={() => }
78 | >
79 |
80 |
81 | );
82 | }
83 | ```
84 |
85 | **NOTE: All hooks and components must be used within `QueryClientProvider`.**
86 |
87 | ## API Reference:
88 |
89 | ### `configureAuth`:
90 |
91 | The `configureAuth` function takes in a configuration object and returns a set of custom hooks for handling authentication.
92 |
93 | #### The `configureAuth` configuration object:
94 |
95 | A configuration object that specifies the functions and keys to be used for various authentication actions. It accepts the following properties:
96 |
97 | - **`userFn`:**
98 | A function that is used to retrieve the authenticated user. It should return a Promise that resolves to the user object, or null if the user is not authenticated.
99 |
100 | - **`loginFn`:**
101 | A function that is used to log the user in. It should accept login credentials as its argument and return a Promise that resolves to the user object.
102 |
103 | - **`registerFn`:**
104 | A function that is used to register a new user. It should accept registration credentials as its argument and return a Promise that resolves to the new user object.
105 |
106 | - **`logoutFn`:**
107 | A function that is used to log the user out. It should return a Promise that resolves when the logout action is complete.
108 |
109 | - **`userKey`:**
110 | An optional key that is used to store the authenticated user in the react-query cache. The default value is `['authenticated-user']`.
111 |
112 | #### The `configureAuth` returned object:
113 |
114 | `configureAuth` returns an object with the following properties:
115 |
116 | - **`useUser`:**
117 | A custom hook that retrieves the authenticated user. It is a wrapper around [useQuery](https://tanstack.com/query/v4/docs/react/reference/useQuery) that uses the `userFn` and `userKey` specified in the `configAuth` configuration. The hook accepts the same options as [useQuery](https://tanstack.com/query/v4/docs/react/reference/useQuery), except for `queryKey` and `queryFn`, which are predefined by the configuration.
118 |
119 | - **`useLogin`:**
120 | A custom hook that logs the user in. It is a wrapper around [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation) that uses the `loginFn` specified in the configuration. The hook accepts the same options as [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation), except for `mutationFn`, which is set by the configuration. On success, the hook updates the authenticated user in the React Query cache using the `userKey` specified in the configuration.
121 |
122 | - **`useRegister`:**
123 | A custom hook that registers a new user. It is a wrapper around [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation) that uses the `registerFn` specified in the configuration. The hook accepts the same options as [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation), except for `mutationFn`, which is set by the configuration. On success, the hook updates the authenticated user in the React Query cache using the `userKey` specified in the configuration.
124 |
125 | - **`useLogout`:**
126 | A custom hook that logs the user out. It is a wrapper around [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation) that uses the `logoutFn` specified in the configuration. The hook accepts the same options as [useMutation](https://tanstack.com/query/v4/docs/react/reference/useMutation), except for `mutationFn`, which is set by the configuration. On success, the hook removes the authenticated user from the React Query cache using the `userKey` specified in the configuration.
127 |
128 | - **`AuthLoader`:**
129 |
130 | A component that can be used to handle loading states when fetching the authenticated user. It accepts the following props:
131 |
132 | - **`renderLoading`**:
133 | A function that is called when the authenticated user is being fetched. It should return a React node that is rendered while the user is being fetched.
134 |
135 | - **`renderUnauthenticated`**:
136 | A function that is called when the authenticated user is not authenticated. It should return a React node that is rendered when the user is not authenticated.
137 |
138 | - **`renderError`**:
139 | A function that is called when an error is thrown during the authentication request. It should return a React node that is rendered when the error occurs. It receives the `Error` object which can be used during rendering. Defaults to `(error: Error) => <>{JSON.stringify(error)}>`.
140 |
141 | - **`children`**:
142 | A React node that is rendered when the authenticated user is successfully fetched.
143 |
144 | If you need a more custom loading implementation, you can create your own `AuthLoader` component and use the `useUser` hook to fetch the authenticated user and handle the loading and error states yourself.
145 |
146 |
147 | If none of the provided hooks or components meet your needs, feel free to copy the source code into your project and modify it to your liking.
148 |
149 | ## Examples:
150 |
151 | To try out the library, check out the `examples` folder.
152 |
153 | ## Contributing
154 |
155 | 1. Clone this repo
156 | 2. Create a branch: `git checkout -b your-feature`
157 | 3. Make some changes
158 | 4. Test your changes
159 | 5. Push your branch and open a Pull Request
160 |
161 | ## LICENSE
162 |
163 | [MIT](/LICENSE)
164 |
--------------------------------------------------------------------------------
/examples/vite/public/mockServiceWorker.js:
--------------------------------------------------------------------------------
1 | /* eslint-disable */
2 | /* tslint:disable */
3 |
4 | /**
5 | * Mock Service Worker.
6 | * @see https://github.com/mswjs/msw
7 | * - Please do NOT modify this file.
8 | * - Please do NOT serve this file on production.
9 | */
10 |
11 | const PACKAGE_VERSION = '2.6.8'
12 | const INTEGRITY_CHECKSUM = '00729d72e3b82faf54ca8b9621dbb96f'
13 | const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
14 | const activeClientIds = new Set()
15 |
16 | self.addEventListener('install', function () {
17 | self.skipWaiting()
18 | })
19 |
20 | self.addEventListener('activate', function (event) {
21 | event.waitUntil(self.clients.claim())
22 | })
23 |
24 | self.addEventListener('message', async function (event) {
25 | const clientId = event.source.id
26 |
27 | if (!clientId || !self.clients) {
28 | return
29 | }
30 |
31 | const client = await self.clients.get(clientId)
32 |
33 | if (!client) {
34 | return
35 | }
36 |
37 | const allClients = await self.clients.matchAll({
38 | type: 'window',
39 | })
40 |
41 | switch (event.data) {
42 | case 'KEEPALIVE_REQUEST': {
43 | sendToClient(client, {
44 | type: 'KEEPALIVE_RESPONSE',
45 | })
46 | break
47 | }
48 |
49 | case 'INTEGRITY_CHECK_REQUEST': {
50 | sendToClient(client, {
51 | type: 'INTEGRITY_CHECK_RESPONSE',
52 | payload: {
53 | packageVersion: PACKAGE_VERSION,
54 | checksum: INTEGRITY_CHECKSUM,
55 | },
56 | })
57 | break
58 | }
59 |
60 | case 'MOCK_ACTIVATE': {
61 | activeClientIds.add(clientId)
62 |
63 | sendToClient(client, {
64 | type: 'MOCKING_ENABLED',
65 | payload: {
66 | client: {
67 | id: client.id,
68 | frameType: client.frameType,
69 | },
70 | },
71 | })
72 | break
73 | }
74 |
75 | case 'MOCK_DEACTIVATE': {
76 | activeClientIds.delete(clientId)
77 | break
78 | }
79 |
80 | case 'CLIENT_CLOSED': {
81 | activeClientIds.delete(clientId)
82 |
83 | const remainingClients = allClients.filter((client) => {
84 | return client.id !== clientId
85 | })
86 |
87 | // Unregister itself when there are no more clients
88 | if (remainingClients.length === 0) {
89 | self.registration.unregister()
90 | }
91 |
92 | break
93 | }
94 | }
95 | })
96 |
97 | self.addEventListener('fetch', function (event) {
98 | const { request } = event
99 |
100 | // Bypass navigation requests.
101 | if (request.mode === 'navigate') {
102 | return
103 | }
104 |
105 | // Opening the DevTools triggers the "only-if-cached" request
106 | // that cannot be handled by the worker. Bypass such requests.
107 | if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
108 | return
109 | }
110 |
111 | // Bypass all requests when there are no active clients.
112 | // Prevents the self-unregistered worked from handling requests
113 | // after it's been deleted (still remains active until the next reload).
114 | if (activeClientIds.size === 0) {
115 | return
116 | }
117 |
118 | // Generate unique request ID.
119 | const requestId = crypto.randomUUID()
120 | event.respondWith(handleRequest(event, requestId))
121 | })
122 |
123 | async function handleRequest(event, requestId) {
124 | const client = await resolveMainClient(event)
125 | const response = await getResponse(event, client, requestId)
126 |
127 | // Send back the response clone for the "response:*" life-cycle events.
128 | // Ensure MSW is active and ready to handle the message, otherwise
129 | // this message will pend indefinitely.
130 | if (client && activeClientIds.has(client.id)) {
131 | ;(async function () {
132 | const responseClone = response.clone()
133 |
134 | sendToClient(
135 | client,
136 | {
137 | type: 'RESPONSE',
138 | payload: {
139 | requestId,
140 | isMockedResponse: IS_MOCKED_RESPONSE in response,
141 | type: responseClone.type,
142 | status: responseClone.status,
143 | statusText: responseClone.statusText,
144 | body: responseClone.body,
145 | headers: Object.fromEntries(responseClone.headers.entries()),
146 | },
147 | },
148 | [responseClone.body],
149 | )
150 | })()
151 | }
152 |
153 | return response
154 | }
155 |
156 | // Resolve the main client for the given event.
157 | // Client that issues a request doesn't necessarily equal the client
158 | // that registered the worker. It's with the latter the worker should
159 | // communicate with during the response resolving phase.
160 | async function resolveMainClient(event) {
161 | const client = await self.clients.get(event.clientId)
162 |
163 | if (activeClientIds.has(event.clientId)) {
164 | return client
165 | }
166 |
167 | if (client?.frameType === 'top-level') {
168 | return client
169 | }
170 |
171 | const allClients = await self.clients.matchAll({
172 | type: 'window',
173 | })
174 |
175 | return allClients
176 | .filter((client) => {
177 | // Get only those clients that are currently visible.
178 | return client.visibilityState === 'visible'
179 | })
180 | .find((client) => {
181 | // Find the client ID that's recorded in the
182 | // set of clients that have registered the worker.
183 | return activeClientIds.has(client.id)
184 | })
185 | }
186 |
187 | async function getResponse(event, client, requestId) {
188 | const { request } = event
189 |
190 | // Clone the request because it might've been already used
191 | // (i.e. its body has been read and sent to the client).
192 | const requestClone = request.clone()
193 |
194 | function passthrough() {
195 | // Cast the request headers to a new Headers instance
196 | // so the headers can be manipulated with.
197 | const headers = new Headers(requestClone.headers)
198 |
199 | // Remove the "accept" header value that marked this request as passthrough.
200 | // This prevents request alteration and also keeps it compliant with the
201 | // user-defined CORS policies.
202 | const acceptHeader = headers.get('accept')
203 | if (acceptHeader) {
204 | const values = acceptHeader.split(',').map((value) => value.trim())
205 | const filteredValues = values.filter(
206 | (value) => value !== 'msw/passthrough',
207 | )
208 |
209 | if (filteredValues.length > 0) {
210 | headers.set('accept', filteredValues.join(', '))
211 | } else {
212 | headers.delete('accept')
213 | }
214 | }
215 |
216 | return fetch(requestClone, { headers })
217 | }
218 |
219 | // Bypass mocking when the client is not active.
220 | if (!client) {
221 | return passthrough()
222 | }
223 |
224 | // Bypass initial page load requests (i.e. static assets).
225 | // The absence of the immediate/parent client in the map of the active clients
226 | // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
227 | // and is not ready to handle requests.
228 | if (!activeClientIds.has(client.id)) {
229 | return passthrough()
230 | }
231 |
232 | // Notify the client that a request has been intercepted.
233 | const requestBuffer = await request.arrayBuffer()
234 | const clientMessage = await sendToClient(
235 | client,
236 | {
237 | type: 'REQUEST',
238 | payload: {
239 | id: requestId,
240 | url: request.url,
241 | mode: request.mode,
242 | method: request.method,
243 | headers: Object.fromEntries(request.headers.entries()),
244 | cache: request.cache,
245 | credentials: request.credentials,
246 | destination: request.destination,
247 | integrity: request.integrity,
248 | redirect: request.redirect,
249 | referrer: request.referrer,
250 | referrerPolicy: request.referrerPolicy,
251 | body: requestBuffer,
252 | keepalive: request.keepalive,
253 | },
254 | },
255 | [requestBuffer],
256 | )
257 |
258 | switch (clientMessage.type) {
259 | case 'MOCK_RESPONSE': {
260 | return respondWithMock(clientMessage.data)
261 | }
262 |
263 | case 'PASSTHROUGH': {
264 | return passthrough()
265 | }
266 | }
267 |
268 | return passthrough()
269 | }
270 |
271 | function sendToClient(client, message, transferrables = []) {
272 | return new Promise((resolve, reject) => {
273 | const channel = new MessageChannel()
274 |
275 | channel.port1.onmessage = (event) => {
276 | if (event.data && event.data.error) {
277 | return reject(event.data.error)
278 | }
279 |
280 | resolve(event.data)
281 | }
282 |
283 | client.postMessage(
284 | message,
285 | [channel.port2].concat(transferrables.filter(Boolean)),
286 | )
287 | })
288 | }
289 |
290 | async function respondWithMock(response) {
291 | // Setting response status code to 0 is a no-op.
292 | // However, when responding with a "Response.error()", the produced Response
293 | // instance will have status code set to 0. Since it's not possible to create
294 | // a Response instance with status code 0, handle that use-case separately.
295 | if (response.status === 0) {
296 | return Response.error()
297 | }
298 |
299 | const mockedResponse = new Response(response.body, response)
300 |
301 | Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
302 | value: true,
303 | enumerable: true,
304 | })
305 |
306 | return mockedResponse
307 | }
308 |
--------------------------------------------------------------------------------