I lis­ten to mu­sic most of the day while I work. It helps me fo­cus, and it makes me happy. When think­ing of ideas for my new site, I wanted to show off my re­cently played tracks to give vis­i­tors a sense of my mu­si­cal taste. After spend­ing some time look­ing into the Apple Music API, I de­cided it would be eas­ier to use the Last.fm API in­stead.

Installing Our Packages #

First, let’s in­stall 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 ex­ter­nal API and cache the re­sults so that we’re not re­quest­ing data every time we build the site.

Second, dotenv will make it easy to han­dle our lo­cal en­vi­ron­ment vari­ables. Last.fm re­quires us to send an API key with each re­quest. Which re­minds me, get your API key here. If you’re us­ing Netlify, you can read the doc­u­men­ta­tion on how to set en­vi­ron­ment vari­ables.

Setup Your API Key #

Before we be­gin, you’ll need to get your API key. Next, cre­ate a .env file in the root of your pro­ject and put your key in it. For ex­am­ple:

API_KEY=token_goes_here

Remember to add your API key to the server where you host your site. If you’re us­ing Netlify, you can read the doc­u­men­ta­tion on how to set en­vi­ron­ment vari­ables to do it.

Fetching Data #

Create a file in your _data folder. 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 ac­cess to the last ten re­cently played tracks in JSON form. I have the cache set to two hours, but you can set it to what­ever you’d like. I could­n’t find the rate limit 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­ated a par­tial called recently-played.html in the _includes/partials folder. Now we’ll add the fol­low­ing:

<!-- _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 do­ing a few things here. We’re us­ing Nunjucks to set which ar­ray we want to loop over. lastfm is the name of the data file, recenttracks is the ob­ject 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 dis­play.

You’ll then want to in­clude 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 mo­ment I felt like a to­tal badass, hope you’re feel­ing it too.

If you need some help or end up us­ing this on your site, please let me know! You can find me on Twitter as @smithtimmytim. Happy cod­ing!

Series Learn Eleventy

Documenting new and exciting things I learn how to do with Eleventy.

View Series →

Webmentions 7

  1. frostedechoes frostedechoes
    @smith This is really cool (I didn’t even realize Last.fm was still around). I know you are using Eleventy, but this is the kind of thing that would be great as a Micro.blog plugin.
  2. smith smith
    @frostedechoes Thanks so much! Yes it is! It's a pretty cool service. Funny you say that because that's exactly what @endonend wants. I'm planning to look over the plugin docs soon and see if I can make it happen.
  3. smith smith
    @maique Thanks so much! I really appreciate it 😊
  4. mikehaynes mikehaynes
    @smith While I'm not prepared to try and set something like this up for myself, I did log back into my Last.fm account and start using it again after four years. Thank you for that. 😂

Up Next