Using MusicKitJS to Integrate Your Web Application With Apple Music

Sajan Gutta
4 min readApr 11, 2021
Photo by Alexander Shatov on Unsplash

In recent years, streaming services such as Spotify and Apple Music have become the primary source of music for many. A major advantage of these streaming services is the ability to track listening data and cater to user’s specific preferences. This makes integration with these services very useful for your application. For example, you may want to learn about a user’s favorite genres so you can make informed recommendations in your own application. This typically entails requesting authorization from the user to access their information and receiving a token specifically for your application to access that user’s information. You will then use that token with an API to get the user’s streaming service account information.

While Spotify has extensive documentation on the web, I was recently working on integration with Apple Music and found it extremely difficult to implement in a web application. While the code wasn’t difficult, the documentation was lacking and I found many unanswered questions in online forums from developers struggling to integrate Apple Music.

Fortunately, I was able to figure out how to integrate with Apple Music using MusicKitJS. The process is actually quite simple, but due to a lack of online information, it was challenging to figure out. Let’s get started on how to do this integration.

Create a MusicKit Identifier

First, you must create a MusicKit identifier for your application. This is essentially just registering your application to use the Apple Music API and this part is well documented by Apple. You can see the steps here to learn more about how to create your identifier.

Create a Private Key for Apple Music

Next, you will need to create a Private Key for accessing the Apple Music API using your MusicKit Identifier. This is well documented with the steps found here.

Create a JSON Web Token

Finally, for your application to integrate with MusicKitJS, you need to create a JSON Web Token (JWT). Apple provides some useful steps to do this at this link. Essentially, you will need to convert your private key into a JWT with specific information in the headers and claims payloads. There are many useful libraries out there such as pyjwt that make this process easy.

The script here is a useful Python example to see how exactly this will work. Since JWT’s eventually expire, you’ll want to integrate this type of logic into your backend so it can be called before rendering the web page containing the Apple Music integration. This allows your application to generate a new token if the current one has expired (unlike an API key, you can’t use the same token for a long time).

NOTE: For Apple Music, your JWT token MUST be encoded using the ES256 algorithm.

Embedding MusicKit in Your Frontend

Now that we have created a token for using MusicKitJS, we are ready to embed MusicKitJS in the JavaScript of our webpage.

<script src="https://js-cdn.music.apple.com/musickit/v1/musickit.js"></script>
<script>
document.addEventListener('musickitloaded', function() {
// MusicKit global is now defined
MusicKit.configure({
developerToken: 'INSERT TOKEN HERE',
app: {
name: 'INSERT NAME HERE',
build: 'INSERT NUMBER HERE'
}
})
let music = MusicKit.getInstance();
document.getElementById('login-btn').addEventListener('click', () => {
music.authorize().then(function(token) {
// do something with token here
window.location.href += "?music-user-token=" + encodeURIComponent(token);
}).catch (e => {
console.log ('Error:' + e );
});
});
});
</script>

This is the part of this process that is particularly poorly documented. However, the code above should help with the integration and as you can see, it’s actually pretty simple. Let’s break down what is happening.

First, the MusicKitJS library is loaded just like any other JS library would be loaded. Next, we add a listener to execute when the script is loaded in. When this occurs, we configure a MusicKit instance using the JWT token created in our previous step. You should also pass a name for your application and a version number (build). Once MusicKit is configured, we store the instance in a variable (‘music’) which will be used later.

Elsewhere in your webpage, you should have a button that users can click in order to authorize your application to connect with their Apple Music account. We attach a click event listener to this element which calls authorize() on the MusicKit instance. This will cause the Apple Music authentication flow to pop up on the user’s screen. The user will authorize access to their account after which the frontend JS will receive a token for accessing their information. At this point, you can send the token to your backend. You will now be able to access information about a user’s account from the Apple Music API.

Extra Information/Notes

  1. The whole purpose of this integration is to pull user information from Apple Music’s API. All of the Apple Music API’s documentation can be found here.
  2. MusicKitJS has some very non-descriptive error messages unfortunately. I frequently ran into one that said “Error: 0.” In my case this was usually due to having token issues. Check that the token you’re using in your frontend isn’t expired and your token generation logic works properly if you run into this error.
  3. When your JavaScript receives the user specific token (Apple called it a music-user-token), a useful way to use this is to pass the token in a redirect to another url/endpoint where you handle connecting to the user’s Apple Music account and fetching their information. You will notice that the code above is doing something similar to this.
  4. Eventually this may become outdated in the event that Apple releases a better library (with more capabilities) for web integration with Apple Music. Hopefully that happens sometime soon!

--

--

Sajan Gutta

Computer Science and Business Administration Student @ USC | Backend Developer @ Discotech | Passionate about Software Engineering