Backend Integration

Integrate Stack Auth with your own server with the REST APIs

To authenticate your endpoints, you need to send the user’s access token and refresh token in the headers of the request to your server, and then making a request to Stack’s server API to verify the user’s identity.

Sending requests to your server endpoints

To authenticate your own server endpoints using Stack’s server API, you need to protect your endpoints by sending the user’s access token and refresh token in the headers of the request.

On the client side, you can retrieve the access token and refresh token from the user object by calling user.getAuthJson(). This will return an object containing accessToken and refreshToken.

Then, you can call your server endpoint with these two tokens in the headers, like this:

1const { accessToken, refreshToken } = await user.getAuthJson();
2const response = await fetch('/api/users/me', {
3 headers: {
4 'x-stack-access-token': accessToken,
5 'x-stack-refresh-token': refreshToken
6 },
7 // your other options and parameters
8});

Authenticating the user on the server endpoints

On the server side, you can extract the access token and refresh token from the headers of the request and use them to authenticate the user. (more details on the headers here.)

1const url = 'https://api.stack-auth.com/api/v1/users/me';
2const headers = {
3 'x-stack-access-type': 'server',
4 'x-stack-project-id': 'generated from the Stack dashboard',
5 'x-stack-secret-server-key': 'generated from the Stack dashboard',
6 'x-stack-access-token': 'access token from headers',
7 'x-stack-refresh-token': 'refresh token from headers'
8};
9
10fetch(url, { headers })
11 .then(response => response.json())
12 .then(data => {
13 if (data.id) {
14 console.log('User is authenticated');
15 } else {
16 console.log('User is not authenticated');
17 }
18 });