Code

How I Made My Badass Listening To’ Section

We’ll use the Last.fm API and Eleventy to make it happen

I lis­ten to music most of the day while I work. It helps me focus, and it makes me hap­py. When think­ing of ideas for my new site, I want­ed to show off my recent­ly played tracks to give vis­i­tors a sense of my musi­cal taste. After spend­ing some time look­ing into the Apple Music API, I decid­ed it would be eas­i­er to use the Last.fm API instead.

Installing Our Packages

First, let’s install two pack­ages we’ll need to make this work.

npm install @11ty/eleventy-cache-assets dotenv

First, @11ty/eleventy-cache-assets will let us fetch data from an exter­nal API and cache the results so that we’re not request­ing data every time we build the site.

Sec­ond, dotenv will make it easy to han­dle our local envi­ron­ment vari­ables. Last.fm requires us to send an API key with each request. Which reminds me, get your API key here. If you’re using Netli­fy, you can read the doc­u­men­ta­tion on how to set envi­ron­ment variables.

Setup Your API Key

Before we begin, you’ll need to get your API key. Next, cre­ate a .env file in the root of your project and put your key in it. For example:

API_KEY=token_goes_here

Remem­ber to add your API key to the serv­er where you host your site. If you’re using Netli­fy, you can read the doc­u­men­ta­tion on how to set envi­ron­ment vari­ables to do it.

Fetching Data

Cre­ate a file in your _data fold­er. I called mine lastfm.js. We’ll add the fol­low­ing to it:

// _data/lastfm.js

const Cache = require('@11ty/eleventy-cache-assets');
require('dotenv').config();

const API_KEY = process.env.LASTFM_KEY;
const USERNAME = 'timothybsmith';
const API = 'http://ws.audioscrobbler.com/2.0/'

module.exports = async () => {
  try {
    const json = await Cache(
      `${API}?method=user.getrecenttracks&user=${USERNAME}&limit=10&api_key=${API_KEY}&format=json`,
      {
        duration: '2h',
        type: 'json',
      }
    );
    return json;
  } catch (ex) {
    console.log(ex);

    return [];
  }
};

And just like that, we have access to the last ten recent­ly played tracks in JSON form. I have the cache set to two hours, but you can set it to what­ev­er you’d like. I could­n’t find the rate lim­it for Last.fm, but I don’t want to hit the API mul­ti­ple times while I work.

Displaying the Data

Now that we have our data, we can ren­der it in our tem­plate. I cre­at­ed a par­tial called recently-played.html in the _includes/partials fold­er. Now we’ll add the following:

<!-- _includes/partials/recently-played.html -->
{% set recentlyPlayed = lastfm.recenttracks.track %}

{% if recentlyPlayed.length %}
<ul class="recently-played">
  {% for item in recentlyPlayed %}
    <li class="recently-played__track">
      <a href="{{ item.url }}" class="track__url">
        <div class="track__media">
          <img
            src="{{ item.image[3]['#text'] }}"
            alt="Album artwork for {{ item.name }} by {{ item.artist['#text'] }}"
            loading="lazy" />
        </div>
        <span class="track__name">{{ item.name }}</span>
        <span class="track__artist">{{ item.artist['#text'] }}</span>
      </a>
    </li>
  {% endfor %}
</ul>
{% endif %}

So we’re doing a few things here. We’re using Nun­jucks to set which array we want to loop over. lastfm is the name of the data file, recenttracks is the object that con­tains our tracks, and each track has our nec­es­sary items. From there, we only ren­der the rest of the tem­plate if there are songs to display.

You’ll then want to include this par­tial in your tem­plate like this:

{% include "partials/recently-played.html" %}

Conclusion

And just like that, we’ve fetched our data and ren­dered it in our tem­plate! Now it’s your turn to add some style. This is the moment I felt like a total badass, hope you’re feel­ing it too.

If you need some help or end up using this on your site, please let me know! You can find me on Twit­ter as @smithtimmytim. Hap­py coding!