Skip to content

Integration with NextJS/SSR applications #13

@nicholas-c

Description

@nicholas-c

We're currently in the process of integrating mParticle into a NextJS application, however when we include the @mparticle/web-braze-kit there is many occurrences of window is undefined problems which happen.

Although we initialise mParticle and braze-kit within a useEffect, the import itself just runs window functions on import (Which occurs Serverside, and window is undefined)

This leads our block of code to look something like this which is quite messy.

try {
    (async () => {
        /**
         * Dynamic import as the package uses `window.xxx` within it's internals, breaks SSR/ISR
         * Braze will hook into mParticle and call a `Fowarding` endpoint,
         * this then does a xmlhttprequest to Braze itself.
         */
        const brazeTracking = await import('@mparticle/web-braze-kit');
        brazeTracking.register(mParticleConfig);

        /**
         * Because the above is Dynamic import, and async, the kit isn't always registered when mParticle init's
         * it causes race conditions where sometimes it will init before, and other times it wont
         * but the .kits object the above register call does is required when mParticle init's so here we are 🥺
         */
        mParticle.init(process.env.NEXT_PUBLIC_MPARTICLE_API_KEY!, mParticleConfig);
    })();
} catch (e) {
    console.error('Failed to load Braze mParticle integration', e);

    // Just run mparticle even if the above fails
    mParticle.init(process.env.NEXT_PUBLIC_MPARTICLE_API_KEY!, mParticleConfig);
}

Is there any plans to rework the window calls so this block of code can be streamlined and reduced in risk/complexity?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions