Render a JSON page in Astro


How to render a JSON page in Astro

6 Oct, 2021 · 2 min read

I’ve been working on a search solution for my Astro blog, and building search on top of static site generators is always tricky.

My general idea would be to do it almost the same as my Eleventy search.

Creating a JSON page in Astro

However, I quickly realized Astro doesn’t have a neat permalink structure by default.

Trying out some things, I learned that we could create pages like search.json.astro.

These will render as

But let’s see how we can render a JSON response of all our blog posts in there.

Astro has the cool built-in fetch method for internal pages so let’s use that first.

const allPosts = Astro.fetchContent('./posts/*.md');

In the next step, I’d like to map these to the output that I can use, which only needs the following three elements.

  • title
  • description
  • slug

Let’s see how that would look: => {
  return {
    title: p.title,
    description: p.description,
    slug: p.url,

However, let’s create a variable from this, and JSON stringify the output.

const json = JSON.stringify( => {
    return {
      title: p.title,
      description: p.description,
      slug: p.url,

Now all that’s left is to render the JSON output on the page.

// All our code

And that’s it. We can now leverage a simple JSON file for our search to use.

You can find my example code on the following file. Or see the end JSON file here.

Note: This process might change if Astro will support this eventually, but for now, this seems like an excellent approach.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Computed Nano Stores

6 Sep, 2022 · 2 min read

Computed Nano Stores

Astro Nano Stores maps

5 Sep, 2022 · 3 min read

Astro Nano Stores maps

Join 2098 devs and subscribe to my newsletter