For AI agents: the complete documentation index is available at https://docs.clickmax.io/en/llms.txt, the full documentation bundle is available at https://docs.clickmax.io/en/llms-full.txt, and this page is available as Markdown at https://docs.clickmax.io/en/reference/api/clickmax-apps.md.
  • English
  • Clickmax Apps OAuth reference

    The OAuth 2.0 and OpenID Connect contract a Clickmax App's server uses to receive installations and call the Clickmax API. The app is created in Settings > Connections, My apps tab (see How do I create a Clickmax App in My apps?); the full flow is in How does a Clickmax App get installed and act in a workspace?.

    Addresses

    UseAddress
    AuthorizationGET https://login.clickmax.io/api/auth/oauth2/authorize
    TokenPOST https://login.clickmax.io/api/auth/oauth2/token
    UserInfoGET https://login.clickmax.io/api/auth/oauth2/userinfo
    OpenID Connect discoveryhttps://login.clickmax.io/api/auth/.well-known/openid-configuration
    Installation listGET https://login.clickmax.io/api/auth/apps/installations
    One installationGET https://login.clickmax.io/api/auth/apps/installations/<installation_id>
    Install linkhttps://login.clickmax.io/apps/<client_id>/install
    v0 APIhttps://mcp.clickmax.io/api/v0
    resource of the installation token and of the session token exchangehttps://mcp.clickmax.io/api
    Page of an app inside the panelhttps://app.clickmax.io/<workspace>/apps/<app slug>

    App credentials

    ItemValue
    Client IDThe client_id. Stays visible in My apps.
    Client secretStarts with cxp_cs_. Shown once, when the app is created or a new secret is generated.
    Authentication at the token endpointHTTP Basic with the client ID and secret (client_secret_basic). Other methods are refused.
    Redirect URLs1 to 10. https, or http on localhost, 127.0.0.1 or [::1]. No fragment (#). The authorization's redirect_uri must equal one of them, port and path included.

    Authorization request

    Parameters of GET /oauth2/authorize:

    ParameterRequiredValue
    response_typeYescode
    client_idYesThe client ID.
    redirect_uriYesOne of the app's Redirect URLs, exactly.
    scopeYesSpace-separated scopes (table below). To install, include install.
    code_challengeYesSHA-256 of the PKCE verifier, base64url-encoded.
    code_challenge_methodYesS256. No other method is accepted.
    stateRecommendedA random single-use value. Comes back unchanged; check it against the one you stored in the person's session.

    Scopes

    ScopeWhat it gives the app
    installCreates or updates the installation in the workspace the person picks. The code exchange returns installation_id and workspace_id.
    openidAn id_token of the person who authorized, with sub.
    emailemail and email_verified in the id_token and in UserInfo.
    profilename in the id_token and in UserInfo.

    An app accepts only these scopes. Any other scope comes back with error=invalid_scope.

    With install, Clickmax asks the person to sign in, shows Where to install … and then Install …. Without install, there is no workspace choice (see Sign in with Clickmax).

    Return to the redirect_uri

    OutcomeParameters
    Authorizedcode, state, iss (https://login.clickmax.io/api/auth)
    Denied or invaliderror, error_description, state, iss
    errorWhen
    access_deniedThe person clicked Deny.
    invalid_scopescope has a scope the app does not accept.
    invalid_requestPKCE is missing, the method is not S256, or another parameter is malformed.

    When client_id or redirect_uri does not match the app, Clickmax shows an error page and does not return to the redirect_uri.

    Code exchange

    POST /oauth2/token, with HTTP Basic and an application/x-www-form-urlencoded body:

    FieldValue
    grant_typeauthorization_code
    codeThe code received at the redirect_uri.
    code_verifierThe request's PKCE verifier.
    redirect_uriThe same redirect_uri as the request.

    The code is valid for 10 minutes and once.

    Response fieldContent
    installation_idInstallation ID. Store it with the workspace: the app requests tokens with it. Only with the install scope.
    workspace_idWorkspace the app was installed in. Only with the install scope.
    id_tokenID token of the person who authorized. Only with the openid scope. Signed with EdDSA (Ed25519).
    access_tokenThe person's token, good only for UserInfo. The v0 API refuses it.
    token_type, expires_in, scopeStandard OAuth fields.

    The response has no refresh_token. Installing again in the same workspace returns the same installation_id.

    errorWhen
    invalid_grantCode expired, already used or from another app; code_verifier or redirect_uri differ from the request; or the installation stopped being valid before the exchange.
    invalid_requestcode, code_verifier or redirect_uri is missing.
    invalid_clientWrong client ID or secret, or the app was turned off or deleted.

    Installation token

    POST /oauth2/token, with HTTP Basic and an application/x-www-form-urlencoded body:

    FieldValue
    grant_typeurn:clickmax:params:oauth:grant-type:installation
    installation_idThe installation ID.
    resourcehttps://mcp.clickmax.io/api
    Response fieldContent
    access_tokenA JWT the v0 API accepts for that installation.
    token_typeBearer
    expires_in600 (10 minutes).
    expires_atExpiry, in seconds since 1970.
    scopeapp

    There is no refresh_token. To renew, request another token with the same installation_id, at any time. The installation_id does not expire: it is valid while the installation exists.

    errorWhen
    invalid_clientWrong ID or secret, secret replaced, or the app was turned off or deleted.
    invalid_granterror_description installation not found: the installation was removed or belongs to another app, or the app is private and the installation is in another workspace (suspended installation).
    unauthorized_clientThe client is not a Clickmax App.
    invalid_requestinstallation_id missing or malformed.
    invalid_targetresource is not https://mcp.clickmax.io/api.

    The TypeScript SDK requests the token on the first call, reuses it until one minute before it expires and requests another when the API answers 401.

    Install from Clickmax

    An install can also start on Clickmax, without an authorization request from the app: through the install link of an Unlisted app, through the Install button in My apps, or when a Private app is created, which installs it in the workspace that created it. This path has no code to exchange: the app receives the installation_id at the Setup URL or finds it in the installation list.

    Optional parameters of the install link:

    ParameterValue
    workspace_idWorkspace the page shows already picked.

    After the click on Install or Update permissions, if the app has a Setup URL, the browser goes there with these parameters, added to the query the URL already has:

    ParameterValue
    installation_idInstallation ID.
    workspace_idWorkspace the app was installed in.
    setup_actioninstall when the installation was created or reactivated just now; update when it was already active and only its permissions were updated.

    The Setup URL follows the rules of the Redirect URLs (https, or http on localhost, 127.0.0.1 or [::1], no fragment), up to 2048 characters. The install from the app's system (install in the authorization request) does not go through it.

    Check the installation_id before trusting it

    Anyone can open the Setup URL with a made-up installation_id and workspace_id. Before using the ID, read the installation at GET /apps/installations/<installation_id> with the app's credentials: only an active installation of your app answers, and the workspace in the response is the one that counts. Do not tie the installation to the person signed in to your system just because they arrived through the Setup URL; to tie an installation to an account in your system, use the install from the app's system, with state.

    Installation list

    With the app's credentials, no installation token. HTTP Basic authentication with the client ID and secret, as at the token endpoint.

    GET https://login.clickmax.io/api/auth/apps/installations

    ParameterValue
    pagePage, from 1. Defaults to 1.
    perPageInstallations per page, from 1 to 100. Defaults to 50.

    The response holds the app's active installations, oldest first, suspended ones included. Removed installations and those of disabled workspaces are absent.

    {
      "data": [
        {
          "id": "6f1c…",
          "workspace": { "id": "0b7e…", "name": "Example Store" },
          "grantedCapabilities": ["tags:read"],
          "pendingCapabilities": ["segments:read"],
          "suspended": null,
          "createdAt": "2026-11-19T12:00:00.000Z",
          "updatedAt": "2026-11-19T12:00:00.000Z"
        }
      ],
      "meta": { "countItens": 1, "countPages": 1, "perPage": 50 }
    }
    FieldContent
    idInstallation ID, the installation_id of the token.
    workspaceThe workspace's id and name.
    grantedCapabilitiesPermissions the installation can use, in the same format as the capability field of API errors.
    pendingCapabilitiesRequested permissions waiting for someone in the workspace to approve them.
    suspendedapp_private when the app went back to Private and the installation is in another workspace: token requests fail until the app is Unlisted again. null otherwise.
    createdAt, updatedAtISO 8601 dates of the installation and of its last change, such as an approval.
    meta.countItensTotal installations, across every page.
    meta.countPagesTotal pages; 0 when the page asked for is past the last one.
    meta.perPagePage size used.

    GET https://login.clickmax.io/api/auth/apps/installations/<installation_id> returns one installation in the same format as the items of data.

    StatuserrorWhen
    401invalid_clientNo authentication, wrong ID or secret, or the app was turned off or deleted. The response carries WWW-Authenticate: Basic.
    400unauthorized_clientThe client is not a Clickmax App.
    400invalid_requestpage or perPage out of range.
    404installation_not_foundThe installation does not exist, was removed, belongs to another app or is in a deactivated workspace. The response is the same in all these cases.
    429rate_limitedThe app went over 120 requests per minute on these two addresses. Wait the seconds in Retry-After.

    Errors come in the token endpoint's format: { "error": "…", "error_description": "…" }. In the TypeScript SDK, use listInstallations and getInstallation (see Read the app's installations).

    Calling the API

    Send the installation token on every request to https://mcp.clickmax.io/api/v0:

    Authorization: Bearer <access_token>

    An expired token, or one of an installation that is no longer valid, gets 401 with the code unauthorized. Request a new token and retry once. If the token request fails with invalid_grant, the installation is no longer valid.

    Every key and app of a workspace shares the same rate limit. Each source IP also has a limit of its own, counted across every workspace it calls: a server that serves many installations shares that limit among them. In Max Design server routes, that limit counts per project. Error format in Errors.

    End of access

    What happensToken requestToken already issued
    The workspace removes the app in Installed appsinvalid_grantRefused on the next call.
    The app is deleted in My appsinvalid_clientRefused on the next call.
    The app goes back to Privateinvalid_grant for installations in other workspaces, until the app is Unlisted again. In the installation list they show suspended app_private.Refused on the next call, for those installations.
    A new secret is generatedinvalid_client with the previous secretValid until it expires, within 10 minutes at most.

    Missing permissions

    An API operation may need more than one permission. Searching leads by filters, for example, also needs View on Lists and segments. When a permission is missing, the operation fails with type permission, code missing_permission and the capability field naming the missing permission. The granted and pending permissions of each installation are in grantedCapabilities and pendingCapabilities of the installation list.

    Changing the Requested permissions in My apps does not change what each installation already has. Anything new stays pending until someone in the workspace approves it in Installed apps, and the approver grants only what they can do. Whatever leaves the request is removed from the installations. While a permission is pending, operations that depend on it fail with missing_permission.

    Sign in with Clickmax

    To let people sign in to your system with their Clickmax account, use any OpenID Connect library with discovery at https://login.clickmax.io/api/auth/.well-known/openid-configuration and the scopes openid profile email, without install. There is no workspace choice: the screen is Sign in to … with Clickmax, with the Continue button. The ID token and UserInfo carry sub and, depending on the scopes, email, email_verified and name.

    ID tokens are signed with EdDSA (Ed25519). Libraries that only accept RS256 need that algorithm enabled. Sign in with Clickmax grants no API access: the v0 API refuses the token of this flow.

    Apps inside Clickmax

    An app with an Address in Clickmax opens inside the panel, on a https://app.clickmax.io/<workspace>/apps/<app slug> page, for whoever has the View and open installed apps permission in a workspace where the app is installed and active. The panel loads the Address in Clickmax in an iframe and talks to it through the bridge. The app never gets the person's session: it asks the panel for a session token, and the app's server exchanges that token for an access token that acts on the person's behalf.

    ItemRule
    Address in Clickmaxhttps, with no user name or password. It cannot have the Clickmax panel's origin.
    Panel originhttps://app.clickmax.io
    Session tokenJWT issued by the panel. Valid for 60 seconds and a single exchange. Its audience (aud) is the app's client_id.
    Access tokenJWT from the exchange. Valid for 10 minutes, no refresh_token.
    Support accessApps do not open.

    Bridge with the panel

    Messages are JSON objects { type, v: 1, ... } sent with postMessage. The panel accepts messages only from the iframe whose origin is the Address in Clickmax origin. The app must accept only messages whose event.origin equals the panel's origin, and send its own with that origin as the target.

    typeDirectionFieldsPurpose
    clickmax:readyapp → panelnoneThe app screen is ready. The panel answers with clickmax:context.
    clickmax:contextpanel → apptheme (light or dark), locale, workspaceId, installationIdPage context.
    clickmax:session-token:requestapp → panelidAsks for a session token. Use a new id on each request.
    clickmax:session-token:responsepanel → appid, token, expiresAt, or id, errorAnswer to the request with the same id. error is not_allowed (the person cannot use the app right now) or unavailable (the panel could not issue the token).
    clickmax:resizeapp → panelheight (px)Height of the app screen.
    clickmax:navigateapp → panelpathThe app's current path. The panel keeps it in its URL (?path=), so reloading or sharing the link returns to that screen.
    clickmax:toastapp → panelkind (success, error or info), messageShows a notice in the panel.
    clickmax:themepanel → appthemeThe person switched between light and dark.

    Send the session token to your server in the x-clickmax-session-token header. Inside the iframe, the browser blocks your site's cookies, and on Max Design sites the Authorization and Cookie headers do not reach the /api routes in the preview.

    Session token exchange

    POST https://login.clickmax.io/api/auth/oauth2/token, with HTTP Basic (client ID and secret, as in the other token requests) and an application/x-www-form-urlencoded body:

    FieldValue
    grant_typeurn:ietf:params:oauth:grant-type:token-exchange
    subject_tokenThe session token received from the panel.
    subject_token_typeurn:clickmax:params:oauth:token-type:session
    resourcehttps://mcp.clickmax.io/api
    Response fieldContent
    access_tokenJWT that API v0 accepts on behalf of the person, through the app.
    token_typeBearer
    expires_in600 (10 minutes).
    installation_idThe app's installation in the page's workspace.
    workspace_idThe page's workspace.

    There is no refresh_token. When the access token expires, ask the panel for a new session token and exchange it again. Use the workspace_id and installation_id from the response, not the ones the app screen sends to your server.

    errorWhen
    invalid_grantSession token expired, already exchanged or issued to another app; the installation was removed or is suspended; or the person no longer belongs to the workspace.
    invalid_clientWrong client ID or secret, or the app was disabled or deleted.
    invalid_targetresource other than https://mcp.clickmax.io/api.
    invalid_requestsubject_token is missing, or subject_token_type is not urn:clickmax:params:oauth:token-type:session.
    unauthorized_clientThe client cannot use this exchange.

    Apps built in Max Design

    In a Max Design project with .clickmax/app.json, publishing creates the app, saves APP_CLIENT_ID and APP_CLIENT_SECRET to the project's Secrets and sets the published address as the Address in Clickmax. An exchange coming from that project's server also works without the secret: Clickmax recognizes where the call comes from and authenticates the project's app. In that case, send client_id in the body, without Authorization. The project preview exchanges as the same app.

    The project gets two files that already do all of this: src/lib/clickmax-app.ts, the bridge in the page, and src/server/clickmax.ts, the exchange and the API calls. The panel, login and API origins reach the server in CLICKMAX_PANEL_ORIGIN, CLICKMAX_LOGIN_BASE_URL and CLICKMAX_API_BASE_URL, with the values of the environment the site runs in.

    On behalf of the person

    With the exchanged token, each API v0 call acts as the person through the app. The operation goes through only if the installation was granted the permission and the person can do it in the workspace. Clickmax checks both on every call: a change to the person's role or to the installation's permissions applies on the next one. Being the workspace owner gives the app nothing beyond what the installation was granted. History shows the person and the app.

    When either permission is missing, the API answers as in Missing permissions. For work with no person behind it, such as background tasks, keep using the installation token.

    For permissions with an "everyone's" version, such as opportunities, scheduling and conversations, a person who only has their own version sees through the app only the records assigned to them, as in the panel.

    Example

    TypeScript, fetch only, no framework. On the screen the panel loads:

    bridge.ts
    const PANEL_ORIGIN = 'https://app.clickmax.io'
    
    type Pending = { resolve: (token: string) => void; reject: (error: Error) => void }
    const pending = new Map<string, Pending>()
    
    function send(message: { type: string; [field: string]: unknown }) {
      window.parent.postMessage({ ...message, v: 1 }, PANEL_ORIGIN)
    }
    
    function applyTheme(theme: 'light' | 'dark') {
      document.documentElement.dataset.theme = theme
    }
    
    window.addEventListener('message', (event) => {
      if (event.origin !== PANEL_ORIGIN || event.source !== window.parent) return
      const message = event.data
      if (!message || message.v !== 1) return
    
      if (message.type === 'clickmax:context' || message.type === 'clickmax:theme') {
        applyTheme(message.theme)
      }
      if (message.type === 'clickmax:session-token:response') {
        const request = pending.get(message.id)
        if (!request) return
        pending.delete(message.id)
        if (message.error) request.reject(new Error(message.error))
        else request.resolve(message.token)
      }
    })
    
    function sessionToken(): Promise<string> {
      const id = crypto.randomUUID()
      return new Promise((resolve, reject) => {
        pending.set(id, { resolve, reject })
        send({ type: 'clickmax:session-token:request', id })
      })
    }
    
    // A new session token per call: each one is good for a single exchange.
    export async function callServer(path: string, init: RequestInit = {}) {
      const headers = new Headers(init.headers)
      headers.set('x-clickmax-session-token', await sessionToken())
      return fetch(path, { ...init, headers })
    }
    
    send({ type: 'clickmax:ready' })

    On your server, the route that receives the session token, exchanges it and calls the API (tags/list, which needs View on Tags for both the installation and the person):

    server.ts
    const LOGIN_URL = 'https://login.clickmax.io/api/auth'
    const API_URL = 'https://mcp.clickmax.io/api'
    
    type AccessToken = {
      access_token: string
      expires_in: number
      installation_id: string
      workspace_id: string
    }
    
    // Without a time limit, a stuck response holds your server's route.
    const TIMEOUT_MS = 10_000
    
    type Exchange = { ok: true; token: AccessToken } | { ok: false; error: string; status?: number }
    
    async function exchangeSessionToken(
      sessionToken: string,
      clientId: string,
      clientSecret: string,
    ): Promise<Exchange> {
      const credentials = btoa(`${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`)
      const response = await fetch(`${LOGIN_URL}/oauth2/token`, {
        method: 'POST',
        headers: {
          authorization: `Basic ${credentials}`,
          'content-type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
          grant_type: 'urn:ietf:params:oauth:grant-type:token-exchange',
          subject_token: sessionToken,
          subject_token_type: 'urn:clickmax:params:oauth:token-type:session',
          resource: API_URL,
        }),
        signal: AbortSignal.timeout(TIMEOUT_MS),
      })
      const body = await response.json().catch(() => null)
      if (!response.ok) {
        return { ok: false, error: body?.error ?? 'http_error', status: response.status }
      }
      if (typeof body?.access_token !== 'string' || typeof body?.installation_id !== 'string') {
        return { ok: false, error: 'invalid_response', status: response.status }
      }
      return { ok: true, token: body }
    }
    
    // Your server's GET /api/tags route; clientId and clientSecret come from your secret store.
    export async function handleTags(request: Request, clientId: string, clientSecret: string) {
      const sessionToken = request.headers.get('x-clickmax-session-token')
      if (!sessionToken) return Response.json({ error: 'missing_session_token' }, { status: 401 })
    
      const exchange = await exchangeSessionToken(sessionToken, clientId, clientSecret).catch(
        (): Exchange => ({ ok: false, error: 'unavailable' }),
      )
    // Only `invalid_grant` means the session token is no longer good (expired, already exchanged): ask the
    // bridge for another one. Wrong credentials or an outage are your server's failure, not the session's.
      if (!exchange.ok && exchange.error === 'invalid_grant') {
        return Response.json({ error: 'session_expired' }, { status: 401 })
      }
      if (!exchange.ok) {
        console.error({
          op: 'session_token_exchange',
          clientId,
          status: exchange.status,
          errorCode: exchange.error,
        })
        return Response.json({ error: 'exchange_failed' }, { status: 502 })
      }
    
      const tags = await fetch(`${API_URL}/v0/tags/list`, {
        headers: { authorization: `Bearer ${exchange.token.access_token}` },
        signal: AbortSignal.timeout(TIMEOUT_MS),
      })
      return new Response(tags.body, {
        status: tags.status,
        headers: { 'content-type': 'application/json; charset=utf-8' },
      })
    }

    What apps cannot do yet

    With the installation token, an app acts with the permissions of its installation, and no person is attached to its calls. In this version, apps cannot use these resources through the API, even with the permission granted:

    WhatWhat the API answers
    Social media, Webinar, AI agents and AI voicetype permission, code principal_not_allowed
    The webhooks operations of Integrations. The other Integrations operations work.type permission, code principal_not_allowed
    Meetings and recordings, Max artifacts, AI keys and Clickmax subscribersThe API has no operations for these resources.
    Creating conversations and sending messages through connected WhatsApp, Instagram or email accounts, which belong to peopletype not_found: the app has access to no connected account.
    Operations not governed by a permission you can grant, such as the help centertype permission, code principal_not_allowed
    The Firecrawl and Apollo operations that call the provider: web search, reading a page, checking the Firecrawl balance, apollo.health() and the Apollo lookups. Connecting the key, checking the status and disconnecting work.type not_found

    Everyone's permissions

    No record is assigned to an app. For the actions below, the permission without "everyone's" reaches only the records assigned to the caller, so it reaches no records when the caller is an app. Grant the everyone's variant of each of these actions, such as View (everyone's):

    ResourceActions that need "everyone's"
    OpportunitiesView, Export
    CalendarView, Export
    ConversationsView
    Support ticketsView
    Custom objectsView, Create, Edit, Delete, Import, Export

    Without the variant, the API refuses the operation with type permission.

    Creating an opportunity, or editing and deleting one at a time, works without "everyone's", but needs View (everyone's) on Opportunities. Bulk actions on opportunities also need Edit (everyone's) or Delete (everyone's). Creating, editing or deleting a calendar appointment works without "everyone's", but needs View (everyone's) on Calendar.

    No app or API key can hold the Apps, API and MCP keys, People with access (Manage) and Account details (Manage) permissions. They show as locked on the app's permission screen.

    API keys created with chosen permissions have the same limits. See Clickmax API authentication.

    Complete example

    The public clickmax-apps-sample repository shows the install from the app's system end to end, in TypeScript with the SDK. Below, a Node.js 20 or newer server, with no dependencies, covering the connect button, the return, the code exchange, the installation token request and one API call (tags/list, which needs View on Tags). Register http://127.0.0.1:3000/clickmax/callback in the app's Redirect URLs, set CLICKMAX_CLIENT_ID and CLICKMAX_CLIENT_SECRET and run node server.mjs. On your deployed server, keep pending and installations in your database and mark the cookie Secure.

    server.mjs
    import { createHash, randomBytes } from 'node:crypto'
    import { createServer } from 'node:http'
    
    const CLIENT_ID = process.env.CLICKMAX_CLIENT_ID
    const CLIENT_SECRET = process.env.CLICKMAX_CLIENT_SECRET
    const REDIRECT_URI = 'http://127.0.0.1:3000/clickmax/callback'
    const AUTH_URL = 'https://login.clickmax.io/api/auth'
    const API_URL = 'https://mcp.clickmax.io/api/v0'
    
    const pending = new Map() // state -> code_verifier
    const installations = new Map() // workspace_id -> installation_id
    
    const basic = `Basic ${Buffer.from(
      `${encodeURIComponent(CLIENT_ID)}:${encodeURIComponent(CLIENT_SECRET)}`,
    ).toString('base64')}`
    
    async function requestToken(fields) {
      const response = await fetch(`${AUTH_URL}/oauth2/token`, {
        method: 'POST',
        headers: { authorization: basic, 'content-type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams(fields),
      })
      const body = await response.json()
      if (!response.ok) throw new Error(`${body.error}: ${body.error_description}`)
      return body
    }
    
    function installationToken(installationId) {
      return requestToken({
        grant_type: 'urn:clickmax:params:oauth:grant-type:installation',
        installation_id: installationId,
        resource: 'https://mcp.clickmax.io/api',
      })
    }
    
    async function handle(req, res) {
      const url = new URL(req.url, 'http://127.0.0.1:3000')
    
      if (url.pathname === '/') {
        res.setHeader('content-type', 'text/html; charset=utf-8')
        return res.end('<a href="/clickmax/connect">Connect with Clickmax</a>')
      }
    
      if (url.pathname === '/clickmax/connect') {
        const state = randomBytes(16).toString('base64url')
        const codeVerifier = randomBytes(32).toString('base64url')
        const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url')
        pending.set(state, codeVerifier)
    
        const authorize = new URL(`${AUTH_URL}/oauth2/authorize`)
        authorize.search = new URLSearchParams({
          response_type: 'code',
          client_id: CLIENT_ID,
          redirect_uri: REDIRECT_URI,
          scope: 'openid email install',
          state,
          code_challenge: codeChallenge,
          code_challenge_method: 'S256',
        }).toString()
    
        res.writeHead(302, {
          location: authorize.href,
          'set-cookie': `clickmax_state=${state}; HttpOnly; SameSite=Lax; Path=/clickmax`,
        })
        return res.end()
      }
    
      if (url.pathname === '/clickmax/callback') {
        const state = url.searchParams.get('state')
        const cookieState = /(?:^|;\s*)clickmax_state=([^;]+)/.exec(req.headers.cookie ?? '')?.[1]
        const codeVerifier = state && state === cookieState ? pending.get(state) : undefined
        pending.delete(state)
        if (!codeVerifier) return res.writeHead(400).end('invalid state')
    
        const error = url.searchParams.get('error')
        if (error) return res.writeHead(400).end(`Install not completed: ${error}`)
    
        const installation = await requestToken({
          grant_type: 'authorization_code',
          code: url.searchParams.get('code'),
          code_verifier: codeVerifier,
          redirect_uri: REDIRECT_URI,
        })
        installations.set(installation.workspace_id, installation.installation_id)
    
        const { access_token } = await installationToken(installation.installation_id)
        const tags = await fetch(`${API_URL}/tags/list`, {
          headers: { authorization: `Bearer ${access_token}` },
        })
        res.writeHead(tags.status, { 'content-type': 'application/json; charset=utf-8' })
        return res.end(await tags.text())
      }
    
      res.writeHead(404).end()
    }
    
    createServer((req, res) => {
      handle(req, res).catch((error) => {
        console.error(error)
        if (!res.headersSent) res.writeHead(500)
        res.end('Error')
      })
    }).listen(3000, '127.0.0.1', () => console.log('http://127.0.0.1:3000'))

    With the TypeScript SDK, exchangeInstallCode does the code exchange and new Clickmax({ clientId, clientSecret, installationId }) handles the installation token. See Use Clickmax App credentials.