FlexpaFlexpa
Developer PortalGet a DemoTry it yourself

All docs

Why headless consent

  • The tradeoffs

How it works

  • What you need

Build your consent screen

  • Consent screen requirements
  • Share a screenshot
  • Recording the time

Find the organization

  • Search
  • Calling it from the browser or your server
  • Showing results
  • Answering what the result requires

Push the request

  • Before you push: PKCE and state
  • Push parameters
  • The push response
  • Push errors

Send the patient to authorize_url

  • Mobile apps

What the patient sees

    Handle the return

    • flexpa_error values
    • When nothing comes back

    Exchange the code

      Search mode walkthrough

        IAL2 walkthrough

        • Wait for the record search
        • Sign-in facilities found during the search

        Connect more facilities

        • Sending a follow-up push
        • Exchanging a follow-up code
        • Pushing twice for the same facility
        • Revoked consents

        Parity with the Consent UI

          Test it

            Go live

              Next steps

                Headless consent guide

                Headless consent lets your application run the whole patient experience of connecting health records in your own UI. Your app collects the patient's consent, helps them find their health plan or provider, and asks any questions up front. Your server then pushes the request to Flexpa, and the patient goes straight to the sign-in page of that health plan, provider or identity provider. They come back to your app with an authorization code. In most cases the patient never sees a Flexpa screen.

                This guide walks you through building it from start to finish:

                1. Build your consent screen, which Flexpa reviews before you go live
                2. Find the organization with the Organization search API
                3. Push the request from your server
                4. Send the patient to Flexpa and handle their return
                5. Exchange the code for tokens
                6. Run a search mode or an IAL2 connection
                7. Connect more facilities to the same consent

                Early access preview. Headless consent and the Organization search API are available to a small number of customers before the full rollout. Some parameters, fields and behaviors described here could change before then. We will tell you ahead of any change that affects your integration.


                #Why headless consent

                Flexpa Consent is a hosted flow. You send the patient to Flexpa, and Flexpa's screens ask everything: the terms, which health plan or provider, which plan type, the patient's name and date of birth. It is the fastest way to integrate, and it is the right choice for most applications.

                Headless consent exists for applications that want control of their own user experience. Your app already knows a lot about the patient, has its own look and voice, and may want to ask questions in a different order or in a different form, such as a chat or an onboarding checklist. With headless consent you draw every screen yourself, and Flexpa runs only the parts that must happen at Flexpa: the sign-in, the identity check and the record retrieval.

                #The tradeoffs

                That control comes with more work and a few limits. Read these before you choose headless consent.

                • You build more. You build the consent screen, the search, the plan type and state questions, the error handling and the "connect another facility" flow. The hosted Consent UI does all of this for you.
                • Flexpa reviews your consent screen. Your screen replaces Flexpa's own terms screen, so it must meet the requirements below. Live mode stays off until Flexpa approves a screenshot of your flow. Test mode works right away.
                • One connection per search visit. In the Consent UI a patient can connect several health plans and providers in one visit. A headless search mode visit connects one. (An IAL2 visit connects every facility it finds that needs no sign-in.) You add more with follow-up pushes, and each one gives you a new token pair.
                • Some screens are still Flexpa's. If your push does not answer a question, such as the patient's plan type or date of birth, the patient sees a Flexpa screen for it. A few health plans also sign the patient in on a Flexpa screen instead of their own page. What the patient sees explains each case.
                • You handle every ending. Every way a visit ends comes back to your redirect_uri, and your app decides what to show. A patient who closes the window sends nothing back at all.
                • IAL2 has fewer identity options. A headless IAL2 visit can use CLEAR or ID.me. Persona is not available.
                • You keep your UI up to date. Improvements to the Consent UI reach hosted patients on their own. With headless consent, your UI is yours to change.
                Consent UIHeadless consent
                Who draws the screensFlexpaYou
                Consent and terms screenFlexpa'sYours, reviewed by Flexpa
                Search for a health plan or providerBuilt inYou call Organization search
                Plan type and state questionsBuilt inYou ask, or Flexpa asks
                Sources per visitSeveralOne, then follow-ups
                IAL2 identity providersCLEAR, ID.me, PersonaCLEAR, ID.me
                Live modeAny timeAfter Flexpa reviews your screen

                Not sure? Start with the hosted Flexpa Consent flow. You can move to headless consent later without changing how you exchange codes or fetch records.


                #How it works

                A search mode connection goes like this. Each step is one message, in order.

                1. Your app shows your consent screen. The patient checks the box to opt in, and your app records the time.
                2. Your app calls GET /rest/organizations/search as the patient types, and the patient picks their health plan or provider from your results.
                3. Your app asks any questions the result still needs, such as the plan type.
                4. Your server sends POST /oauth/par to Flexpa with everything the patient told you. Flexpa replies with an authorize_url.
                5. Your server sends the patient's browser to authorize_url.
                6. Flexpa sends the patient straight on to the sign-in page of their health plan or provider.
                7. The patient signs in there. The health plan or provider sends them back to Flexpa.
                8. Flexpa sends the patient to your redirect_uri with a code, or with an error that says why it ended.
                9. Your server exchanges the code at POST /oauth/token for an access token, and fetches records with it.

                An IAL2 connection is the same, except the patient verifies their identity with CLEAR or ID.me instead of signing in to one organization. Flexpa then searches the TEFCA network for every facility that holds the patient's records. See the IAL2 walkthrough.

                #What you need

                • A pair of API Keys from the Flexpa Portal: the publishable key (pk_...) and the secret key (sk_...). Keep the secret key on your server.
                • A redirect URI registered in the Flexpa Portal for each mode you use.
                • A server. Pushes are authenticated with your secret key, so they can never be sent from a browser or a mobile app.
                • For IAL2: a webhook registered in the Flexpa Portal, or polling of GET /rest/consent/:consentId, so you learn which facilities need a sign-in and when the record search ends.
                • For live mode: Flexpa's approval of your consent screen. See Go live.
                Search mode, in order: the patient opts in, searches, and picks in your app; your app calls GET /rest/organizations/search on Flexpa and asks your server to connect; your server sends POST /oauth/par and gets authorize_url; the patient is sent to authorize_url, then to the health plan's sign-in, then back to your redirect_uri with a code; your server exchanges the code at POST /oauth/token for an access_token.

                #Build your consent screen

                In the hosted flow, Flexpa's first screen asks every patient to agree to Flexpa's Terms and Privacy Policy. A headless push skips that screen, so your app must collect the same consent before you push. You send Flexpa the moment the patient opted in, and Flexpa records it on the consent.

                #Consent screen requirements

                Your consent screen must do all of the following. Flexpa checks each one when it reviews your screen.

                1. Say that you use Flexpa. State plainly that your app uses Flexpa to help the patient share their health records with you.
                2. Say that Flexpa does not sell personal information. For example: "Flexpa does not sell your personal information."
                3. Say that the patient can revoke access at any time. For example: "You can revoke access at any time." Patients can revoke through Flexpa at Revoking access, and you can revoke a consent for them with the Revoke endpoint.
                4. Link Flexpa's Terms and Privacy Policy. Link to flexpa.com/terms and flexpa.com/privacy.
                5. Get an explicit opt-in. The patient must take a clear action to agree, such as checking a box that starts unchecked, or tapping a button whose label says they agree. Leaving the screen, scrolling, or a box that is checked by default does not count. The patient must also be free to say no.
                6. Record when the patient opted in. Save the exact time the patient agreed, and send it as flexpa_consented_at on every push. Flexpa rejects a push without it.

                #Share a screenshot

                Once your consent screen is built, send Flexpa screenshots of the whole flow for review, from your consent screen to the moment the patient leaves for Flexpa. Flexpa reviews them and turns on headless consent in live mode for your workspace. Until then, a live mode push fails with 403 unauthorized_client. Test mode is never gated, so you can build and test everything first.

                If you change the wording or the flow of your consent screen later, send new screenshots.

                #Recording the time

                flexpa_consented_at is an RFC 3339 timestamp, such as 2026-01-31T14:03:22Z.

                • Take it when the patient opts in, not when you push. Store it with the patient's record in your own database.
                • It cannot be later than the push. Flexpa allows no clock drift, so keep your server clock accurate, and take the time on your server rather than trusting the device clock.
                • It cannot be more than a year old. A follow-up push sends the patient's latest opt-in time, which is the first push's time until they opt in again. When it is close to a year old, show your consent screen again and send the new time.
                • Flexpa returns it as consentedAt on the Consent endpoint.

                Example consent screen (React)

                function ConnectRecordsConsent({ onAgree }: { onAgree: () => void }) {
                  const [checked, setChecked] = useState(false);
                
                  return (
                    <form
                      onSubmit={(event) => {
                        event.preventDefault();
                        if (checked) onAgree();
                      }}
                    >
                      <h2>Connect your health records</h2>
                      <p>
                        Acme Health uses Flexpa to help you share your health
                        records with us.
                      </p>
                      <ul>
                        <li>Flexpa does not sell your personal information.</li>
                        <li>You can revoke access at any time.</li>
                      </ul>
                      <label>
                        <input
                          type="checkbox"
                          checked={checked}
                          onChange={(event) => setChecked(event.target.checked)}
                        />
                        I agree to use Flexpa to share my health records with Acme
                        Health, and to Flexpa's{' '}
                        <a href="https://www.flexpa.com/terms" target="_blank">Terms</a>{' '}
                        and{' '}
                        <a href="https://www.flexpa.com/privacy" target="_blank">
                          Privacy Policy
                        </a>
                        .
                      </label>
                      <button type="submit" disabled={!checked}>
                        Agree and continue
                      </button>
                      <button type="button">Not now</button>
                    </form>
                  );
                }
                

                Record the opt-in on your server

                app.post('/consent/opt-in', requireUser, async (req, res) => {
                  // Your server's clock, to the second, in UTC
                  const consentedAt = new Date().toISOString().replace(/\.\d{3}Z$/, 'Z');
                
                  await db.flexpaConsent.create({
                    data: { userId: req.user.id, consentedAt },
                  });
                
                  res.sendStatus(204);
                });
                

                These words are an example. Use your own app's voice, as long as every requirement on the left is met.


                #Find the organization

                In search mode, the patient tells you which health plan or provider to connect. The Organization search API turns what they type into an organization to show and an endpoint to connect through. Build a search box, a typeahead, or an agent tool on top of it.

                A result has two organizations:

                • organization is the one that matched the patient's words, such as a brand ("Aetna") or a facility ("Ingen Clinic"). Show this one to the patient.
                • connectingOrganization is the one that owns the endpoint the patient signs in through. For a facility it is the parent brand. For a brand it is the same organization as organization.

                Either organization.id or connectingOrganization.id works as flexpa_organization_id on the push, and both lead to the same questions.

                #Search

                GET https://api.flexpa.com/rest/organizations/search

                Query parameters

                qstring

                The patient's words, up to 200 characters. Every word is looked for in the organization's name, aliases and address. Punctuation is ignored, one-letter words are dropped, and only the first 6 words are searched. q needs a word of 3 or more letters other than "the", "and" or "for", or the page is empty. Optional when you send a filter below, which returns a browse list of brands instead.

                modeenum

                LIVE (default) or TEST. Use TEST while you build against test mode keys.

                typeenum

                PAYER for health plans or PROVIDER for providers.

                statestring

                Two-letter US state. With q it ranks matches in that state first. Without q it filters the browse list.

                postalCodestring

                3 to 5 digits. Ranks results near that ZIP code first. Requires q.

                lineOfBusinessenum

                Keep only health plans that connect that plan type: EMPLOYER, OFF_EXCHANGE, MEDICARE_ADV, ON_EXCHANGE or MEDICAID.

                isBCBSboolean

                true keeps only Blue Cross Blue Shield plans.

                matchOnstring

                Which fields q may match: name, alias, address, or a comma list. Default: all three.

                connectableOnlyboolean

                true drops results the patient cannot connect to right now. Default false.

                limitinteger

                Results to return, 1 to 50. Default 20. There is no next page: ask the patient to type more.

                Any other query parameter returns 400, so a typo never quietly returns an unfiltered list.

                #Calling it from the browser or your server

                • From the browser, no key is needed. The limit is 60 requests a minute for each IP address. Wait at least one second after the patient stops typing before you search.
                • From your server, every patient shares your server's IP address, so send an Application Access Token as Authorization: Bearer <token>. The limit is then 600 requests a minute for your application, and the search runs in the token's mode. Leave out mode, or send the token's mode: a different one returns 400.

                A 429 means you hit the limit. All application tokens together also share a cap, so a 429 can come before your own limit during a spike. Wait for the seconds in the retry-after header, then try again.

                Request

                curl "https://api.flexpa.com/rest/organizations/search?q=ingen%20clinic&state=CO&mode=TEST"
                

                One result

                {
                  "organization": {
                    "id": "1f4a2c0e-6b1d-4a8e-9c3f-0d2b7e5a9c11",
                    "name": "Ingen Clinic",
                    "type": "PROVIDER",
                    "address": { "city": "Boulder", "state": "CO", "...": "..." }
                  },
                  "connectingOrganization": {
                    "id": "7c9e1b2a-3d4f-4e5a-8b6c-1a2b3c4d5e6f",
                    "name": "Cyberdine Health Systems",
                    "type": "PROVIDER"
                  },
                  "endpoint": {
                    "id": "d39433b7-0fbd-4bc2-bdae-fb276799979f",
                    "label": "MyChart",
                    "logoUrl": "https://cdn.flexpa.com/logos/d39433b7-..."
                  },
                  "partial": false,
                  "available": true,
                  "requires": {
                    "lineOfBusiness": [],
                    "state": {},
                    "searchKey": false,
                    "tenantChoice": false
                  },
                  "tenantEndpointIds": null
                }
                

                #Showing results

                Result fields to use

                organizationobject

                What to show: name, type, address (line1, city, state, postalCode, each null when unknown) and aka (other names).

                connectingOrganizationobject

                Who the patient signs in with. When its id differs from organization.id, you can show "via connectingOrganization.name", because the sign-in page will carry that name.

                endpointobject

                The connection itself. Show logoUrl as the logo, and hide the image if it fails to load: not every endpoint has one. label is a display label such as "MyChart", or null.

                partialboolean

                true when nothing matched every word and this result matched only some of them. Consider showing these under a "Did you mean" heading.

                availableboolean

                Whether the patient can connect here right now. Show unavailable results greyed out, or drop them with connectableOnly=true. Flexpa rejects a push for an unavailable endpoint.

                requiresobject

                The questions you still need to answer before the push. See below.

                tenantEndpointIdsarray

                When requires.tenantChoice is true, the endpoint IDs of every same-named organization, oldest first. Otherwise null. Push one as flexpa_endpoint_id.

                #Answering what the result requires

                requires tells you what the Consent UI would have asked next. Ask the patient yourself and send the answers on the push, and the patient skips those Flexpa screens.

                • requires.lineOfBusiness: the plan types Flexpa connects for this health plan. If it is not empty, ask the patient which plan type they have, even when only one is listed, and send it as flexpa_line_of_business. If their plan type is not in the list, they cannot connect through this result.
                • requires.state: for each plan type whose connection depends on where the patient lives, the states that connect differently. If the patient's plan type has an entry, ask which state they live in, from all US states, not only the listed ones, and send it as flexpa_state.
                • requires.tenantChoice: several organizations share this name and nothing tells them apart. A push with organization.id connects the top-ranked one, and Flexpa does not ask the patient to pick. To connect a different one, push flexpa_endpoint_id set to another entry of tenantEndpointIds, for example after the first sign-in ends with sign_in_failed.
                • requires.searchKey: several organizations share this name and only a vendor office key tells them apart. A push with organization.id connects the top-ranked office, and Flexpa does not ask the patient to pick.
                Plan type valueAsk it as
                EMPLOYERInsurance through an employer
                OFF_EXCHANGEAn individual plan bought outside the marketplace
                ON_EXCHANGEA marketplace (ACA) plan
                MEDICARE_ADVMedicare Advantage
                MEDICAIDMedicaid

                Blue Cross Blue Shield is a group of independent companies. When a patient types "BCBS" or "Blue Cross", ask which state their plan is in, or search with isBCBS=true&state=XX.

                A health plan that needs a plan type

                "requires": {
                  "lineOfBusiness": ["MEDICARE_ADV", "MEDICAID", "EMPLOYER"],
                  "state": { "MEDICARE_ADV": ["CA", "TX"] },
                  "searchKey": false,
                  "tenantChoice": false
                }
                

                Turn a result into push answers

                type PushAnswers = {
                  flexpa_organization_id?: string;
                  flexpa_endpoint_id?: string;
                  flexpa_line_of_business?: string;
                  flexpa_state?: string;
                };
                
                async function answersFor(result: SearchResult): Promise<PushAnswers> {
                  const answers: PushAnswers = {};
                
                  // Connects the top-ranked organization. When requires.tenantChoice is true and
                  // that sign-in fails, push again with another of result.tenantEndpointIds
                  // as flexpa_endpoint_id.
                  answers.flexpa_organization_id = result.organization.id;
                
                  if (result.requires.lineOfBusiness.length > 0) {
                    const planType = await askPlanType(result.requires.lineOfBusiness);
                    answers.flexpa_line_of_business = planType;
                
                    if (result.requires.state[planType]) {
                      // Ask from every US state, not only the listed ones
                      answers.flexpa_state = await askState();
                    }
                  }
                
                  return answers;
                }
                
                StatusWhen
                400A parameter is unknown, out of range or missing
                401The access token is invalid or expired
                403You sent a Patient Access Token; send an Application Access Token or none
                429Too many requests; wait for retry-after

                #Push the request

                When the patient is ready to connect, your server pushes the request to Flexpa with a pushed authorization request (RFC 9126). The push carries everything the patient told you, so none of it travels in the browser's address bar, and the patient skips every screen the push answers.

                POST https://api.flexpa.com/oauth/par

                Authenticate with HTTP Basic auth: your publishable key as the username and your secret key as the password. Send the body as application/x-www-form-urlencoded or JSON.

                #Before you push: PKCE and state

                Every push needs a PKCE code challenge, and should carry a state value.

                1. Create a random code_verifier and a random state on your server.
                2. Store both in the patient's own browser session, one entry per state, not in a shared server-side table. The session must be signed and encrypted, as an HttpOnly cookie, or kept server-side behind a session cookie.
                3. Send code_challenge (the SHA-256 of the verifier) and state on the push.

                A push belongs to whichever browser opens its authorize_url first, and the code comes back to that browser. Keeping state and the verifier in that browser's session means a link the patient forwards to someone else can never finish in your patient's account.

                Start the push from the same origin as your redirect_uri. A browser sends a cookie only to the host that set it, so a flow started on localhost with a redirect_uri on a tunnel such as ngrok returns to a callback that cannot read the session.

                Your server: start a connection

                import crypto from 'node:crypto';
                
                const base64url = (buffer: Buffer) => buffer.toString('base64url');
                
                app.post('/connect', requireUser, async (req, res) => {
                  const codeVerifier = base64url(crypto.randomBytes(32));
                  const codeChallenge = base64url(
                    crypto.createHash('sha256').update(codeVerifier).digest(),
                  );
                  const state = base64url(crypto.randomBytes(16));
                
                  // A follow-up push names a consent this patient already has
                  const followUp = await ownedConsent(req.user.id, req.body.consentId);
                  if (followUp === null) return res.sendStatus(404);
                
                  // Every push sends the patient's latest opt-in time
                  const optIn = await db.flexpaConsent.findLatest(req.user.id);
                  // Missing or close to a year old: show your consent screen again
                  if (!optIn || Date.now() - Date.parse(optIn.consentedAt) > REASK_AFTER_MS) {
                    return res.redirect(303, '/consent');
                  }
                  const { consentedAt } = optIn;
                
                  const push = await pushToFlexpa({
                    // Patient answers first, so the server-owned fields below always win
                    ...pickAnswers(req.body.answers), // from answersFor() above
                    ...(followUp ? { flexpa_consent_id: followUp.consentId } : {}),
                    state,
                    code_challenge: codeChallenge,
                    flexpa_external_id: req.user.id,
                    flexpa_consented_at: consentedAt,
                  });
                
                  // Kept in this browser's session, one entry per state, checked on return
                  req.session.flexpa = pruneExpired(req.session.flexpa ?? {});
                  req.session.flexpa[state] = {
                    userId: req.user.id,
                    consentId: push.consent_id,
                    codeVerifier,
                    createdAt: Date.now(),
                  };
                
                  // Send this same browser on to Flexpa
                  res.redirect(303, push.authorize_url);
                });
                
                // No consentId sent: undefined, a first consent. Otherwise the stored row,
                // only if it is this user's and not revoked. Anything else is null: reject
                // the request, never fall back to a new consent. Set revokedAt when you
                // revoke the consent or a patient returns with consent_revoked.
                async function ownedConsent(userId: string, consentId: unknown) {
                  if (consentId === undefined) return undefined;
                  if (typeof consentId !== 'string') return null;
                  return db.flexpaTokens.findFirst({ where: { consentId, userId, revokedAt: null } });
                }
                
                type SavedPush = {
                  userId: string;
                  consentId: string;
                  codeVerifier: string;
                  createdAt: number;
                };
                
                const ANSWER_KEYS = [
                  'flexpa_organization_id',
                  'flexpa_endpoint_id',
                  'flexpa_line_of_business',
                  'flexpa_state',
                ] as const;
                
                function isRecord(value: unknown): value is Record<string, unknown> {
                  return typeof value === 'object' && value !== null;
                }
                
                // Keep only the PushAnswers fields the browser may set, and only strings
                function pickAnswers(input: unknown): PushAnswers {
                  const answers: PushAnswers = {};
                  if (!isRecord(input)) return answers;
                  for (const key of ANSWER_KEYS) {
                    const value = Object.hasOwn(input, key) ? input[key] : undefined;
                    if (typeof value === 'string') answers[key] = value;
                  }
                  return answers;
                }
                
                // Longer than Flexpa's 30-minute visit limit, so a late return still matches
                const SAVED_FOR_MS = 60 * 60 * 1000;
                
                const REASK_AFTER_MS = 330 * 24 * 60 * 60 * 1000; // about 11 months, before Flexpa's one-year limit
                
                // Drop saved entries older than SAVED_FOR_MS, and keep only the newest 4
                // so the new one makes 5 and a cookie session stays small
                function pruneExpired(saved: Record<string, SavedPush>) {
                  return Object.fromEntries(
                    Object.entries(saved)
                      .filter(([, entry]) => Date.now() - entry.createdAt < SAVED_FOR_MS)
                      .sort(([, a], [, b]) => b.createdAt - a.createdAt)
                      .slice(0, 4),
                  );
                }
                

                #Push parameters

                Always

                client_idstringRequired

                Your publishable key. Must be the same key you authenticate with.

                response_typestringRequired

                Always code.

                redirect_uristringRequired

                Where Flexpa sends the patient back. Must exactly match a redirect URI registered for this mode.

                code_challengestringRequired

                The base64url SHA-256 of your code_verifier, 43 characters.

                code_challenge_methodstringRequired

                Always S256.

                scopestringRequired

                launch/patient, plus offline_access if you want a refresh token for ongoing access. See Scopes.

                flexpa_external_idstringRequired

                Your own ID for this patient. Flexpa returns it on webhooks.

                flexpa_consented_atstringRequired

                When the patient opted in on your consent screen. See Recording the time.

                statestring

                Your random value, up to 512 characters. Flexpa returns it on every redirect. Strongly recommended.

                Search mode

                flexpa_organization_idstring

                organization.id or connectingOrganization.id from a search result. The patient skips Flexpa's search screen and goes to that organization's sign-in. If the organization cannot be connected in this mode, the push fails with The organization is not connectable.

                flexpa_endpoint_idstring

                An endpoint ID instead, such as one of tenantEndpointIds. Skips the search screen the same way. Cannot be sent with flexpa_organization_id.

                flexpa_line_of_businessenum

                The patient's plan type, one of requires.lineOfBusiness. Skips the plan type screen. Requires flexpa_organization_id or flexpa_endpoint_id. A plan type the health plan does not connect is rejected, and so is any plan type for a provider.

                flexpa_statestring

                The patient's two-letter US state. Skips the state screen. Requires flexpa_line_of_business, and is accepted only when the health plan asks about the state for that plan type (requires.state has an entry for it). Any state is accepted then.

                flexpa_hint_first_namestring

                The patient's first name.

                flexpa_hint_last_namestring

                The patient's last name.

                flexpa_hint_dobstring

                The patient's date of birth, YYYY-MM-DD. With all three hints the patient skips Flexpa's demographics screen.

                flexpa_default_filterenum

                PAYER or PROVIDER. Only matters when the patient lands on Flexpa's search screen, which opens filtered to that kind.

                flexpa_consent_idstring

                A follow-up push: the consent to add one more facility to. See Connect more facilities.

                IAL2 mode

                flexpa_ial2_modestring

                true starts the IAL2 flow. Cannot be sent with an organization, endpoint, plan type, state, hints or flexpa_consent_id.

                flexpa_identity_providerenum

                clear (default) or idme. The patient goes straight to that identity provider. It must be enabled for your application.

                flexpa_qhin_networkenum

                COMMONWELL or KNO2: the TEFCA network the record search runs on. Optional.

                flexpa_resume, flexpa_chatbot_mode, id_token_hint, request and request_uri are not accepted on a push. flexpa_search_mode is accepted and ignored: every push without flexpa_ial2_mode is a search mode push.

                pushToFlexpa

                const FLEXPA_PK = process.env.FLEXPA_PUBLISHABLE_KEY!;
                const FLEXPA_SK = process.env.FLEXPA_SECRET_KEY!;
                
                async function pushToFlexpa(params: Record<string, string>) {
                  const response = await fetch('https://api.flexpa.com/oauth/par', {
                    method: 'POST',
                    headers: {
                      Authorization:
                        'Basic ' + Buffer.from(`${FLEXPA_PK}:${FLEXPA_SK}`).toString('base64'),
                      'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                      ...params,
                      // Fixed fields last, so params can never override them
                      client_id: FLEXPA_PK,
                      response_type: 'code',
                      redirect_uri: 'https://example.com/flexpa/callback',
                      code_challenge_method: 'S256',
                      scope: 'launch/patient offline_access',
                    }),
                  });
                
                  const body = await response.json();
                  if (response.status !== 201) {
                    // For example 400 invalid_request "flexpa_consented_at is required: ..."
                    throw new FlexpaPushError(
                      response.status,
                      body.error,
                      body.error_description ?? body.message,
                    );
                  }
                  return body as {
                    request_uri: string;
                    expires_in: number;
                    authorize_url: string;
                    consent_id: string;
                    requires: {
                      lineOfBusiness: string[];
                      state: Record<string, string[]>;
                      searchKey: boolean;
                      tenantChoice: boolean;
                    };
                  };
                }
                

                cURL

                curl -X POST https://api.flexpa.com/oauth/par \
                  -u "pk_test_...:sk_test_..." \
                  -d client_id=pk_test_... \
                  -d response_type=code \
                  -d redirect_uri=https://example.com/flexpa/callback \
                  -d code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM \
                  -d code_challenge_method=S256 \
                  -d "scope=launch/patient offline_access" \
                  -d state=af0ifjsldkj \
                  -d flexpa_external_id=user-123 \
                  -d flexpa_consented_at=2026-01-31T14:03:22Z \
                  -d flexpa_organization_id=7c9e1b2a-3d4f-4e5a-8b6c-1a2b3c4d5e6f \
                  -d flexpa_line_of_business=MEDICARE_ADV \
                  -d flexpa_hint_first_name=Jane \
                  -d flexpa_hint_last_name=Doe \
                  -d flexpa_hint_dob=1990-05-15
                

                #The push response

                A push that works returns 201.

                Response fields

                authorize_urlstring

                Where to send the patient's browser.

                request_uristring

                The single-use handle inside authorize_url.

                expires_innumber

                600. The patient must open authorize_url within 10 minutes.

                consent_idstring

                The consent this visit will create, or on a follow-up push the consent it adds to. Save it with the patient.

                requiresobject

                The questions your push did not answer, which Flexpa will ask on its own screens: lineOfBusiness and state. Empty lists mean the patient sees no Flexpa question. searchKey and tenantChoice are always false on a push, because the push names one endpoint. Demographics are not listed here: a first search mode push without all three flexpa_hint_* values always shows Flexpa's demographics screen.

                Check requires before you send the patient. If anything is listed, you can ask the patient yourself and push again with the answer. A push nobody opens creates no consent: its consent_id returns 404 until the patient opens authorize_url.

                #Push errors

                A failed push returns an RFC 6749 error body with error and error_description. These are for you, not the patient: log them and show the patient a general error.

                StatuserrorWhen
                400invalid_requestA parameter is missing, invalid or conflicts with another. error_description names it.
                400invalid_scopeThe scope is not allowed, or a follow-up's scope differs from the consent's.
                400unsupported_response_typeresponse_type is not code.
                400request_not_supportedThe body has a request object. Signed request objects are not supported.
                401invalid_clientThe Basic credentials are missing or wrong.
                403unauthorized_clientYour application is not licensed for this flow, or live mode is not yet enabled for headless consent.
                413Payload Too LargeThe body is larger than 8 KB.
                415Unsupported Media TypeThe body is not form-encoded or JSON.
                429Too Many RequestsMore than 50 pushes a minute from one application in one mode, or 20 failed logins a minute from one IP address.

                413, 415 and 429 bodies have message instead of error_description.

                201 Created

                {
                  "request_uri": "urn:ietf:params:oauth:request_uri:6esc_11ACC5bwc014ltc14eY22cqPq2Ms0f4Bk9nWdX",
                  "expires_in": 600,
                  "authorize_url": "https://api.flexpa.com/oauth/authorize?client_id=pk_test_...&request_uri=urn%3Aietf%3Aparams%3Aoauth%3Arequest_uri%3A6esc_11ACC5bwc014ltc14eY22cqPq2Ms0f4Bk9nWdX",
                  "consent_id": "4b2a9c1e-7d3f-4a8b-9e6c-2f1d0a9b8c7d",
                  "requires": {
                    "lineOfBusiness": [],
                    "state": {},
                    "searchKey": false,
                    "tenantChoice": false
                  }
                }
                

                400 Bad Request

                {
                  "error": "invalid_request",
                  "error_description": "flexpa_line_of_business requires flexpa_organization_id or flexpa_endpoint_id"
                }
                

                #Send the patient to authorize_url

                Redirect the patient's browser to authorize_url right after the push. Flexpa sends them straight on to the sign-in page or identity provider. They may see a blank page for a moment while Flexpa gets ready, but no Flexpa screen unless the push left a question open.

                • Push right before you redirect. The link expires after 10 minutes and works once. Do not push ahead of time, and do not email or text authorize_url.
                • Keep the patient in one browser. Only the browser that started a sign-in can finish it. If a health plan's sign-in sends an email link that opens in a different browser, the visit ends with flexpa_error=different_browser.
                • Opening it again in the same browser returns the patient to the visit in progress. Opening it after the visit ended, or in another browser, returns error=invalid_request_uri.
                • One visit per browser at a time. If the same browser opens a newer push, the older visit ends with flexpa_error=superseded when its patient returns. The newer one carries on.

                #Mobile apps

                Open authorize_url in the system's authentication browser: ASWebAuthenticationSession on iOS, or Custom Tabs on Android. Do not use an embedded web view. Many health plans block sign-in inside web views, and a web view does not share cookies with the browser. See Mobile applications for redirect URI setup.

                What the patient sees

                Your app: "Connect Aetna"  →  (blank page, briefly)
                  →  Aetna's own sign-in page
                  →  back in your app
                

                #What the patient sees

                Flexpa shows a screen only when it needs something from the patient that your push did not give. Each screen looks like Flexpa's hosted Consent UI, not like your app. Answer everything you can in the push and most patients never see one.

                Flexpa screenWhen the patient sees itHow to skip it
                TermsNever on a pushYour consent screen and flexpa_consented_at replace it
                SearchSearch mode push without an organization or endpointSend flexpa_organization_id or flexpa_endpoint_id
                Plan typeThe health plan connects more than one plan type and the push did not say whichSend flexpa_line_of_business
                StateThe plan type connects differently by state and the push did not say whichSend flexpa_state
                DemographicsFirst search mode push without all three hints. Partial hints pre-fill it. Follow-ups and IAL2 never show it.Send flexpa_hint_first_name, flexpa_hint_last_name and flexpa_hint_dob
                Plan sign-inA few health plans sign the patient in on a Flexpa screen instead of their own pageCannot be skipped
                Identity provider choiceNever on a pushflexpa_identity_provider, or CLEAR by default
                Review and shareNever on a pushFlexpa shares the connection as soon as it is ready

                Every Flexpa screen has a Back button and a close button. If the patient leaves with either, they come back to your redirect_uri with flexpa_error=member_cancelled, and nothing is connected.

                Always send an organization or endpoint on a search mode push. Without one the patient lands on Flexpa's search screen, which defeats the point of a headless flow, and a follow-up push cannot be sent without one at all.


                #Handle the return

                Every visit ends at your redirect_uri, with a code when it worked or with an error when it did not. Both carry your state.

                1. Read state from the query, and look up the saved entry for that state in this browser's session. If there is none, it was saved for a different user, or it is older than the limit, stop: do not exchange anything. The one exception is error=invalid_request_uri with no saved entry: that is a reopened link, so send the patient on without an error.
                2. Delete that entry, so a reload cannot use it again.
                3. If there is a code, exchange it with the code_verifier from that entry, under the consent's lock, and replace that consent's stored token pair. See Store one pair per consent.
                4. If there is an error, read flexpa_error to decide what to tell the patient. superseded is not a failure, so show no error for it. Do not show error_description to patients and do not branch on it: its wording can change.

                Error redirect parameters

                errorstring

                The OAuth error: access_denied, temporarily_unavailable, server_error, invalid_request or invalid_request_uri.

                flexpa_errorstring

                Flexpa's reason. Branch on this. See the table below.

                error_descriptionstring

                A sentence for your logs.

                error_uristring

                A link to Flexpa's error documentation.

                statestring

                The state you pushed.

                issstring

                Flexpa's issuer URL. Also sent with a code.

                Two errors come without flexpa_error, because they happen before the visit starts:

                • error=invalid_request_uri: the link was already used or expired. It can arrive after a visit already finished, when the patient opens the link again. Never let it override a code you already received for that state.
                • error=invalid_request or invalid_scope: the request no longer holds when the patient opens it, for example the facility is already connected. error_description says why.

                It worked

                https://example.com/flexpa/callback
                  ?code=public_token_...
                  &state=af0ifjsldkj
                

                It ended

                https://example.com/flexpa/callback
                  ?error=access_denied
                  &error_description=The+patient+left+before+finishing
                  &error_uri=https%3A%2F%2Fflexpa.com%2Fdocs%2Fconsent%23error-codes
                  &flexpa_error=member_cancelled
                  &state=af0ifjsldkj
                

                Your server: the callback

                app.get('/flexpa/callback', requireUser, async (req, res) => {
                  const pending = req.session.flexpa ?? {};
                  const state = typeof req.query.state === 'string' ? req.query.state : '';
                  const saved = Object.hasOwn(pending, state) ? pending[state] : undefined;
                
                  // A reopened link after its visit ended: never override a code already received
                  if (!saved && req.query.error === 'invalid_request_uri') {
                    return res.redirect('/connect');
                  }
                
                  // Missing, someone else's, malformed or expired; other entries stay untouched
                  if (
                    !saved ||
                    saved.userId !== req.user.id ||
                    typeof saved.consentId !== 'string' ||
                    typeof saved.codeVerifier !== 'string' ||
                    !Number.isFinite(saved.createdAt) ||
                    Date.now() - saved.createdAt >= SAVED_FOR_MS
                  ) {
                    return res.redirect('/connect?problem=session_lost');
                  }
                  delete pending[state];
                
                  if (typeof req.query.code === 'string') {
                    // First consent or follow-up: one path, under the consent's lock
                    await exchangeAndStore(saved, req.query.code);
                    return res.redirect('/records?connected=1');
                  }
                
                  // Not a failure: the newer visit returns on its own
                  if (req.query.flexpa_error === 'superseded') return res.redirect('/connect');
                
                  const reason = String(req.query.flexpa_error ?? req.query.error);
                  return res.redirect(`/connect?problem=${encodeURIComponent(reason)}`);
                });
                

                #flexpa_error values

                flexpa_error values

                member_cancelled

                error: access_denied

                What happened: The patient left a Flexpa screen with Back or close.

                What to do: Let them try again. Answer more in the push, such as flexpa_line_of_business.

                sign_in_failed

                error: access_denied

                What happened: The patient's sign-in with the organization failed or was refused.

                What to do: Let them try again. On a follow-up, the consent is unchanged.

                identity_abandoned

                error: access_denied

                What happened: IAL2: the patient cancelled at the identity provider.

                What to do: Let them try again.

                identity_failed

                error: access_denied

                What happened: IAL2: the identity provider could not verify the patient.

                What to do: Offer the other identity provider, or the search mode flow.

                expired

                error: access_denied

                What happened: The patient did not finish a step in time.

                What to do: Push again.

                different_browser

                error: access_denied

                What happened: The sign-in finished in a different browser than the one that started it.

                What to do: Push again and ask the patient to stay in one browser.

                superseded

                error: access_denied

                What happened: A newer push replaced this one: the same browser opened a newer push, or you pushed a newer follow-up for the same facility.

                What to do: Nothing. The newer visit returns on its own.

                consent_revoked

                error: access_denied

                What happened: Follow-up only: the consent was revoked while the patient was signing in.

                What to do: Start a new consent.

                no_records

                error: access_denied

                What happened: IAL2, rare: identity passed but the search found nothing before the patient could be returned.

                What to do: Tell the patient no records were found.

                record_search_failed

                error: access_denied

                What happened: IAL2, rare: the network search failed before the patient could be returned.

                What to do: Ask the patient to try again later.

                timed_out

                error: temporarily_unavailable

                What happened: Flexpa could not get the patient to the next step within 20 seconds.

                What to do: Push again.

                routing_failed

                error: temporarily_unavailable

                What happened: Flexpa could not check how to reach the organization.

                What to do: Push again.

                internal_error

                error: server_error

                What happened: A step on Flexpa's side failed. The patient did nothing wrong.

                What to do: Push again.

                Treat any flexpa_error you do not recognize as "something went wrong, try again". New values may be added during early access.

                #When nothing comes back

                If the patient closes the window or the app during the sign-in, there is no browser left to redirect, so you get no code and no error. After a few minutes, let the patient start again from your app, but keep the saved state and code_verifier for at least 30 minutes, so a late return can still be exchanged. Flexpa ends a visit nobody returns from after about 15 minutes for IAL2 and about 30 minutes for search mode, and marks a first consent ABANDONED. You can confirm it with List consents and state=ABANDONED.


                #Exchange the code

                Exchange the code at the token endpoint exactly as in the hosted flow: send the code, the same redirect_uri, your publishable key as client_id, and the code_verifier from the browser session. A code works once.

                Save the access_token, the refresh_token (when you asked for offline_access), and the consent_id from the push response. Then fetch records with the access token as described in Records.

                The token response of an IAL2 consent also carries consent_id and facilities_requiring_sign_in. On a headless visit the record search is usually still running, so that list holds only the sign-in facilities the search has found so far. It is often empty, but it can already list facilities when you exchange the code after the search found them. See Wait for the record search.

                exchangeCode

                async function exchangeCode(code: string, codeVerifier: string) {
                  const response = await fetch('https://api.flexpa.com/oauth/token', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                      grant_type: 'authorization_code',
                      client_id: FLEXPA_PK,
                      code,
                      redirect_uri: 'https://example.com/flexpa/callback',
                      code_verifier: codeVerifier,
                    }),
                  });
                  if (!response.ok) throw new Error(`Exchange failed: ${response.status}`);
                  return response.json() as Promise<{
                    access_token: string;
                    refresh_token?: string;
                    expires_in: number;
                    consent_id?: string;
                    facilities_requiring_sign_in?: unknown[];
                  }>;
                }
                

                #Search mode walkthrough

                Search mode connects one health plan or provider that the patient picks. Here is the whole flow for a patient with a Medicare Advantage plan.

                1. Consent. The patient checks the box on your consent screen at 14:03:22 UTC. You save 2026-01-31T14:03:22Z.
                2. Search. The patient types "aetna". Your app calls Organization search and shows the results. The patient picks Aetna.
                3. Questions. The result's requires.lineOfBusiness lists MEDICARE_ADV, MEDICAID and EMPLOYER. You ask "What kind of plan do you have?" and the patient picks Medicare Advantage. requires.state has no entry for MEDICARE_ADV, so you do not ask about the state.
                4. Push. Your server pushes with flexpa_organization_id, flexpa_line_of_business=MEDICARE_ADV and the three hints you already have. The response's requires is empty.
                5. Sign in. You redirect the patient to authorize_url. They land on Aetna's sign-in page and sign in.
                6. Return. The patient comes back to your callback with a code. You check state and exchange the code.
                7. Records. You fetch the patient's records with the access token. Flexpa sends a sync_completed webhook when the first sync finishes.

                To connect another health plan or provider for the same patient later, send a follow-up push instead of starting a new consent.

                The push

                curl -X POST https://api.flexpa.com/oauth/par \
                  -u "pk_test_...:sk_test_..." \
                  -d client_id=pk_test_... \
                  -d response_type=code \
                  -d redirect_uri=https://example.com/flexpa/callback \
                  -d code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM \
                  -d code_challenge_method=S256 \
                  -d "scope=launch/patient offline_access" \
                  -d state=af0ifjsldkj \
                  -d flexpa_external_id=user-123 \
                  -d flexpa_consented_at=2026-01-31T14:03:22Z \
                  -d "flexpa_organization_id=<organization.id>" \
                  -d flexpa_line_of_business=MEDICARE_ADV \
                  -d flexpa_hint_first_name=Jane \
                  -d flexpa_hint_last_name=Doe \
                  -d flexpa_hint_dob=1990-05-15
                

                What changes if you leave something out

                No flexpa_line_of_business  →  Flexpa's plan type screen
                No hints, or only some      →  Flexpa's demographics screen
                No organization or endpoint →  Flexpa's search screen
                

                #IAL2 walkthrough

                IAL2 mode finds records the patient may not know about. The patient verifies their identity once with CLEAR or ID.me, and Flexpa searches the TEFCA network for every facility that holds their records. It returns provider facilities, not health plans.

                The patient does not wait for that search. They return to you with a code as soon as their identity passes. The search keeps running in the background, usually for a few minutes and sometimes much longer, and Flexpa connects every facility it can without a sign-in. Some facilities need the patient to sign in to their own patient portal first. You learn which ones from a webhook as soon as the search finds them, and connect them with follow-up pushes.

                1. Consent. The patient opts in on your consent screen. Tell them they will verify their identity with CLEAR or ID.me, and that you will search for their records across the national network.
                2. Push. Your server pushes with flexpa_ial2_mode=true, and optionally flexpa_identity_provider=idme. Do not send an organization, endpoint, plan type, state or hints: they are rejected in IAL2 mode. Save the consent_id from the response.
                3. Verify. You redirect the patient to authorize_url. They land on the identity provider and verify.
                4. Return. The patient comes back with a code within a few seconds of finishing. Exchange it. Show the patient that you are looking for their records.
                5. Wait for the search. Flexpa sends record_search_sign_in_facilities_found as soon as the search finds facilities that need a sign-in, and record_search_completed when the search ends.
                6. Follow up. For each facility in facilities_requiring_sign_in, offer the patient a "Connect" button that starts a follow-up push.

                #Wait for the record search

                Listen for the record_search_completed webhook. Flexpa sends it for IAL2 consents only, once the search has ended and the patient has authorized the consent. Verify the X-Flexpa-Signature header before you trust it: every follow-up push you start from its list sends the patient to sign in with that organization.

                record_search_completed data

                consent_idstring

                The consent whose search ended. Send it as flexpa_consent_id on a follow-up push.

                external_idstring

                Your flexpa_external_id for the patient.

                statusstring

                completed (it found the patient), no_records (identity was verified but nothing matched) or failed (the network search failed).

                facilities_requiring_sign_inarray

                The facilities that need the patient's own sign-in, each with facility_name to show, connecting_organization (id, name) and endpoint (id, logo_url). Send connecting_organization.id as flexpa_organization_id on a follow-up push. Empty when status is no_records. For failed, it lists the facilities the search found before it failed.

                Flexpa searches the consent again over time, and a later search can find facilities the first one did not. Each search sends its own event with its own event_id. A later search that ends no_records or failed does not undo an earlier completed: keep the facilities you already have. Use event_id to ignore a repeated delivery.

                You can also poll the consent with an Application Access Token at GET /rest/consent/:consentId until recordSearch.status is no longer searching. recordSearch.facilitiesRequiringSignIn lists the same facilities in the search result shape (facilityName, connectingOrganization.id, endpoint.logoUrl). Once a search has completed, it lists the newest completed search's facilities. Before that, it can already list facilities while status is searching, as soon as the search finds them, and it lists them when status is failed. recordSearch appears once the consent is AUTHORIZED or EXCHANGED.

                A search that finds only facilities needing a sign-in is not an error. The consent completes with a code and no records yet, and the records arrive as the patient connects each facility.

                IAL2 push

                curl -X POST https://api.flexpa.com/oauth/par \
                  -u "pk_test_...:sk_test_..." \
                  -d client_id=pk_test_... \
                  -d response_type=code \
                  -d redirect_uri=https://example.com/flexpa/callback \
                  -d code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM \
                  -d code_challenge_method=S256 \
                  -d "scope=launch/patient offline_access" \
                  -d state=af0ifjsldkj \
                  -d flexpa_external_id=user-123 \
                  -d flexpa_consented_at=2026-01-31T14:03:22Z \
                  -d flexpa_ial2_mode=true \
                  -d flexpa_identity_provider=clear
                

                record_search_completed

                {
                  "event_id": "880fb700-2c3d-4e5f-8a9b-0c1d2e3f4a5b",
                  "event": "record_search_completed",
                  "version": 1,
                  "timestamp": 1704067200000,
                  "data": {
                    "mode": "test",
                    "external_id": "user-123",
                    "consent_id": "4b2a9c1e-7d3f-4a8b-9e6c-2f1d0a9b8c7d",
                    "patient_authorization_id": "7c3e9f2a-4b8d-4e1f-9a3c-5d7e8f9a1b2c",
                    "status": "completed",
                    "facilities_requiring_sign_in": [
                      {
                        "facility_name": "Memorial Hospital Central",
                        "connecting_organization": {
                          "id": "3f2e1d0c-9b8a-4766-a5b4-c3d2e1f0a9b8",
                          "name": "UCHealth"
                        },
                        "endpoint": {
                          "id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
                          "logo_url": "https://cdn.flexpa.com/logos/9a8b7c6d-..."
                        }
                      }
                    ]
                  }
                }
                

                Webhook handler

                app.post('/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
                  const payload = req.body.toString('utf8');
                  if (!verifyWebhookSignature(payload, req.headers['x-flexpa-signature'], WEBHOOK_SECRET)) {
                    return res.status(401).send('Invalid signature');
                  }
                
                  const { event_id, event, data } = JSON.parse(payload);
                  if (await alreadyProcessed(event_id)) return res.sendStatus(200);
                
                  if (event === 'record_search_sign_in_facilities_found' || event === 'record_search_completed') {
                    // The two events can arrive in either order: merge by organizationId, never replace
                    await mergeFacilitiesToConnect(
                      data.external_id,
                      data.consent_id,
                      data.facilities_requiring_sign_in.map((facility) => ({
                        name: facility.facility_name,
                        logoUrl: facility.endpoint.logo_url,
                        organizationId: facility.connecting_organization.id,
                      })),
                    );
                  }
                
                  if (event === 'record_search_completed' && data.status !== 'completed') {
                    if (!(await hasFacilitiesToConnect(data.consent_id))) {
                      await tellPatient(data.external_id, data.status);
                    }
                  }
                
                  res.sendStatus(200);
                });
                

                #Sign-in facilities found during the search

                The search can find the facilities that need a sign-in long before it ends. Flexpa sends the record_search_sign_in_facilities_found webhook as soon as it finds them, so you can show "Connect" buttons while the search keeps running. Verify the X-Flexpa-Signature header as you do for record_search_completed.

                Flexpa sends it at most once per consent, for the consent's first search, for headless consents only, and only when at least one facility needs a sign-in. It has no status: the search is still running, and its answer comes in record_search_completed.

                record_search_sign_in_facilities_found data

                consent_idstring

                The consent whose search found the facilities. Send it as flexpa_consent_id on a follow-up push.

                external_idstring

                Your flexpa_external_id for the patient.

                patient_authorization_idstring

                The search. record_search_completed for the same search carries the same patient_authorization_id.

                modestring

                test or live.

                facilities_requiring_sign_inarray

                The facilities found so far that need the patient's own sign-in, in the same shape as on record_search_completed: facility_name, connecting_organization (id, name) and endpoint (id, logo_url). Never empty.

                The two events can arrive in either order. record_search_completed is the final answer for the search, so ignore a record_search_sign_in_facilities_found for a patient_authorization_id that already has a record_search_completed, or re-read GET /rest/consent/:consentId. The webhook handler in the IAL2 walkthrough takes a third way: it merges both lists by connecting_organization.id, which gives the same list in either order.

                record_search_sign_in_facilities_found

                {
                  "event_id": "5d4c3b2a-1f0e-4d9c-8b7a-6f5e4d3c2b1a",
                  "event": "record_search_sign_in_facilities_found",
                  "version": 1,
                  "timestamp": 1704067170000,
                  "data": {
                    "mode": "test",
                    "external_id": "user-123",
                    "consent_id": "4b2a9c1e-7d3f-4a8b-9e6c-2f1d0a9b8c7d",
                    "patient_authorization_id": "7c3e9f2a-4b8d-4e1f-9a3c-5d7e8f9a1b2c",
                    "facilities_requiring_sign_in": [
                      {
                        "facility_name": "Memorial Hospital Central",
                        "connecting_organization": {
                          "id": "3f2e1d0c-9b8a-4766-a5b4-c3d2e1f0a9b8",
                          "name": "UCHealth"
                        },
                        "endpoint": {
                          "id": "9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d",
                          "logo_url": "https://cdn.flexpa.com/logos/9a8b7c6d-..."
                        }
                      }
                    ]
                  }
                }
                

                #Connect more facilities

                A follow-up push adds one more facility to a consent the patient already shared. Use it for:

                • Each facility in an IAL2 search's facilities_requiring_sign_in.
                • Another health plan or provider the patient wants to add to a search mode consent, found with Organization search.

                The patient goes straight to that organization's sign-in and comes back with a new code, like the first visit.

                #Sending a follow-up push

                A follow-up push is a search mode push with three differences:

                • flexpa_consent_id is the consent to add to. It must be EXCHANGED, belong to your application in the same mode, and its refresh token must not have expired.
                • flexpa_organization_id or flexpa_endpoint_id is required. For an IAL2 facility, send connecting_organization.id.
                • scope and flexpa_external_id must match the consent's, or the push fails with invalid_scope or invalid_request.

                Send the time of the patient's latest opt-in as flexpa_consented_at. When it is close to a year old, show your consent screen again first. Use a new state and a new PKCE pair, like any push. Do not send flexpa_ial2_mode.

                A push for a facility the consent is already connected to fails. Some consents made through the hosted flow cannot take a follow-up; the push fails with invalid_request before the patient signs in, and the patient starts a new consent instead.

                Follow-up push

                curl -X POST https://api.flexpa.com/oauth/par \
                  -u "pk_test_...:sk_test_..." \
                  -d client_id=pk_test_... \
                  -d response_type=code \
                  -d redirect_uri=https://example.com/flexpa/callback \
                  -d "code_challenge=<new challenge>" \
                  -d code_challenge_method=S256 \
                  -d "scope=launch/patient offline_access" \
                  -d "state=<new state>" \
                  -d flexpa_external_id=user-123 \
                  -d flexpa_consented_at=2026-01-31T14:03:22Z \
                  -d flexpa_consent_id=4b2a9c1e-7d3f-4a8b-9e6c-2f1d0a9b8c7d \
                  -d flexpa_organization_id=3f2e1d0c-9b8a-4766-a5b4-c3d2e1f0a9b8
                

                Follow-up return

                https://example.com/flexpa/callback?code=public_token_...&state=<new state>
                

                #Exchanging a follow-up code

                Exchange the follow-up code the same way as the first one. The connection becomes active at the exchange, and the response is a new token pair for the whole consent: it reaches the facilities already connected and the new one. Exchange it within 30 minutes; a follow-up code that is not exchanged by then expires, and the connection is discarded.

                A follow-up exchange replaces the consent's token pair. The moment you exchange a follow-up code, the previous access token and refresh token stop working: the old access token gets 401, and a refresh with the old refresh token gets invalid_grant.

                Keep one stored token pair per consent, and overwrite it after every exchange and every refresh. A background job that keeps its own copy of the old pair will fail after the next follow-up.

                Run refreshes and follow-up exchanges for the same consent one at a time. If they run at the same time, only the one that finishes last holds a working pair.

                #Pushing twice for the same facility

                If you push more than one follow-up for the same facility, for example a retry or a reminder, the newest one wins:

                • An older visit whose patient returns while the newer one is still under way ends with flexpa_error=superseded.
                • An older visit's code is refused with invalid_grant once the patient has finished signing in on the newer one.
                • Once any code for that facility is exchanged, every other code for it is refused with invalid_grant, so a consent never holds two connections to one facility.
                • If the newer visit fails, expires or is cancelled, the older one still works.

                #Revoked consents

                Revoking a consent ends every follow-up still open on it. A patient who is signing in at that moment returns with flexpa_error=consent_revoked, and a follow-up code exchanged after the revoke is refused with invalid_grant.

                Store one pair per consent

                // Every return with a code, first consent or follow-up, comes here
                async function exchangeAndStore(saved: SavedPush, code: string) {
                  const { consentId, userId, codeVerifier } = saved;
                
                  // A per-consent lock, such as a Postgres advisory lock keyed on consentId
                  // (a first consent has no row yet to lock). Your refresh job must take
                  // the same lock, and read the stored pair only after taking it.
                  await withConsentLock(consentId, async () => {
                    const stored = await db.flexpaTokens.findUnique({ where: { consentId } });
                    if (stored && stored.userId !== userId) throw new Error('Consent belongs to another user');
                
                    const tokens = await exchangeCode(code, codeVerifier);
                    const pair = {
                      accessToken: tokens.access_token,
                      refreshToken: tokens.refresh_token,
                    };
                
                    // Overwrite: the previous pair for this consent no longer works.
                    // userId is kept to check follow-up pushes.
                    await db.flexpaTokens.upsert({
                      where: { consentId },
                      update: pair,
                      create: { consentId, userId, ...pair },
                    });
                  });
                }
                

                #Parity with the Consent UI

                Use this checklist to make sure your flow covers everything the hosted Consent UI does for the patient.

                Consent UI stepYour equivalent
                Terms and privacy screenYour consent screen, with flexpa_consented_at
                Health plan and provider searchOrganization search, with a debounced typeahead
                "Did you mean" and unavailable resultspartial and available on each result
                Plan type questionrequires.lineOfBusiness, sent as flexpa_line_of_business
                State questionrequires.state, sent as flexpa_state
                Choosing between same-named locationstenantEndpointIds, sent as flexpa_endpoint_id (Flexpa has no screen for this on a push)
                Name and date of birthThe three flexpa_hint_* values
                Identity provider choiceflexpa_identity_provider
                "Searching for your records"Your own waiting state, ended by record_search_completed. It can show "Connect" buttons as soon as record_search_sign_in_facilities_found arrives
                Facilities that need a sign-infacilities_requiring_sign_in, each with a follow-up push
                Adding another sourceA follow-up push
                Error and retry screensYour handling of each flexpa_error
                Leaving the flowYour own Back and cancel, before the push

                #Test it

                Build and test everything with your test mode keys (pk_test_... and sk_test_...). Test mode is not gated, so pushes work before Flexpa reviews your consent screen.

                • Search with mode=TEST so the results are test mode endpoints. See Test mode for the test health plans and their sign-ins.
                • Push and exchange with your test mode keys and a redirect URI registered for test mode.
                • Register a test mode webhook to receive record_search_sign_in_facilities_found and record_search_completed. In test mode, the CommonWell search returns YourChart, a test facility that needs a sign-in.

                Before you go live, make sure you have tried each of these:

                1. A search mode push with every question answered, and no Flexpa screen.
                2. A push missing the plan type, to see Flexpa's plan type screen, then Back to get member_cancelled.
                3. A patient who closes the window halfway, and your app's handling of a visit that never returns.
                4. Pushing twice in the same browser, to see superseded on the older visit.
                5. An IAL2 push, the record_search_sign_in_facilities_found and record_search_completed webhooks, and a follow-up push to YourChart from their list.
                6. A follow-up exchange, and that your app uses the new token pair everywhere.

                #Go live

                1. Finish your consent screen and test the whole flow in test mode.
                2. Send Flexpa screenshots of the whole flow for review, from your consent screen to the moment the patient leaves for Flexpa.
                3. Flexpa reviews them against the consent screen requirements and turns on headless consent in live mode for your workspace.
                4. Switch to your live mode keys, search with mode=LIVE (or a live mode Application Access Token), and register a live mode redirect URI and webhook.

                Until step 3, a live mode push fails with 403 unauthorized_client. The description says pushed authorization requests are not enabled for this workspace in live mode.


                #Next steps

                • Read the Consent reference for token refresh, introspection and revocation
                • Fetch the patient's data with the Records API
                • Set up webhooks and signature verification
                • Questions about early access? Reach out to Flexpa
                Status TwitterGitHub

                © 2026 Flexpa. All rights reserved.

                FHIR® is the registered trademark of Health Level Seven International and its use does not constitute endorsement by HL7.