Skip to content

Instantly share code, notes, and snippets.

@ullaskunder3
Created September 13, 2025 06:33
Show Gist options
  • Select an option

  • Save ullaskunder3/dd23a7b466213f729236a63d1e3e1871 to your computer and use it in GitHub Desktop.

Select an option

Save ullaskunder3/dd23a7b466213f729236a63d1e3e1871 to your computer and use it in GitHub Desktop.
import matter from "gray-matter";
const GITHUB_TOKEN = process.env.GITHUB_BLOG_CLIENT;
const REPO_OWNER = "ullaskunder3";
const REPO_NAME = "blog-api";
const BRANCH = "main";
interface BlogPostMeta {
title: string;
date: string;
subtitle: string;
slug: string;
tag: string[];
}
export const fetchBlogPostsFromGitHub = async (): Promise<BlogPostMeta[]> => {
try {
const res = await fetch(
`https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/contents?ref=${BRANCH}`,
{
headers: {
Authorization: `Bearer ${GITHUB_TOKEN}`,
Accept: "application/vnd.github.v3+json",
},
}
);
const files = await res.json();
if (!Array.isArray(files)) {
console.error("GitHub API did not return an array:", files);
return [];
}
const mdxFiles = files.filter((file: any) => file.name.endsWith(".mdx"));
const posts: BlogPostMeta[] = await Promise.all(
mdxFiles.map(async (file: any) => {
const contentRes = await fetch(file.download_url, {
headers: {
Authorization: `Bearer ${GITHUB_TOKEN}`,
},
});
const rawContent = await contentRes.text();
const { data, content } = matter(rawContent);
return {
title: data.title,
date: data.date,
subtitle: data.subtitle,
slug: file.name.replace(".mdx", ""),
tag: data.tag || [],
content,
};
})
);
return posts;
} catch (error) {
console.error("Error fetching posts:", error);
return [];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment