Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

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.

fetch('/api/foo').then(res => res.json());

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.

import useSWR from 'swr'; import { useAuth } from '@clerk/nextjs'; export default function useClerkSWR(url) { const { getToken } = useAuth(); const fetcher = async (...args) => { return fetch(...args, { headers: { Authorization: `Bearer ${await getToken()}` } }).then(res => res.json()); }; return useSWR(url, fetcher); }
import useSWR from 'swr'; import { useAuth } from '@clerk/nextjs'; export default function useClerkSWR(url: string) { const { getToken } = useAuth(); const fetcher = async (...args: [RequestInfo]) => { return fetch(...args, { headers: { Authorization: `Bearer ${await getToken()}` } }).then(res => res.json()); }; return useSWR(url, fetcher); }

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.

Make sure that you have your application wrapped in <QueryClientProvider /> with a QueryClient set.

import { useQuery } from '@tanstack/react-query'; const { data, error } = useQuery('foo', async () => { const res = await fetch('/api/foo'); if (!res.ok) { throw new Error('Network response error') } return res.json() });

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.

import { useAuth } from '@clerk/nextjs'; export default function useFetch() { const { getToken } = useAuth(); const authenticatedFetch = async (...args) => { return fetch(...args, { headers: { Authorization: `Bearer ${await getToken()}` } }).then(res => res.json()); }; return authenticatedFetch; }

What did you think of this content?

Clerk © 2023