# Code Samples

Copy-pasteable JavaScript (`fetch`, in the browser or Node) for the token
lifecycle. A web app with a backend runs it there, so the tokens stay off
the browser ([Tokens](/documentation/developers/tokens/#browser-apps)).
These samples use the [Quickstart](/documentation/developers/quickstart/)'s
`ISSUER`, `CLIENT_ID` and `discover()`, and a `REDIRECT_URI` registered for
your app. The samples after the backend one pick up from a `code` you
already have.

## On a backend

A server (Node 18 or later, Express-style handlers shown) that keeps
this attempt's `state` and PKCE verifier in the user's session across
the redirect, checks the callback, exchanges the code, and keeps the
tokens in its own datastore:

```js
import { createHash, randomBytes } from 'node:crypto';

const REDIRECT_URI = 'https://your-app.example/pca/callback'; // registered for your app
const CLIENT_SECRET = process.env.PCA_CLIENT_SECRET; // unset for a public client

app.get('/pca/connect', async (req, res) => {
  const verifier = randomBytes(32).toString('base64url');
  const state = randomBytes(16).toString('base64url');
  req.session.pcaAttempt = { state, verifier }; // this attempt only
  const { authorization_endpoint } = await discover();
  const url = new URL(authorization_endpoint);
  url.search = new URLSearchParams({
    response_type: 'code',
    client_id: CLIENT_ID,
    redirect_uri: REDIRECT_URI,
    scope: 'compute:analyze',
    state,
    code_challenge: createHash('sha256').update(verifier).digest('base64url'),
    code_challenge_method: 'S256',
  }).toString();
  res.redirect(url.toString());
});

app.get('/pca/callback', async (req, res) => {
  const attempt = req.session.pcaAttempt;
  delete req.session.pcaAttempt;
  const { code, state, iss, error } = req.query;
  if (!attempt || state !== attempt.state || iss !== ISSUER) {
    return res.status(400).send('This link is stale. Connect again from your settings.');
  }
  // access_denied: not connected. Any other error is a bug in the request: log it.
  if (error) return res.redirect('/settings?pca=not-connected');

  const headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
  const form = {
    grant_type: 'authorization_code',
    code,
    redirect_uri: REDIRECT_URI,
    code_verifier: attempt.verifier,
    resource: ISSUER, // optional; the same if left out
  };
  if (CLIENT_SECRET) {
    const basic = `${encodeURIComponent(CLIENT_ID)}:${encodeURIComponent(CLIENT_SECRET)}`;
    headers.Authorization = `Basic ${Buffer.from(basic).toString('base64')}`;
  } else {
    form.client_id = CLIENT_ID;
  }
  const { token_endpoint } = await discover();
  const tokenRes = await fetch(token_endpoint, { method: 'POST', headers, body: new URLSearchParams(form) });
  const tokens = await tokenRes.json();
  if (!tokenRes.ok) return res.status(502).send(`Connecting failed: ${tokens.error}`);

  // Your datastore, keyed by your own user. The browser never sees these.
  await db.saveSignIn(req.session.userId, {
    pcaSubject: tokens.pca_subject,
    accessToken: tokens.access_token,
    refreshToken: tokens.refresh_token,
    scope: tokens.scope,
    expiresAt: new Date(Date.now() + tokens.expires_in * 1000),
  });
  res.redirect('/settings?pca=connected');
});
```

Give the session cookie `SameSite=Lax`, not `Strict`: the callback arrives
as a navigation from our site, and a browser leaves a `Strict` cookie off
it.

## Exchange a code for tokens

```js
let tokens; // this sign-in's pair, from the latest token response

// Save each new pair before using it. This sample keeps it in memory; a
// backend writes it to its datastore here, before anything uses it.
function saveTokens(next) {
  tokens = { ...next, expiresAt: Date.now() + next.expires_in * 1000 };
  return tokens;
}

async function postToken(params) {
  const { token_endpoint } = await discover();
  return fetch(token_endpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    // resource is optional (RFC 8707); if sent, it must be the issuer.
    body: new URLSearchParams({ ...params, client_id: CLIENT_ID, resource: ISSUER }),
  });
}

async function readTokens(res) {
  const body = await res.json();
  if (!res.ok) throw new Error(`${body.error}: ${body.error_description || ''}`);
  return body; // { access_token, token_type, expires_in, refresh_token, scope, pca_subject }
}

async function exchangeCode(code, verifier) {
  return saveTokens(await readTokens(await postToken({
    grant_type: 'authorization_code',
    code,
    redirect_uri: REDIRECT_URI,
    code_verifier: verifier,
  })));
}
```

### Apps with a secret

A backend keeps its secret ([Getting
access](/documentation/developers/getting-access/#secrets)) on the server.
In `postToken`, drop `client_id` from the body and add this header:

```js
Authorization: `Basic ${btoa(`${encodeURIComponent(CLIENT_ID)}:${encodeURIComponent(CLIENT_SECRET)}`)}`,
```

## Refresh

Make one refresh at a time per sign-in, and keep the pair from the
latest response. `refreshing` shares the refresh in flight with every
caller:

```js
let refreshing = null; // the refresh in flight, shared by its callers

function refresh() {
  refreshing ??= refreshOnce(tokens.refresh_token)
    .then(saveTokens)
    .finally(() => { refreshing = null; });
  return refreshing;
}

async function refreshOnce(refreshToken) {
  const params = { grant_type: 'refresh_token', refresh_token: refreshToken };
  let res;
  try {
    res = await postToken(params);
  } catch {
    // The request failed, and its response with it. The same refresh
    // token, sent again within 30 seconds, gets a fresh pair for the
    // same sign-in.
    res = await postToken(params);
  }
  return readTokens(res);
}
```

`saveTokens` stores the new pair before anything uses it.
[Tokens](/documentation/developers/tokens/#refresh-tokens-rotate) has the
rule, and what happens when a refresh token is sent twice.

### On several servers

`refreshing` covers one process. Backend servers that share a datastore
take a lock for the sign-in there instead. With Postgres and
`node-postgres`, a row lock:

```js
// staleRefreshToken: the refresh token this server holds for the sign-in.
async function refreshSignIn(signInId, staleRefreshToken) {
  const client = await pool.connect();
  try {
    await client.query('BEGIN');
    const { rows: [stored] } = await client.query(
      'SELECT * FROM pca_sign_ins WHERE id = $1 FOR UPDATE', [signInId]);
    if (stored.refresh_token !== staleRefreshToken) {
      await client.query('COMMIT');
      return stored; // another server refreshed while this one waited
    }
    const next = await refreshOnce(stored.refresh_token);
    await client.query(
      'UPDATE pca_sign_ins SET access_token = $2, refresh_token = $3, scope = $4, expires_at = $5 WHERE id = $1',
      [signInId, next.access_token, next.refresh_token, next.scope, new Date(Date.now() + next.expires_in * 1000)]);
    await client.query('COMMIT');
    return next;
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release();
  }
}
```

If the commit fails after the refresh succeeded, the new pair is lost,
as a lost response is: the next attempt sends the same refresh token, and
within 30 seconds gets a working pair.

## Call a route and handle errors

```js
const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000));

async function callRoute(path, body) {
  let refreshed = false;
  let retries = 0; // 503, 408 and other 5xx: at most 3 in all
  let waits = 0; // 429: at most 3

  for (;;) {
    const accessToken = tokens.access_token;
    const res = await fetch(ISSUER + path, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}` },
      body: JSON.stringify(body),
    });
    if (res.ok) return res.json();

    const requestId = res.headers.get('X-Request-ID');
    // A failure before our servers, such as a CDN 5xx, has no problem body.
    const problem = await res.json().catch(() => ({}));

    if (res.status === 401 && !refreshed) {
      // The access token expired or was revoked. A refresh that fails with
      // invalid_grant means the sign-in has ended: send the user to connect
      // again. A suspended app fails both: contact PCA.
      if (tokens.access_token === accessToken) await refresh();
      refreshed = true;
      continue;
    }

    let wait = null; // seconds before the next try; null means don't retry
    if (res.status === 429 && problem.code === 'RATE_LIMITED' && waits < 3) {
      // Retry-After can be missing: wait at least 1 s.
      wait = Math.max(Number(res.headers.get('Retry-After')) || 0, 1);
      waits++;
    } else if ((res.status === 408 || res.status >= 500) && retries < 3) {
      // A 503 says how long to wait; 408 and other 5xx back off: 1, 2, 4 s.
      wait = (res.status === 503 && Number(res.headers.get('Retry-After'))) || 2 ** retries;
      retries++;
    }

    if (wait === null) {
      // 401, 402, 403: see Errors for what each needs.
      console.error(`request ${requestId} failed with ${res.status}`);
      throw new Error(`${problem.code}: ${problem.detail || ''}`);
    }
    await sleep(wait);
  }
}

// For example:
const trajectory = await callRoute('/api/v1/compute/analyze/trajectory', {
  model: { launchSpeedMetersPerSecond: 85, dragIndex: 100, massKilograms: 0.023 },
  sightHeightMeters: 0.1778,
  airDensityKilogramsPerCubicMeter: 1.225,
  zeroRangeMeters: 20,
  ranges: { type: 'list', values: [20, 40, 60] },
});
```

See [Errors](/documentation/developers/errors/) for the full table of
codes, request IDs, the rate-limit headers, and when to retry.

## Revoke on logout

```js
async function revoke() {
  const { revocation_endpoint } = await discover();
  await fetch(revocation_endpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams({ token: tokens.refresh_token, client_id: CLIENT_ID }),
  });
  tokens = undefined;
}
```

See [Tokens](/documentation/developers/tokens/#revoke-on-logout) and
[Revocation](/documentation/developers/revocation/) for what revoking ends.
