Genesys Cloud - Developer Community!

 View Only

Sign Up

  • 1.  JavaScript SDK: loginPKCEGrant popup leaks message listeners, re-auth exchanges the same code multiple times (invalid_grant / CORS error)

    Posted 10-07-2026 10:58

    SDK version: purecloud-platform-client-v2 260.0.0 (bundled with Vite, using src/purecloud-platform-client-v2/ApiClient.js)

    I have a web widget that authenticates with PKCE using the popup flow:

    client.updateAuthPopupConfiguration({
        usePopup: true,
        popupTimeout: 4000,
        autoClosePopup: true,
        autoClosePopupDelay: 30000,
        popupTarget: "_blank",
        popupWindowFeatures: "popup=true,width=600,height=500",
        waitForLoginPromise: true
        // other options left at default values
    });
    
    export async function authenticate() {
        client.setEnvironment(environment);
    
        try {
            return await client.loginPKCEGrant(clientId, redirectUri, { target: organizationId, skipTest: true });
        } catch (error) {
            console.error('loginPKCEGrant error', error);
            throw error;
        }
    }
    

    I have made my oauth/callback following the github examples:
    platform-client-sdk-javascript/build/samples at master · MyPureCloud/platform-client-sdk-javascript
    My open window send a postMessage to an eventListener from the sdk.

    window.opener.postMessage(
        { name: "gc_auth_popup", type: "message", hash: window.location.hash, search: window.location.search },
        targetOrigin
    );
    

     

    When an API call returns 401, I call loginPKCEGrant again to get a new token. Usually i made my oAuth credentials only last 300 seconds to validate reauthentication.

    Problem

    • The first login always works.
    • On every re-login after a 401, the browser sends more than one request to /oauth/token with the same authorization code. One succeeds and the token is saved. The others fail with invalid_grant, and since that error response has no Access-Control-Allow-Origin header, the browser shows it as a CORS error.
    • Listeners run in registration order, so the failing exchange is often the one tied to the current promise. loginPKCEGrant rejects even though a valid token was just saved.
    • The failing exchange also calls _saveSettings({ accessToken: undefined }), so depending on which response arrives last, it can wipe the valid token.
    • Each re-login adds one more exchange: 2 on the first re-login, 3 on the second, and so on.

    Steps to reproduce

    1. Call loginPKCEGrant with usePopup: true and complete the login.
    2. Call loginPKCEGrant again (for example after a 401). 
    3. Check the Network tab: there are two POST /oauth/token requests with the same code, and one fails.

    Possible cause

    In ApiClient.js, _startAuthPopup registers an anonymous arrow function as the message listener:

    // ApiClient.js:591
    window.addEventListener('message', (event) => this._handleAuthPopupMessage(event, loginPopupConfiguration, resolve, reject));
    

    But the cleanup code removes a different function reference:

    // ApiClient.js:553, 621, 710
    window.removeEventListener('message', this._handleAuthPopupMessage);
    

     

    Since removeEventListener matches listeners by function reference, nothing is ever removed. Every popup login leaves a listener on window. On the next login, all the old listeners also receive the popup's postMessage and each one runs authorizePKCEGrant with the same code.

    Current workaround

    I'm not an expert on this topic, so I used AI to help me investigate. The workaround below intercepts window.addEventListener while loginPKCEGrant is running, to keep a reference to the listener the SDK registers, and removes it when the login finishes. With it, only one token exchange happens per login and the errors stopped:

    const originalAddEventListener = window.addEventListener;
    const sdkListeners = [];
    
    window.addEventListener = function (type, listener, options) {
        if (type === 'message' && String(listener).includes('_handleAuthPopupMessage')) {
            sdkListeners.push({ listener, options });
        }
        return originalAddEventListener.call(this, type, listener, options);
    };
    
    try {
        return await client.loginPKCEGrant(clientId, redirectUri, { target: organizationId, skipTest: true });
    } finally {
        window.addEventListener = originalAddEventListener;
        sdkListeners.forEach(({ listener, options }) => window.removeEventListener('message', listener, options));
    }
    



    Questions

    1. Can anyone confirm that the SDK is not removing this listener properly? ( i dont have enough knowledge about this)
    2. If so, can it be fixed in a future release, so the workaround is no longer needed?
    3. Should I also open a ticket with Genesys Customer Care, or is this forum the right place for SDK issues?

    Thanks!

     


    #PlatformSDK

    ------------------------------
    Julio
    ------------------------------


  • 2.  RE: JavaScript SDK: loginPKCEGrant popup leaks message listeners, re-auth exchanges the same code multiple times (invalid_grant / CORS error)

    Posted 10-07-2026 11:29

    Hello,

    Could you please try with version 263.2.0 (latest)?

    I made a fix in version 263.0.0. A message listener was not removed properly after the end of a loginPKCEGrant - so they were "accumulating" after multiple ones. This looks what you are describing.

    Regards,



    ------------------------------
    Jerome
    Senior Development Support Engineer
    ------------------------------



  • 3.  RE: JavaScript SDK: loginPKCEGrant popup leaks message listeners, re-auth exchanges the same code multiple times (invalid_grant / CORS error)

    Posted 10-07-2026 11:41
    Edited by Jerome Saint-Marc 10-07-2026 11:41

    For your information, we have also introduced a new optional parameter in the loginPKCEGrant method - "skipTest"

    `client.loginPKCEGrant(clientId, redirectUri, { skipTest: true, state: state, login_hint: "jane@example.com:acme-org" } }`

    By default, when the loginPKCEGrant is invoked, the sdk checks if there is already a token in memory (variable or local storage). If there is one, it tests it - and if it is still valid, the sdk will not invoke the PKCE Grant flow.

    The new skipTest option (if set to true) is to force the sdk to trigger the PKCE Grant flow. I mean the sdk doesn't check if there is already a token and if it is still valid - it will then trigger the OAuth PKCE Grant flow.



    ------------------------------
    Jerome
    Senior Development Support Engineer
    ------------------------------



  • 4.  RE: JavaScript SDK: loginPKCEGrant popup leaks message listeners, re-auth exchanges the same code multiple times (invalid_grant / CORS error)

    Posted 10-07-2026 11:55

    Thanks for the info about skipTest! Funny thing: I was already using skipTest: true because I saw it in the documentation, but I had no idea it was from a newer version than the one I had installed, haha. Now that I've updated, it makes sense, since I only call loginPKCEGrant again after a 401, when I know the current token is no longer valid.

    Thanks again for your help!



    ------------------------------
    Julio
    ------------------------------



  • 5.  RE: JavaScript SDK: loginPKCEGrant popup leaks message listeners, re-auth exchanges the same code multiple times (invalid_grant / CORS error)

    Posted 10-07-2026 11:54

    Hi Jerome,

    Thank you for the quick response!

    I updated to 263.2.0, removed my workaround, and tested the re-authentication several times. It's working correctly now: each re-login sends a single /oauth/token request and the CORS / invalid_grant errors are gone.

    Thanks again for the fix!

    Regards, Júlio



    ------------------------------
    Julio
    ------------------------------



  • 6.  RE: JavaScript SDK: loginPKCEGrant popup leaks message listeners, re-auth exchanges the same code multiple times (invalid_grant / CORS error)

    Posted 10-07-2026 11:57

    Glad to hear the issue is fixed.



    ------------------------------
    Jerome
    Senior Development Support Engineer
    ------------------------------