Create a JSON feed with 11ty

Categories

Eleventy is great because you can literally output anything. To output a JSON feed with 11ty, all you need to do is create a file called feed.njk and adding the following to it:

Code language
text
---
permalink: '/my-cool-feed.json'
---
{
  "posts": [
    {% for item in collections.posts %}
      {
        "title": "{{ item.data.title }}",
        "url": "{{ item.url }}"
      }{% if not loop.last %},{% endif %}
    {% endfor %}
  ]
}

The JSON feed will give you an output like this:

Code language
json
{
  "posts": [
    {
      "title": "Quick and simple image placeholder",
      "url": "/posts/quick-and-simple-image-placeholder/"
    },
    {
      "title": "Color Palette Generator",
      "url": "/posts/color-palette-generator/"
    }
  ]
}

This little snippet creates a feed of posts that have a title and url. Whatever data you have access to in your collection, you can output in this feed, too.

Pro tip: Make sure you set the permalink to have a .json extension so the browser knows that it is application/json. That’ll save you a lot of server hassle!

You can grab a basic Eleventy starter for this demo here.

Hello, I’m Andy and I’ll help you to level up your front-end development skills.

I'm a designer and front-end developer who has worked in the design and web industries for over 15 years, and in that time, I have worked with some of the largest organisations in the world, like Google, Harley-Davidson, BSkyB, Unilever, The Natural History Museum, Oracle, Capita, Vice Media and the NHS.

On Piccalilli, I share my knowledge and experience to make you a better front-end developer.

I'm the founder of Set Studio, a creative agency that specialises in building stunning websites that work for everyone. Check out what we're all about.