# OAuth

Source: https://developers.swell.is/apps/oauth

Swell gives your app one OAuth callback URL for every store. You register it with the provider once, and Swell sends each provider redirect to your callback function in the store that started the connection.

1. The merchant clicks Connect in your app's settings. Your component calls your start route.
1. The start route calls `req.oauth.start()`, which answers a single-use `state` and the `redirectUri`, and answers the provider's authorization URL.
1. The dashboard tab goes to the provider, where the merchant approves.
1. The provider redirects to your app's callback URL with a `code` and the `state`.
1. Swell finds the store, environment and installation from the state, and calls your callback function there.
1. The callback exchanges the code for a token and saves it in your app's settings.
1. The tab comes back to your app's settings.

The provider only ever sees your app's one callback URL. The state tells Swell which store, environment and installation started the connection, so your callback runs there.

## Before you start

The examples connect a Cloudflare account with standard OAuth 2.0. Other providers differ only in their URLs and parameter names.

**Register the callback URL with the provider.** Push the app, then run `swell app info`. It prints the URL as **OAuth callback**:

```txt
https://swell.store/integration/api/apps/<app record id>/oauth/callback
```

The ID in the URL is the app's record ID, not the `id` in your `swell.json`. There is one URL per app, for every store and environment that installs it. A copy of the app pushed from another store is another app, with another URL.

**Keep the client credentials in [app secrets](ref:apps-app-secrets):**

```bash
swell app secret set CF_OAUTH_CLIENT_ID
swell app secret set CF_OAUTH_CLIENT_SECRET
```

**Declare where the connection lives.** A [settings](https://developers.swell.is/apps/settings) group holds the Connect button and the fields the callback writes:

```json
// settings/cloudflare.json
{
  "label": "Cloudflare",
  "fields": [
    { "id": "connect", "type": "component", "component": "ConnectCloudflare", "label": "Cloudflare account" },
    { "id": "access_token", "type": "secret", "label": "Access token", "readonly": true },
    { "id": "connected_at", "type": "short_text", "label": "Connected at", "readonly": true },
    { "id": "last_error", "type": "short_text", "label": "Last error", "readonly": true }
  ]
}
```

`readonly` only stops the merchant from editing a field. Your functions still write it.

## The start route

One route serves the Connect button. `POST` starts a connection, and `GET` reads its status, since a component sees only public settings.

```typescript
// functions/cloudflare-connect.ts
export const config: SwellConfig = { route: { methods: ['post', 'get'] } };

function requireAdmin(req: SwellRequest) {
  if (!(req.swellContext?.surface === 'admin' && req.swellContext.storeUser)) {
    throw new SwellError('Admin component calls only', { status: 403 });
  }
}

// POST: start a connection and answer the provider's authorization URL
export async function post(req: SwellRequest) {
  requireAdmin(req);
  const clientId = req.appSecrets.CF_OAUTH_CLIENT_ID;
  if (!clientId) {
    throw new SwellError('Set CF_OAUTH_CLIENT_ID with swell app secret set', { status: 500 });
  }

  const { state, redirectUri } = await req.oauth.start({ callback: 'cloudflare-callback' });

  const url = new URL('https://dash.cloudflare.com/oauth2/auth');
  url.search = new URLSearchParams({
    client_id: clientId,
    response_type: 'code',
    scope: 'user-details.read',
    state,
    redirect_uri: redirectUri,
  }).toString();
  return { url: url.href };
}

// GET: the connection's status, for the component
export async function get(req: SwellRequest) {
  requireAdmin(req);
  const { cloudflare } = await req.swell.settings();
  return {
    connected: Boolean(cloudflare?.access_token),
    connected_at: cloudflare?.connected_at ?? null,
    last_error: cloudflare?.last_error ?? null,
  };
}
```

- `req.oauth.start({ callback })` answers `{ state, redirectUri, expiresAt }`. Send `state` and `redirectUri` to the provider.
- `callback` names your route function that gets the redirect. It must be enabled and answer GET: `start()` refuses any other function and says why.
- `data` is optional JSON up to 2,048 bytes, such as a PKCE `code_verifier`. It stays on Swell for the callback and never goes to the browser.
- **Never make this route public.** Leave out `route.public`. A connection isn't tied to the person who started it, so a shopper who could start one could link their own account to the store. The check at the top lets only admins in the dashboard through.

## The Connect button

The provider's page can't open inside the dashboard, so the button sends the whole dashboard tab there. The tab comes back to your app's settings, which load again and show the outcome.

```typescript
// components/ConnectCloudflare.tsx
import type { ComponentProps } from '@swell/apps-sdk/components';
import { useEffect, useState } from 'preact/hooks';

const route = '/functions/<app_id>/cloudflare-connect';
type Status = { connected: boolean; connected_at: string | null; last_error: string | null };

export default function ConnectCloudflare(props: ComponentProps<string>) {
  const [status, setStatus] = useState<Status | null>(null);
  const [continueUrl, setContinueUrl] = useState('');
  const [message, setMessage] = useState('');

  // The merchant comes back to a freshly loaded page: this shows the outcome
  useEffect(() => {
    void props.fetch(route).then((res) => (res.ok ? res.json() : null)).then(setStatus);
  }, []);

  async function connect() {
    setMessage('');
    const res = await props.fetch(route, { method: 'POST' });
    if (!res.ok) {
      setMessage('Could not start the connection');
      return;
    }
    const { url } = await res.json();
    setContinueUrl(url);
    window.open(url, '_top'); // the whole dashboard tab goes to Cloudflare
  }

  return (
    <div>
      <p>{status?.connected ? `Connected at ${status.connected_at}` : 'Not connected'}</p>
      {status?.last_error && <p>Last attempt failed: {status.last_error}</p>}
      <button type="button" onClick={() => void connect()}>
        {status?.connected ? 'Reconnect' : 'Connect Cloudflare'}
      </button>
      {continueUrl && (
        <p>
          <a href={continueUrl} target="_top">Continue to Cloudflare</a>
        </p>
      )}
      {message && <p>{message}</p>}
    </div>
  );
}
```

- `<app_id>` is the `id` in your `swell.json`.
- **Keep the Continue link.** A component may send the tab elsewhere only right after a click. When the route answers late, the browser blocks it, and the link does it with a fresh click.
- **No popup, no polling.** The tab leaves the dashboard and comes back, so changes not yet saved elsewhere on the page are lost.

## The callback

Swell calls your callback function in the store that started the connection, with GET, and only after it has checked the state. The function exchanges the code, saves the token and says where the tab goes.

```typescript
// functions/cloudflare-callback.ts
export const config: SwellConfig = { route: { methods: ['get'] } };

export async function get(req: SwellRequest): Promise<SwellOAuthCallbackResult> {
  const callback = req.oauth.callback;
  if (!callback) throw new SwellError('Not an OAuth callback', { status: 400 });

  // Save the outcome, then send the merchant back to the app's settings
  async function finish(cloudflare: object): Promise<SwellOAuthCallbackResult> {
    await req.swell.put(`/settings/${req.appId}`, { cloudflare });
    const url = new URL(req.app.admin_url);
    url.searchParams.set('tab', 'settings');
    return { redirect: url.href };
  }

  const { code, error } = callback.params;
  if (error || !code) {
    return finish({
      last_error: error === 'access_denied' ? 'The connection was declined.' : 'Cloudflare sent no code.',
    });
  }

  const { CF_OAUTH_CLIENT_ID, CF_OAUTH_CLIENT_SECRET } = req.appSecrets;
  if (!CF_OAUTH_CLIENT_ID || !CF_OAUTH_CLIENT_SECRET) {
    console.error('Set CF_OAUTH_CLIENT_ID and CF_OAUTH_CLIENT_SECRET with swell app secret set');
    return finish({ last_error: 'The app is not configured yet.' });
  }

  const res = await fetch('https://dash.cloudflare.com/oauth2/token', {
    method: 'POST',
    redirect: 'manual', // a redirect never carries your credentials elsewhere
    headers: { Authorization: `Basic ${btoa(`${CF_OAUTH_CLIENT_ID}:${CF_OAUTH_CLIENT_SECRET}`)}` },
    body: new URLSearchParams({
      grant_type: 'authorization_code',
      code,
      redirect_uri: callback.redirectUri,
    }),
  });
  const token = res.ok ? await res.json().catch(() => null) : null;
  if (typeof token?.access_token !== 'string') {
    console.error('Cloudflare token exchange failed', res.status);
    return finish({ last_error: 'Cloudflare did not issue a token.' });
  }

  return finish({
    access_token: token.access_token,
    connected_at: new Date().toISOString(),
    last_error: null,
  });
}
```

- `req.oauth.callback` is `{ params, data, name, redirectUri }` on Swell's call, and `null` on any other call.
- `params` holds everything the provider sent, as strings: `code` on success, `error` when the merchant declines. `data` is what you passed to `start()`.
- `redirectUri` goes back into the token request; most providers check it.
- Trust `params` and `data` only once the provider accepts the code exchange. A request sent straight to the function can carry made-up values, but not your app secrets.
- **Answer with a redirect:** `{ redirect }` takes an absolute URL under the app's page in the dashboard, such as that page with `?tab=settings`, or under the app's frontend in the same store. Any other URL, a relative one, or none opens the app's dashboard page.
- **Use manual redirects.** Pass `redirect: 'manual'` on requests that carry your credentials. In Swell's workers, `redirect: 'error'` fails before the request is sent.
- **Log the provider's error code, not the request.** `params` and `data` hold the code and your values, and the store's staff can read function logs.

## What the merchant sees

| What happens | The tab ends on | It shows |
| --- | --- | --- |
| The connection succeeds | The app's settings | Your status: connected |
| The merchant declines at the provider | The app's settings | Your last_error: the callback got params.error |
| The callback answers any other URL | The app's page in the dashboard | That page; a warning in your function log says why |
| The callback throws or answers 400 or more | Swell's Connection not finished page | A link back to the app, the error code, and the swell logs command for you |
| The link was already used, or is older than 10 minutes | Swell's Connection not finished page | That the link expired or was already used, and to connect again |
| The app was uninstalled or reinstalled meanwhile | Swell's Connection not finished page | To go back to the app and try again |

## Rules

- **A connection link works once, for 10 minutes.** It belongs to the store, environment and installation that started it, so uninstalling and reinstalling the app ends a connection in progress.
- **The callback always runs on Swell,** with your app secrets, even while `swell app dev` runs. To try it, run `swell app push` and connect from the dashboard. Local functions then read the saved token from settings.
- **The callback is called with GET,** whether the provider redirects or posts a form, so it needs a `get` or default export. `start()` checks the route's methods but can't see your exports.
- **Find a failed run** with `swell logs --type function -s cloudflare-callback`.
- **Start connections from a component** in the dashboard, and keep the start route admin-only, as above.
- **Refreshing and disconnecting are up to your functions.** They refresh a token with the provider, and clear the settings to disconnect.

## Testing

The `createMockRequest()` helper that `swell create tests` adds takes `oauth`. `req.oauth.start()` throws unless you mock it, and `req.oauth.callback` is `null` unless you set it:

```typescript
const req = createMockRequest({
  appSecrets: { CF_OAUTH_CLIENT_ID: 'id', CF_OAUTH_CLIENT_SECRET: 'secret' },
  oauth: {
    callback: {
      params: { code: 'test-code', state: 'test-state' },
      data: null,
      name: 'cloudflare-callback',
      redirectUri: 'https://example.com/callback',
    },
  },
});
```

Types for `req.oauth` and `SwellOAuthCallbackResult` come with `@swell/app-types` 1.4.1 or later.

Available in Swell CLI 2.9.43 and later. Functions get `req.oauth` once they're pushed with that version.
