Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.dev

Same-Origin Requests

Overview

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

react-query

If you are using 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. Also make sure that you have your application wrapped in <QueryClientProvider /> with a QueryClient set.

Was this helpful?

Clerk © 2022