If your client and server are on different origins (e.g. making an API call to a server on
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/nextjs). Be mindful that
getToken is an async function that returns a Promise which needs to be resolved.
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.
If you are using React Query, it will follow a similar pattern composing the
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.
Using the above guides will make it possible to authenticate requests to the backend from a client and server that are on separate origins.