MSAL: await config load and do the rest
Andrew Elans

Andrew Elans @andrewelans

About: This is my sketchbook where I put things I consider relevant to remember in future and share with others.

Location:
Oslo, Norway
Joined:
Feb 27, 2024

MSAL: await config load and do the rest

Publish Date: Mar 7
0 0

Ref. also to this post of mine: Load scripts in sequence with import(), async and IIFE

When loading Microsoft Authentication Library (MSAL) for JavaScript, you have to make sure that the msal config is loaded, the msal object is intitiated and resolved, so that you can use it further in your code:

You must call and await the initialize function before attempting to call any other MSAL API

Setup

msal-config.js

console.log('<<<<<<<<<<<< msal-config.js start');
// ...msal configuration data and init here...
console.log('<<<<<<<<<<<< msal-config.js end')
Enter fullscreen mode Exit fullscreen mode

main.js

console.log('<<<<<<<<<<<< main.js start');
// ...msal queries here...
console.log('<<<<<<<<<<<< main.js end')
Enter fullscreen mode Exit fullscreen mode

Stardard way

Usually you would set it like this in your html:

<script type="module" src="/msal-config.js"></script>
<script type="module" src="/main.js"></script>
Enter fullscreen mode Exit fullscreen mode

That's what we have as a result (refreshed 3 times):
Image description

We see that main.js is called before msal-config.js is finished which typically gives unexpected results in your logic.

Required way

Let's change to the following method:

<script>
(async () => {
    await import('/msal-config.js');
    import('/main.js')
})();
</script>
Enter fullscreen mode Exit fullscreen mode

Alternatively with Promises:

<script>
import('/msal-config.js').then(() => import('/main.js'))
</script>
Enter fullscreen mode Exit fullscreen mode

Result (refreshed 3 times):
Image description

Comments 0 total

    Add comment