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 in the headers of the request to your server, and then make 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 in the headers of the request.

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

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

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

Authenticating the user on the server endpoints

Stack Auth provides two methods for authenticating users on your server endpoints:

  1. JWT Verification: A fast, lightweight approach that validates the user’s token locally without making external requests. While efficient, it provides only essential user information encoded in the JWT.
  2. REST API Verification: Makes a request to Stack Auth’s servers to validate the token and retrieve comprehensive user information. This method provides access to the complete, up-to-date user profile.

Using JWT

1// you need to install the jose library if it's not already installed
2import * as jose from 'jose';
3
4// you can cache this and refresh it with a low frequency
5const jwks = jose.createRemoteJWKSet(new URL("https://api.stack-auth.com/api/v1/projects/<your-project-id>/.well-known/jwks.json"));
6
7const accessToken = 'access token from the headers';
8
9try {
10 const { payload } = await jose.jwtVerify(accessToken, jwks);
11 console.log('Authenticated user with ID:', payload.sub);
12} catch (error) {
13 console.error(error);
14 console.log('Invalid user');
15}

Using the REST API

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 on the Stack Auth dashboard',
5 'x-stack-secret-server-key': 'generated on the Stack Auth dashboard',
6 'x-stack-access-token': 'access token from the headers',
7};
8
9fetch(url, { headers })
10 .then(response => response.json())
11 .then(data => {
12 if (data.id) {
13 console.log('User is authenticated');
14 } else {
15 console.log('User is not authenticated');
16 }
17 });