# Quickstart: Node

The Node SDK, `@ohauthcat/node`, gives you `OhAuthCat`, `sso.getAuthorizationUrl(...)`, `sso.getProfileAndToken(...)` and `RestartSignIn`. Every example on this page is run against the SDK in our test suite.

## Install

The SDK needs Node.js 20 or later.

Install it:

```sh
npm install @ohauthcat/node
```

## Configure

Set server configuration from the dashboard. Keep secrets on the server.

:::tip[Your test keys]
Signed in to the dashboard? [Show your sandbox keys](/get-started/sandbox-keys/) on that page and copy them straight into your environment.
:::

Sandbox and production environments share these hosts: the keys (`sk_test_...` or `sk_live_...`) select the environment, so you never change the host to switch between them.

| Variable                                        | Where it comes from                                                                                                                                                                                              |
| ----------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OHAUTHCAT_API_KEY`                             | The environment's secret key (`sk_...`), from **API keys**.                                                                                                                                                      |
| `OHAUTHCAT_CLIENT_ID`                           | The environment's publishable key (`pk_...`), from **API keys**. The SDK sends it as the OAuth `client_id`.                                                                                                      |
| `OHAUTHCAT_ENVIRONMENT_ID`                      | The environment ID (`env_...`), shown in the dashboard's quickstart snippet.                                                                                                                                     |
| `OHAUTHCAT_ORGANIZATION`                        | The organization ID (`org_...`) of the customer signing in.                                                                                                                                                      |
| `OHAUTHCAT_REDIRECT_URI`                        | A callback URI registered under **Redirect URIs**.                                                                                                                                                               |
| `OHAUTHCAT_API_ORIGIN`, `OHAUTHCAT_AUTH_ORIGIN` | Leave unset for production: the SDK defaults to `https://api.ohauthcat.com` and `https://auth.ohauthcat.com`. Any other deployment must set both to its own API and auth origins, or sign-in goes to production. |

## Begin and complete a sign-in

This module illustrates a single-process attempt store. Production needs an atomic, expiring shared store and cleanup of abandoned attempts. Bind its browser session ID to your application's secure session cookie, never to a user-controlled query parameter.

```javascript
const apiKey = process.env.OHAUTHCAT_API_KEY;
const clientId = process.env.OHAUTHCAT_CLIENT_ID;
const environmentId = process.env.OHAUTHCAT_ENVIRONMENT_ID;
const organization = process.env.OHAUTHCAT_ORGANIZATION;
const redirectUri = process.env.OHAUTHCAT_REDIRECT_URI;
if (!apiKey || !clientId || !environmentId || !organization || !redirectUri) {
  throw new Error("Missing server SSO configuration");
}
const client = new OhAuthCat({
  apiKey,
  clientId,
  environmentId,
  timeoutMs: 5000,
  maxRetries: 0,
  // Unset in production; required for any other deployment.
  apiBaseUrl: process.env.OHAUTHCAT_API_ORIGIN,
  authBaseUrl: process.env.OHAUTHCAT_AUTH_ORIGIN,
});
// Demonstration only: replace with a durable, atomic server-side attempt store.
const attempts = new Map();

export function beginSignIn(browserSessionId) {
  if (typeof browserSessionId !== "string" || !browserSessionId) {
    throw new Error("Missing initiating browser session");
  }
  const state = randomBytes(32).toString("base64url");
  const { url, codeVerifier } = client.sso.getAuthorizationUrl({
    redirectUri,
    state,
    organization,
  });
  attempts.set(state, {
    browserSessionId,
    codeVerifier,
    expiresAt: Date.now() + 5 * 60 * 1000,
  });
  return { authorizationUrl: url, state };
}

export async function completeSignIn(callbackUrl, browserSessionId) {
  const callback = new URL(callbackUrl);
  const expected = new URL(redirectUri);
  if (
    callback.origin !== expected.origin ||
    callback.pathname !== expected.pathname
  ) {
    throw new Error("Unexpected callback location");
  }
  for (const name of ["state", "code", "error"]) {
    if (callback.searchParams.getAll(name).length > 1) {
      throw new Error("Repeated callback parameter");
    }
  }
  const state = callback.searchParams.get("state") ?? "";
  const attempt = attempts.get(state);
  if (!attempt || attempt.expiresAt <= Date.now()) {
    attempts.delete(state);
    throw new Error("Missing or expired sign-in attempt");
  }
  const actualSession = Buffer.from(browserSessionId ?? "");
  const expectedSession = Buffer.from(attempt.browserSessionId);
  if (
    actualSession.length !== expectedSession.length ||
    !timingSafeEqual(actualSession, expectedSession)
  ) {
    throw new Error("Wrong initiating browser session");
  }
  // Consume before the exchange; a failing exchange requires a fresh attempt.
  attempts.delete(state);
  const code = callback.searchParams.get("code");
  if (callback.searchParams.has("error") || !code) {
    throw new Error("Sign-in failed; start again");
  }
  try {
    const result = await client.sso.getProfileAndToken({
      code,
      codeVerifier: attempt.codeVerifier,
      redirectUri,
    });
    if (result.profile.organization_id !== organization) {
      throw new Error("Unexpected profile organization");
    }
    return result.profile;
  } catch (error) {
    if (error instanceof RestartSignIn) {
      throw new Error("Sign-in interrupted; start a new attempt");
    }
    throw error;
  }
}
```

Your sign-in route calls the begin function and redirects to the returned authorization URL. Your callback route supplies its actual URL and the same trusted browser session ID to the complete function. After a successful organization check, map the returned profile to an allowed local user and create your own secure session. Never log the full profile or token.

Reject wrong state/session, repeated callback parameters, expiry and replay before creating a session. On exchange failure start a new attempt; the code and verifier are single-use. [Token exchange](/sso/how-it-works/) requires both PKCE and the secret key on the auth host.

The example returns a profile, not a provider session. See [identity mapping](/sso/profiles/) and [working with existing auth](/sso/working-with-existing-auth/) for the next step.
