single-page-applicationastrojs

Get most recent posts from a blog built with Astro in a Single Page Application


I have one single page application where I would like to show most recent posts from Astro blog. Does astro provide an API to easily access such information from another application?


Solution

  • I used Astro Endpoints to create custom API for my blog.

    src/pages/recent-posts.json.ts

    
    import { MarkdownInstance } from "astro";
    import { Frontmatter, sortDateDescending } from "src/misc";
    
    export async function get() {
        const allPosts = import.meta.glob<MarkdownInstance<Frontmatter>>("./posts/article/*.md", { eager: true }); // Vite
        const posts = sortDateDescending(Object.values(allPosts))
            .filter((ele) => ele.frontmatter.draft != true)
            .map((ele) => {
    
                return {
                    title: ele.frontmatter.title,
                    url: ele.url,
                    thumbnailUrl: ele.frontmatter.image,
                    content: ele.rawContent(),
                    publishedDate: ele.frontmatter.date,
                    tags: ele.frontmatter.tags,
                };
            });
        
        const LIMIT = 2;
    
        return {
            body: JSON.stringify(posts.slice(0, LIMIT)),
        };
    }
    
    
    

    Now, I can fetch the most recent posts from an endpoint /recent-posts.json.