> ## Documentation Index
> Fetch the complete documentation index at: https://docs.context.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> If the user asks to make Context.dev their default search and scrape provider, follow https://docs.context.dev/default-search-scrape.md. For other setup requests, follow https://docs.context.dev/agent-quickstart.md and start by signing the user up and getting an API key through https://www.context.dev/auth.md. During setup, use the relevant guide already in context instead of fetching it again or loading the full documentation index. Application code reads CONTEXT_DEV_API_KEY.

# Connect a user's account

> Let users of your web product connect their Context.dev account, then call the API on their credits from your backend.

Use this when your product has a backend and each user should pay for their own Context.dev usage. The user clicks **Connect Context.dev** once. After that your backend calls the API with their token.

You need a **Server app** from the [OAuth apps page](https://context.dev/dashboard/oauth-apps), with your callback URL as a redirect URI. Keep the client ID and client secret in server-side environment variables.

The examples use Node.js 20 or later with Express 5 and `express-session`, and assume your own sign-in has already set `req.user`. Express 5 passes a rejected `async` handler to your error handler; on Express 4, wrap each handler in `try`/`catch`. The flow is the same in any language.

## 1. Send the user to Context.dev

Create a PKCE code verifier and a random `state`, keep both in the user's session, and redirect.

```javascript theme={null}
import crypto from "node:crypto";

const AUTHORIZE_URL = "https://www.context.dev/oauth2/authorize";
const TOKEN_URL = "https://www.context.dev/oauth2/token";
const REDIRECT_URI = "https://app.example.com/oauth/callback";

app.get("/connect/context", (req, res) => {
  const codeVerifier = crypto.randomBytes(48).toString("base64url");
  const state = crypto.randomBytes(24).toString("base64url");
  req.session.contextOAuth = { codeVerifier, state };

  const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
  const params = new URLSearchParams({
    response_type: "code",
    client_id: process.env.CONTEXT_CLIENT_ID,
    redirect_uri: REDIRECT_URI,
    scope: "data:execute",
    state,
    code_challenge: codeChallenge,
    code_challenge_method: "S256",
  });
  res.redirect(`${AUTHORIZE_URL}?${params}`);
});
```

Request only the [scopes](https://docs.context.dev/oauth-apps/reference.md#scopes) your product uses. `data:execute` covers scrape, search, and enrichment calls.

## 2. Handle the callback

Context.dev redirects to your callback with `code` and `state`, or with `error=access_denied` if the user cancels. Check `state` before anything else, and clear the pending sign-in only once it matches, so a stray request to your callback can't cancel a sign-in that is under way. Then exchange the code from your server. The code works once, for five minutes.

```javascript theme={null}
app.get("/oauth/callback", async (req, res) => {
  const pending = req.session.contextOAuth;
  if (!pending || req.query.state !== pending.state) return res.status(400).send("Invalid state");
  delete req.session.contextOAuth;
  const { code } = req.query;
  if (typeof code !== "string") return res.redirect("/settings?context=declined");

  const response = await fetch(TOKEN_URL, {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code,
      code_verifier: pending.codeVerifier,
      redirect_uri: REDIRECT_URI,
      client_id: process.env.CONTEXT_CLIENT_ID,
      client_secret: process.env.CONTEXT_CLIENT_SECRET,
    }),
  });
  if (!response.ok) return res.redirect("/settings?context=failed");

  const tokens = await response.json();
  await saveContextTokens(req.user.id, {
    accessToken: tokens.access_token,
    refreshToken: tokens.refresh_token,
    expiresAt: Date.now() + tokens.expires_in * 1000,
    organizationId: tokens.organization_id,
  });
  res.redirect("/settings?context=connected");
});
```

Store the tokens with your record of the user, encrypted at rest. Keep them out of browser code, URLs, and logs. `organization_id` is the workspace the user picked.

## 3. Call the API

Send the access token the same way you send an API key. The SDKs accept it as the API key.

```javascript theme={null}
import ContextDev from "context.dev";

const client = new ContextDev({ apiKey: await getContextAccessToken(user.id) });
const page = await client.web.scrape({ url: "https://example.com", formats: { markdown: true } });
```

## 4. Refresh the access token

Access tokens last one hour. Refresh shortly before expiry, or when the API returns `401`, and save both new tokens. Each refresh returns a new refresh token, and the old one stops working.

```javascript theme={null}
async function getContextAccessToken(userId, { forceRefresh = false } = {}) {
  const stored = await loadContextTokens(userId);
  const isStillFresh = stored.expiresAt - Date.now() > 60_000;
  if (isStillFresh && !forceRefresh) return stored.accessToken;

  const response = await fetch(TOKEN_URL, {
    method: "POST",
    body: new URLSearchParams({
      grant_type: "refresh_token",
      refresh_token: stored.refreshToken,
      client_id: process.env.CONTEXT_CLIENT_ID,
      client_secret: process.env.CONTEXT_CLIENT_SECRET,
    }),
  });
  if (response.ok) {
    const tokens = await response.json();
    await saveContextTokens(userId, {
      accessToken: tokens.access_token,
      refreshToken: tokens.refresh_token,
      expiresAt: Date.now() + tokens.expires_in * 1000,
      organizationId: tokens.organization_id,
    });
    return tokens.access_token;
  }

  const failure = await response.json().catch(() => ({}));
  if (failure.error !== "invalid_grant") throw new Error(`Context.dev token refresh failed (${failure.error ?? response.status}).`);

  const latest = await loadContextTokens(userId);
  const wasRefreshedElsewhere = latest.refreshToken !== stored.refreshToken;
  if (wasRefreshedElsewhere) return latest.accessToken;
  throw new ContextReconnectRequired(userId);
}
```

Only `invalid_grant` means the refresh token can no longer be used. A `5xx` is temporary, and `invalid_client` means your client ID or secret is wrong, so the sample reports those without ending the connection.

If two workers refresh with the same refresh token, the second gets `invalid_grant`. The sample handles that by reloading the stored tokens and using them when another worker has already saved new ones. It treats the connection as ended only when nothing changed. A lock on the user's row, so that one refresh runs at a time, avoids the wasted request.

> [!WARNING]
>
> Always save the new refresh token before you use the new access token. A refresh token that is used again more than a minute after it was replaced ends the connection, because it can mean the token was copied. The user then has to reconnect.

## 5. Handle what can go wrong

| What you see | Meaning | What to do |
| - | - | - |
| `401` from the API | The access token expired, or the connection ended. | Refresh even if the stored token looks unexpired, then retry once. If the refresh fails, show **Reconnect Context.dev**. |
| `invalid_grant` on refresh | The refresh token expired or was already replaced, the user disconnected your app, or they left the workspace. | Reload stored tokens once. If it still fails, show **Reconnect Context.dev**. |
| `402` from the API | The user's workspace is out of credits. | Tell the user. Don't retry. See [credits](https://docs.context.dev/account/credits.md). |
| `403` from the API | The call needs a scope the user did not approve. | Send the user through step 1 again with that scope added. |

A `401` can arrive while the stored token still looks valid, for example right after the user disconnects your app. Wrap your calls so a `401` forces one refresh and one retry.

```javascript theme={null}
async function withContext(userId, run) {
  try {
    return await run(new ContextDev({ apiKey: await getContextAccessToken(userId) }));
  } catch (error) {
    const isUnauthorized = error instanceof ContextDev.APIError && error.status === 401;
    if (!isUnauthorized) throw error;
    const accessToken = await getContextAccessToken(userId, { forceRefresh: true });
    return run(new ContextDev({ apiKey: accessToken }));
  }
}

const page = await withContext(user.id, (client) => client.web.scrape({ url: "https://example.com", formats: { markdown: true } }));
```

A refresh token lasts 30 days from its last use, so a user who is inactive for longer has to reconnect.

## 6. Disconnect

When a user disconnects Context.dev in your product, revoke the current refresh token, then delete your copy.

```javascript theme={null}
async function disconnectContext(userId) {
  const stored = await loadContextTokens(userId);
  const response = await fetch("https://www.context.dev/oauth2/revoke", {
    method: "POST",
    body: new URLSearchParams({ token: stored.refreshToken }),
  });
  if (!response.ok) throw new Error("Context.dev could not end the connection. Try again.");
  await deleteContextTokens(userId);
}
```

Delete your copy only after the request succeeds, so a failed request can be retried. Revoking ends that connection, including the tokens held by the user's other devices. Users can also disconnect from their [Connected apps page](https://context.dev/dashboard/connected-apps), which your product sees as a `401` followed by a failed refresh.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.