Skip to Content
Clerk logo

Clerk Docs

Ctrl + K
Go to clerk.com

Cross-origin requests

If your client and server are on different origins (e.g. making an API call to a server on api.foo.com from JavaScript running on a client at foo.com), the session token needs to be passed in a network request header. There are a few different ways this can be done on the front-end.

Using Fetch with React

In order to pass the session token using the browser Fetch API, it should be put inside a Bearer token in the Authorization header. To retrieve the session token, use the getToken method from the useAuth() hook. Be mindful that getToken is an async function that returns a Promise which needs to be resolved.

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; }

useSWR hook

If you are using React or Next.js and want to use the useSWR(opens in a new tab) hook, you can create a custom hook by utilizing Clerk's useAuth() hook. useAuth() returns the asynchronous getToken function that can be called to add the session token as a Bearer token in the Authorization header of requests.

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); }

Tanstack Query (React Query)

If you are using Tanstack Query(opens in a new tab), 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'; import { useAuth } from '@clerk/nextjs'; export default function useClerkQuery(url) { const { getToken } = useAuth(); return useQuery(url, async () => { const res = await fetch(url, { headers: { Authorization: `Bearer ${await getToken()}` } }); if (!res.ok) { throw new Error('Network response error') } return res.json() }); }

Using Fetch with ClerkJS

If you are not using React or Next.js, you can access the getToken method from the session property of the Clerk object. This assumes you have already followed the instructions on setting up ClerkJS and provided it with your Frontend API URL.

(async () => { fetch('/api/foo', { headers: { Authorization: `Bearer ${await Clerk.session.getToken()}` } }).then(res => res.json()); })();

Last updated on September 15, 2023

What did you think of this content?

Clerk © 2024