Making backend requests

This guide helps you configure AJAX requests so they can be authenticated by your backend.

Request requirements

1. Set __clerk_session_id

Since multiple sessions can be signed in to a single client, your frontend must specify the active session ID when it makes requests to your backend. This ID should be passed through a query string parameter called _clerk_session_id, which our SDKs are configured to read.

To retrieve the active session ID, call the useClerk hook, or use another utility for the Clerk context:

import { useClerk } from '@clerk/clerk-react';
const { session } = useClerk();
const sessionId = session?.id;

2. Include cookies

This is automatic if your frontend and backend have the same origin, but requires additional configuration for cross-origin requests.

In addition to following the examples below, you must configure your backend to respond with a special header for Cross-Origin Resource Sharing (CORS):

Access-Control-Allow-Credentials: true

3. Use HTTPS in production

For production instances, your backend must have SSL configured.

Examples

The examples below assume there is a variable in-scope named sessionId which contains the active session ID.

fetch

The fetch API is automatically included in modern browsers.

Same-origin
Cross-origin
Same-origin
const reqUrl = `/foo?_clerk_session_id=${sessionId}`
const res = await fetch(reqUrl)
Cross-origin
const baseUrl = 'https://backend.yourdomain.com'
const reqUrl = `${baseUrl}foo?_clerk_session_id=${sessionId}`
const res = await fetch(reqUrl, {
credentials: "include", // Include cookies
})

Axios

Axios is a third-party library that provides a more convenient wrapper over XHR. It must be imported before it can be used.

Same-origin
Cross-origin
Same-origin
const reqUrl = `foo?_clerk_session_id=${sessionId}`
const res = await axios.get(reqURL);
Cross-origin
// Create a reusable axios instance
const backend = axios.create({
baseURL: 'https://backend.yourdomain.com',
withCredentials: true, // Include cookies
});
// Make the request
const reqUrl = `/foo?_clerk_session_id=${sessionId}`
const res = await backend.get(reqURL);

XHR

XHR is automatically included in modern browsers, but the API is quite tedious. While we have included the example here for illustrative purposes, we recommend using fetch or Axios instead of XHR directly.

Same-origin
Cross-origin
Same-origin
const reqUrl = `/foo?_clerk_session_id=${sessionId}`
let xhr = new XMLHttpRequest();
xhr.open('GET', reqUrl);
xhr.send();
xhr.onload = function() {
const res = xhr.response
};
xhr.onerror = function() {
alert("Request failed");
};
Cross-origin
const baseUrl = 'https://backend.yourdomain.com'
const reqUrl = `${baseUrl}foo?_clerk_session_id=${sessionId}`
let xhr = new XMLHttpRequest();
xhr.withCredentials = true; // Include cookies
xhr.open('GET', reqUrl);
xhr.send();
xhr.onload = function() {
const res = xhr.response
};
xhr.onerror = function() {
alert("Request failed");
};