DEV Community

Andrew Elans
Andrew Elans

Posted on • Edited on

MSAL: await config load and do the rest

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

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay