Clerk logo

Clerk Docs

Ctrl + K
Go to clerkstage.dev

Cross-Origin Requests

Overview

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 client package (e.g. @clerk/clerk-react, @clerk/nextjs). Be mindful that getToken is an async function that returns a Promise which needs to be resolved.

1
import { useAuth } from '@clerk/nextjs';
2
3
export default function useFetch() {
4
const { getToken } = useAuth();
5
const authenticatedFetch = async (...args) => {
6
return fetch(...args, {
7
headers: { Authorization: `Bearer ${await getToken()}` }
8
}).then(res => res.json());
9
};
10
return authenticatedFetch;
11
}

useSWR hook

If you are using React or Next.js and want to use the useSWR hook, you can create a custom hook with useAuth from Clerk. 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.

1
import useSWR from 'swr';
2
import { useAuth } from '@clerk/nextjs';
3
4
export default function useClerkSWR(url) {
5
const { getToken } = useAuth();
6
const fetcher = async (...args) => {
7
return fetch(...args, {
8
headers: { Authorization: `Bearer ${await getToken()}` }
9
}).then(res => res.json());
10
};
11
return useSWR(url, fetcher);
12
}

react-query

If you are using React Query, it will follow a similar pattern composing the useSession hook.

1
import { useQuery } from 'react-query';
2
import { useAuth } from '@clerk/nextjs';
3
4
export default function useClerkQuery(url) {
5
const { getToken } = useAuth();
6
return useQuery(url, async () => {
7
const res = await fetch(url, {
8
headers: { Authorization: `Bearer ${await getToken()}` }
9
});
10
if (!res.ok) {
11
throw new Error('Network response error')
12
}
13
return res.json()
14
});
15
}

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 assume you have already followed the instructions on setting up ClerkJS and provided it with your Frontend API URL.

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

Conclusion

Using the above guides will make it possible to authenticate requests to the backend from a client and server that are on separate origins.

For information about other ways to authenticate requests, check out our guides on Same-Origin Requests and Backend Requests.

Was this helpful?

Clerk © 2023