Same-origin requests
If your client and server are on the same origin (e.g. making an API call to foo.com/api
from JavaScript running on foo.com
), the session token is automatically passed to the backend in a cookie. This means that all requests to same-origin endpoints are authenticated by default.
Using Fetch
You can use the native browser Fetch API as you normally would and the request will be authenticated.
useSWR hook
If you are using React or Next.js and would like to use the useSWR hook, it’s as simple as supplying the API route with whichever fetcher function you are using. Because of the automatic revalidation feature of SWR, you need to retrieve and set the session token in the Authorization header. Call the asynchronous getToken
method from the useAuth()
hook and add it as a Bearer token.
When you re-focus a page or switch between tabs, SWR automatically revalidates data. This can be useful to immediately synchronize to the latest state in scenarios like stale mobile tabs, or laptops that went to sleep.
Tanstack Query (React Query)
If you are using Tanstack Query, formally known as React Query, in your application, you need to use a query function that throws errors. Since the native Fetch API does not, you can add it in.
Background fetching
For applications that are fetching content in the background, like when a tab is no longer focused, you will need to include an Authorization header along with your request.
Feedback
Last updated on