iTranslated by AI
[Next.js + GitHub API] Building and Managing a Blog with Series and Comments
I wanted to build a blog site where I could write down small articles about technology and other topics, so I created and released one. I have summarized the implementation method along with the source code here. This article will be long as it covers everything from design to implementation and operation.
Conclusion
These are the site and repository resulting from this article.
- HP
- Repository
Goals and Design
Goals
- A Markdown (MD) format blog that is easy to write on a PC
- Use of external services for file hosting, with image support
- Support for organizing posts into a series
- Setting up a comment form
- Low-cost site operation
The goal is to achieve all of these within a single service.
Technologies and Services Used and Reasons
- Vercel
A PaaS. It's very easy to use due to its integration with GitHub accounts and preview features.
- Next.js
Allows for building React-based web applications. The main reasons are that it's managed by Vercel and makes dynamic page generation easy.
- GitHub API
Allows access to your own GitHub repositories, whether public or private, using a personal access token. This is because access control is already handled and it allows for versioning.
- reCAPTCHA
Described later in Comment Function Design.
- Tailwind CSS: I decided to give it a try instead of using SCSS.
Article Management Method
I created a private GitHub repository.
├── posts/
│ ├── [Series name]/
│ │ ├── (meta.json)
│ │ ├── 1.md
│ │ ├── 2.md
│ │ └── ...
│ └── article-name.md
├── img/
│ ├── [Optional]
│ └── Optional
└── profile/
└── index.md
As mentioned in the Goals, I thought that implementing a series could be solved by reflecting the directory structure. However, it's nice to have a title and description. I will make it possible to optionally place a meta.json file.
The profile will be unified in the same MD format. The image placement will be in the same hierarchy as posts, and by referencing it from the root / during writing, I will ensure that preview functions in VS Code and other editors can handle it.
Article Management on the Site
I tag the same topics. First, the YAML header included at the top of the .md file is as follows:
---
title: "Happy New Year"
date: "2024/1/1"
tags: ["Blog","Next.js","Markdown","Tailwind CSS"]
---
Body starts here
Only the title is mandatory. Others will be handled even if they are undefined. The tag management this time will also support full-width characters and spaces. This is to avoid the need for creating a correspondence table.
- For single posts
If the path is /posts/example.md, the URL will be [host]/post/example.
- For series
If the path is /posts/making-website/example.md, the URL will be [host]/post/making-website/example.
In this case, the series identifier is making-website.
If /posts/making-website/meta.json exists, it will be displayed according to the name and description in the file.
{
"name": "Building a Page",
"description": "Site construction with Next.js and GitHub API"
}
Comment Function Design
I decided to use Issues in the private repository for comment management. This is because they can be managed in the same repository and the form can be controlled using the Issue's own functions.
I made it possible to post comments without an account. However, I decided to implement:
- Posting interval limits per IP address
- Authentication via reCAPTCHA
Both serve as anti-spam measures.
Since the comment section functionality is insufficient, I will make it possible to use Issue features to:
- Allow/disallow comment posting via the lock function
- Enable/disable the comment section itself via opening/closing the Issue
Page Layout Structure
Since I'm building a blog site, I'll touch briefly on the layout.

Page Layout
As shown in the image, I combined display: flex and flex-direction. Since I don't use fixed, it's easy to build a responsive design.
Next, I'll move on to the implementation.
Before Implementation
In this implementation, I made sure that no code identifying myself is included, except for the later /src/static/constant.ts and the .env system.
Since I will be omitting some source code, please refer to the code block filenames if something is unclear.
For CSS, I will show the properties for width specifications and item placement methods, but omit the rest.
Implementation: As a Site
Create the project with $ pnpm create next-app.
├── public
├── src/
│ ├── api/
│ │ └── comment-submission/
│ │ └── route.ts
│ ├── app/
│ │ ├── post/
│ │ │ ├── [slug]/
│ │ │ │ └── page.tsx
│ │ │ └── page.tsx
│ │ ├── feed/
│ │ │ └── route.ts
│ │ ├── page.tsx
│ │ ├── layout.tsx
│ │ ├── not-found.tsx
│ │ ├── sitemap.ts
│ │ └── [...]
│ ├── components/
│ │ └── [...]
│ └── styles/
│ ├── global.css
│ └── [...]
├── .env
└── [...]
Implementing the Layout
First, let's set up layout.tsx.
export default function RootLayout({ children }) {
return (
<html lang="ja">
<head />
<body>
<Header />
<div className="md:flex justify-center">
<Menu />
{children}
</div>
<Footer />
</body>
</html>
);
}
I placed the header, footer, and main content inside the <body> tag. The main content is positioned using flex as per the Page Layout Structure and designed within each component. The left side is a common menu, so it will display the same content.
As an example, let's set up the page.tsx for the top page.
export default async function Blogs() {
return <Main>
<Side>
{/* Right menu */}
</Side>
<Section>
<Title>Title</Title>
{/* Content */}
</Section>
</Main>
}
<Main>, <Side>, <Section>, and <Title> are all called as common components.
This ensures that the layout remains consistent across all pages. Declarations are made in components under src.
export function Main({ children }: { children?: React.ReactNode }) {
return <main className="md:flex flex-row-reverse flex-grow md:flex-grow-0">
{children}
</main>
}
export function Side({ children }: { children?: React.ReactNode }) {
return <div className="hidden md:block">
<div className="w-full sticky">
{children}
</div>
</div>
}
export function Section({ children }: { children?: React.ReactNode }) {
return <section className="w-full mx-auto xl:m-0">
{children}
</section>
}
export function Title({ children }: { children: React.ReactNode }) {
return <h1 className="text-3xl">
{children}
</h1>
}
Components can be adjusted by whether or not { children: React.ReactNode } allows undefined.
To Use the GitHub API
Issuing a Token
Issue a Personal Access Token (PAT) so that you can use fetch. Since we do not require users to log in, we will not use OAuth.
Go to GitHub, select Menu → Settings → Developer settings → Personal access tokens → Tokens (classic), and click "Generate New Token" to issue one with repo permissions.
Adding the PAT to Environment Variables
Configure the environment variables.
In a React-based app, values written in a .env file at the root can be called within the source code. For example, by adding .env.local, you can set private environment variables that are not added to Git. This file is extremely important for public repositories.
GIT_TOKEN=(YOUR TOKEN HERE)
Other variables like the username, repository name, and post folder name are also declared as environment variables.
GIT_USERNAME=(YOUR USER NAME HERE)
GIT_REPO=(YOUR REPOSITORY NAME HERE)
GIT_POSTS_DIR=posts
GIT_IMAGES_DIR=img
GIT_PROFILE_PATH=profile/index.md
These have been aligned with the directory structure described in the Article Management Method section.
When using environment variables in TypeScript:
// string | undefined
const name = process.env.GIT_USERNAME
The type becomes string | undefined. You can define the type as a non-null string by writing it as follows:
// string
const name = process.env.GIT_USERNAME!
Implementation: Fetching and Displaying Articles
Calling via API
The API URL is as follows:
const gitContentPath = `https://api.github.com/repos/${process.env.GIT_USERNAME!}/${process.env.GIT_REPO!}/contents`
I have declared gitContentPath. Next, by adding the token to the fetch headers, it becomes an authorized API access, allowing you to reference private repositories.
Since I will be accessing api.github.com in several ways, I created multiple functions for the init? object.
- Header Information
export function getHeaders() {
return {
headers: {
"Authorization": `token ${process.env.GIT_TOKEN!}`,
"Content-Type": "application/json",
}
};
};
The Authorization header requires the format token "YOUR TOKEN HERE", not just the token string.
- Countermeasures for Next.js Caching
In Next.js, when you fetch a specific URL, the results are cached. By default, they are cached permanently, leading to undesirable situations where you must use "Ctrl + F5 during development" or "Clear Caching Data" in Vercel to refresh them.
Therefore, by including next in the init? object, you can specify the revalidation time in seconds. I use this extensively in this article.
export type FetchOptions = RequestInit & {
next?: { revalidate: number };
};
export function getNext(revalidate: number): FetchOptions {
if (revalidate === 0) {
return { cache: 'no-store' };
} else {
return { next: { revalidate } };
}
}
The getNext function receives revalidate: number and sets the cache time if it's non-zero. If it's 0, it determines that the latest state is required and returns cache: 'no-store'. For this reason, defining FetchOptions was necessary.
Fetching the List with GitHub API
Let's fetch the article list. First, if we only consider simple fetching, it would look like this:
const data = await fetch(`${gitContentPath}/${process.env.GIT_POSTS_DIR!}`, {
...getHeaders(), ...getNext(3600)
}).then(res => res.json()).catch(err => console.error(err));
Using getNext(3600), I set a cache period of 3600 seconds (1 hour).
data contains an array of filenames, directory names, URLs, etc.
Here, a problem arises: the list can only fetch up to 30 items at once. Even if you change the parameters, the maximum is 100, so you might not be able to retrieve everything. To fix this, you need to retrieve subsequent pages using the Link header in the response.
Therefore, I wrote the following code:
export async function fetchAllData(url: string, revalidate: number): Promise<any[]> {
let results: any[] = [];
let nextUrl: string | null = url;
while (nextUrl) {
const response: Response = await fetch(nextUrl, {
...getHeaders(), ...getNext(revalidate),
});
const data = await response.json();
results = results.concat(data);
const linkHeader = response.headers.get('Link');
if (linkHeader) {
const nextLinkMatch = linkHeader.match(/<([^>]+)>;\s*rel="next"/);
nextUrl = nextLinkMatch ? nextLinkMatch[1] : null;
} else {
nextUrl = null;
}
}
return results;
}
When obtaining the list, I decided to retrieve the following information:
-
slug: Page ID -
excerpt: Article summary (about 100 characters) -
data: YAML header (title, date, tags)
Following the Article Management on the Site rules, if /posts/making-website/example.md exists in the repository, it will be managed as slug = "making-website/example".
export type PostData = {
title: string;
tags?: string[];
date?: string;
series?: string;
[key: string]: any;
};
export type Post = {
slug: string;
excerpt: string;
data: PostData;
};
In this implementation, since I am supporting a series, folders are included. If data[i].type === 'dir', it is necessary to fetch that directory. To support fetching only a specific series by passing dir?: string as an argument, the function looks like this:
async function createPostFromFile(item: any, dir: string): Promise<Post | null> {
const { data, excerpt } = await getPostContent(`${dir}/${item.name}`);
if (data.title) {
return {
slug: item.path.replace(`${process.env.GIT_POSTS_DIR}/`, "").replace('.md', ''),
data,
excerpt,
};
}
return null;
}
async function createPostsFromDirectory(item: any): Promise<Post[]> {
const dirPath = `${process.env.GIT_POSTS_DIR}/${item.name}`;
const dirContent = await fetchAllData(`${gitContentPath}/${dirPath}`, 3600);
const markdownFiles = dirContent.filter((subItem) => subItem.type === "file" && subItem.name.endsWith('.md'));
const dirFiles = await Promise.all(markdownFiles.map(subItem => createPostFromFile(subItem, dirPath)));
return dirFiles.filter((post): post is Post => post !== null);
}
export const getPostsProps = cache(async (dir?: string): Promise<Post[]> => {
const targetDir = dir ? `${process.env.GIT_POSTS_DIR}/${dir}` : process.env.GIT_POSTS_DIR!;
const data = await fetchAllData(`${gitContentPath}/${targetDir}`, 3600);
const posts: Post[] = [];
for (const item of data) {
if (item.type === "file" && item.name.endsWith('.md')) {
const post = await createPostFromFile(item, targetDir);
if (post) {
posts.push(post);
}
} else if (!dir && item.type === "dir") {
const dirPosts = await createPostsFromDirectory(item);
posts.push(...dirPosts);
}
}
return posts.sort(comparePosts);
});
If data.title is missing when adding to the Post[] array, it is filtered out. This prevents errors during rendering.
I will also describe the getPostContent function. When specifying a file directly, the content contains base64-encoded content, so it needs to be decoded.
const getPostContent = cache(async (path: string): Promise<{ data: PostData; content: string; excerpt: string }> => {
const fileJson = await fetch(`${gitContentPath}/${path}`, {
...getHeaders(), ...getNext(3600)
}).then(res => res.json()).catch(err => console.error(err))
if (fileJson?.message === 'Not Found' || fileJson?.status === 404) {
notFound();
}
// Decoding
const buf = Buffer.from(fileJson.content, 'base64');
const fileContent = buf.toString("utf-8");
const { data, content } = matter(fileContent);
// If there is a subdirectory, add its name to series
const pathParts = path.split('/');
const outputData = pathParts.length > 2 ? { ...data, series: pathParts[1] } : data;
// Create an excerpt
const plainText = await MarkdownToPlainText(content);
const excerpt = makeExcerpt(plainText, 128);
return {
data: outputData as PostData,
content,
excerpt,
}
})
Providing a notFound function here allows you to return a 404 status in case of an unexpected page ID.
Displaying Articles
Now that we can fetch the articles, let's display them.
- Displaying the List of Articles
Create the post list in /src/app/post/page.tsx.
By importing the files created in Implementing the Layout, we can create a unified layout.
export default async function PostList() {
const posts = await getPostsProps();
return <Main>
<Side />
<Section>
<Title>Post List</Title>
<div className='flex flex-col'>
{posts.map((post, i) => <PostCard post={post} key={i} />)}
</div>
</Section>
</Main>
}

/post display
The main description is now very clean. By defining <PostCard />, we make it reusable in other components.
export default function PostCard({ post }: { post: Post }) {
return <div>
<div><Link href={`/post/${post.slug}`}>
<div className="flex items-center">
<DateCard date={post.data.date} />
<div>
<p>
{post.data.series ? <span>Series</span> : <></>}
<span>{post.data.title}</span>
</p>
<p>{makeExcerpt(post.excerpt, 64)}</p>
</div>
</div></Link>
</div>
{post.data.tags || post.data.series ?
<div className='flex flex-wrap'>
{post.data.series ? <Link href={`/series/${post.data.series}`}>
<div>
<span>View Series</span>
</div>
</Link> : <></>}
{post.data.tags?.map((tag, i) => <TagBanner tag={tag} key={i} />)}
</div> : <></>}
</div>
}
- Displaying the Article
Now, let's display the article as a blog post. Create the page in /src/app/post/[...slug]/page.tsx.
Using [ ] in the directory name enables Dynamic Routes.
As stated in the official documentation, the type in TypeScript varies depending on how the [ ] is written. Since slug already includes /, it is a multi-layered directory, so the specification method is [...slug].
[[...slug]] would also target undefined as slug?: string[]. In this case, it would also pick up the post list page, so we won't use it here.
const getFileContent = cache(async (path: string) => {
const decodedSlug = decodeURIComponent(path);
const postPath = `${process.env.GIT_POSTS_DIR!}/${decodedSlug}.md`
return await getPost(postPath);
})
export default async function Post({ params }: { params: { slug: string[] } }) {
const slug = params.slug.join('/')
const { data, content } = await getFileContent(slug);
const issue = await getCommentList(slug);
return <Main>
<SideMDShown>
<PostIndex content={content} title={data.title} />
<div>
<div>Share</div>
<ShareButtons path={`/post/${slug}`} text={data.title} />
</div>
</SideMDShown>
<Article data={data} content={content} issue={issue} slug={slug} />
</Main>
}
The getFileContent function is reused when generating Metadata. The main part of the article is componentized into <Article />. This is intended to keep page.tsx clean and to output the same layout for /profile.
export default async function Article({ data, content, issue, slug }: { data: PostData, content: string, issue?: Issue, slug?: string }) {
const series = data.series ? await getSeries(data.series) : undefined;
return <article className="w-full">
<div className="flex items-center">
<DateCard date={data.date} />
<h1>{data.title}</h1>
</div>
{data.tags ?
<div className="flex flex-wrap">
{data.tags?.map((tag, i) =>
<TagBanner tag={tag} key={i} />)}
</div> :
<></>}
{series ?
<div>
<SeriesCard
slug={data.series}
index={series.posts.findIndex((item) => item.slug === slug)}
/>
</div> : <></>}
<PostMarkdown content={content} />
{/* Comment section goes here */}
</article>
}
![/post/[...slug] display](https://res.cloudinary.com/zenn/image/fetch/s--EjouhDuC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_1200/https://storage.googleapis.com/zenn-user-upload/deployed-images/a03d6723d811280244f900a6.png%3Fsha%3Dad21b87e4b45713293a1aaa21b0a35838c8140a5)
/post/[...slug] display
I fetched the series using the getSeries function with data.series (returned by the getPost function) as an argument.
As there are many parameters confirmed to be referenced via data.*, such as in <PostCard /> and <Article />, I declared types for some variables in /src/static/postType.ts in Fetching the List with GitHub API and used [key: string]: any to support undefined keys as well.
issue will be utilized in the next section.
Displaying Images within Articles
I am converting the string written in MD format using <PostMarkdown content={content} />. In this case, I am using <ReactMarkdown />.
<ReactMarkdown
disallowedElements={["h1"]}
components={components}
remarkPlugins={[remarkMath, remarkGfm]}
rehypePlugins={[rehypeRaw]}>
{content}
</ReactMarkdown>
I exclude h1 because it causes layout issues. The components prop calls specified functional components when HTML tags are converted into custom elements.
function getMimeType(path: string) {
const ext = path.split('.').pop()?.toLowerCase();
switch (ext) {
case 'jpg':
case 'jpeg':
return 'image/jpeg';
case 'png':
return 'image/png';
case 'gif':
return 'image/gif';
case 'webp':
return 'image/webp';
case 'bmp':
return 'image/bmp';
default:
return 'application/octet-stream';
}
}
async function ExImg({ path, alt }: { path: string, alt?: string }) {
const image64 = await getImage(path);
const mimeType = getMimeType(path);
return <img alt={alt} src={`data:${mimeType};base64,${image64}`} />
}
// h2, h3 are omitted
const Img = ({ node, ...props }:
ClassAttributes<HTMLImageElement> &
HTMLAttributes<HTMLImageElement> &
ExtraProps & { src?: string, alt?: string }) => {
const src = props.src as string || '';
const alt = props.alt as string || '';
if (src.startsWith(`/${process.env.GIT_IMAGES_DIR!}/`)) {
return <ExImg path={src} alt={alt} />
} else
return (
<img {...props}>{props.children}</img>
);
};
const Pre = ({ children, ...props }:
ClassAttributes<HTMLPreElement> &
HTMLAttributes<HTMLPreElement> &
ExtraProps) => {
if (!children || typeof children !== 'object') {
return <code {...props}>{children}</code>
}
const childType = 'type' in children ? children.type : ''
if (childType !== 'code') {
return <code {...props}>{children}</code>
}
const childProps = 'props' in children ? children.props : {}
const { className, children: code } = childProps
const classList = className ? className.split(':') : []
const language = classList[0]?.replace('language-', '')
const fileName = classList[1]
return (
<div className="post_codeblock w-full">
{fileName && (
<div className="post_fname">
<span>{fileName}</span>
</div>
)}
<SyntaxHighlighter language={language} style={atomOneDark}>
{String(code).replace(/\n$/, '')}
</SyntaxHighlighter>
<CopyToClipboard text={String(code).replace(/\n$/, '')} />
</div>
)
}
const A = ({ href, ...props }:
ClassAttributes<HTMLAnchorElement> &
HTMLAttributes<HTMLAnchorElement> &
{ href?: string }) => {
const isInternalLink = href?.startsWith("/");
return isInternalLink ? (
<a href={href} {...props}>{props.children}</a>
) : (
<a href={href} target="_blank" rel="noopener noreferrer" {...props}>{props.children}</a>
);
};
export const components: Partial<Components> = {
pre: Pre, h2: H2, h3: H3, img: Img, a: A
}
The mappings are created in JSON format within components.
The <a> tag is determined as an internal link if it starts with / and is forwarded as is; otherwise, target="_blank" rel="noopener noreferrer" is added to open it in a new tab.
The <img> tag is output as is if the path does not start with /posts (any name)/. Otherwise, since it needs to be retrieved from GitHub, a fetch is performed. However, if an image exceeds 1MB, it cannot be retrieved in the same way as articles, so I perform another fetch using the git_url obtained at the same time. The image is obtained via base64 encoding and can be displayed by inserting the content along with identification tags into the src. I have supported multiple image extensions in the ExImg function. The getImage function is shown below.
export const getImage = cache(async (path: string) => {
const fileJson = await fetch(`${gitContentPath}${path}`, {
...getHeaders(), ...getNext(3600 * 24 * 30)
}).then(res => res.json()).catch(err => console.error(err));
// Fetch again using git_url
const imageJson = await fetch(fileJson.git_url, {
...getHeaders(), ...getNext(3600 * 24)
}).then(res => res.json()).catch(err => console.error(err));
return imageJson.content as string;
})
Implementation: Comment Form

Overview of the comment form
Fetching Comments
I will create a comment section using the Issues of the repository where the MD files are stored. I will fetch them in the same way as the articles.
Define the necessary types for Issues and Comments.
-
Comment: A comment
- date: Date posted
- content: Content (MD format)
-
Issue: An Issue
- comments: Array of comments
- locked: Whether the Issue is locked
-
state: Whether the Issue is
openorclosed
export type Comment = {
date: string,
content: string
}
export type Issue = {
comments: Comment[],
locked: boolean,
state: "open" | "closed"
}
I will create the getCommentList function. Issues are searched by an exact title match. Since the title is set as the slug, a simple search is possible.
export const getCommentList = cache(async (slug: string): Promise<Issue> => {
const targetIssue = await getIssue(slug);
if (targetIssue) {
const data = await fetch(targetIssue.commentsURL, {
...getHeaders(), ...getNext(20),
})
.then((res) => res.json())
.catch((e) => console.error(e));
const comments: Comment[] = [];
for (const item of data) {
const date = new Date(item.created_at as string);
comments.push({
date: date.toLocaleString("ja-JP"),
content: item.body as string,
});
}
return {
comments,
locked: targetIssue.locked,
state: targetIssue.state
};
} else {
createIssue(slug);
return {
comments: [],
locked: false,
state: "open"
}
}
});
- getIssue function
Combine the fetchAllData function with a title search (${gitIssuePath}?q=${encodeURIComponent(slug)}+in:title&state=all).
const gitIssuePath = `https://api.github.com/repos/${process.env.GIT_USERNAME!}/${process.env.GIT_REPO!}/issues`;
const getFilteredIssuePath = (slug: string) =>
`${gitIssuePath}?q=${encodeURIComponent(slug)}+in:title&state=all`;
async function getIssue(slug: string, revalidate: number = 120) {
const data = await fetchAllData(getFilteredIssuePath(slug), revalidate);
if (data && data.length > 0) {
const issue = data.find((item: any) => item.title === slug);
if (issue) {
return {
slug: issue.title as string,
commentsURL: issue.comments_url as string,
locked: issue.locked as boolean,
state: issue.state as "open" | "closed"
};
}
}
return null;
}
- createIssue function
I created a map variable called issueCreationMap. By setting the key as a string and the value as a Promise<void>, the function logic can be written at the same time as the assignment. By deleting the key upon completion, it is possible to recreate the Issue if it is deleted later.
The reason for this approach is that if createIssue is called when getIssue returns null, but multiple requests arrive simultaneously, duplicate Issues could be created. Therefore, I ensure that simultaneous execution does not occur based on the presence of the key.
const issueCreationMap: Record<string, Promise<void> | undefined> = {};
const createIssue = cache(async (slug: string) => {
if (!issueCreationMap[slug]) {
issueCreationMap[slug] = (async () => {
const targetIssue = await getIssue(slug, 0);
if (targetIssue) return;
const data = {
title: slug,
body: `${process.env.NEXT_PUBLIC_URL!}/post/${slug}`,
labels: ["user-comment"],
};
await fetch(gitIssuePath, {
method: "POST",
body: JSON.stringify(data),
...getHeaders(),
})
.then((res) => {
if (res.status !== 201) {
console.error(`Error creating issue: ${res.status} - ${res.statusText}`);
} else {
console.log(`Issue created successfully for slug: ${slug}`);
}
})
.catch((e) => console.error(e));
})();
issueCreationMap[slug].finally(() => {
delete issueCreationMap[slug];
});
return issueCreationMap[slug];
} else {
return issueCreationMap[slug];
}
});
reCAPTCHA Setup
I will implement reCAPTCHA before displaying the comment form.
I will skip the steps for issuing the site key and secret key here.
pnpm add react-google-recaptcha-v3
Next, add the environment variables to .env.local.
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=(YOUR KEY HERE)
RECAPTCHA_SECRET_KEY=(YOUR KEY HERE)
Displaying Comments
Place the <GoogleReCaptchaProvider /> in a client component.
"use client";
import { GoogleReCaptchaProvider } from "react-google-recaptcha-v3";
function CommentsView({ comments }: { comments: Comment[] }) {
return <div className="flex flex-col">
{comments.length > 0 ? comments.map((comment, i) => (
<div key={i} className="block items-start lg:flex">
<DateCard date={comment.date} />
<div className="flex-grow min-w-0">
<CommentMarkdown content={comment.content} />
</div>
</div>
)) :
<ExplainingBanner>
No comments yet
</ExplainingBanner>}
</div>
}
export function CommentForm({ comments, slug }: { comments: Comment[], slug: string }) {
return <GoogleReCaptchaProvider
reCaptchaKey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY!}
language="ja">
<section>
<h2>Comments</h2>
<CommentsView comments={comments} />
<PostingForm slug={slug} />
</section>
</GoogleReCaptchaProvider>
}
Like NEXT_PUBLIC_RECAPTCHA_SITE_KEY, environment variables starting with NEXT_PUBLIC_ are inlined so they can be used on the client side. If they are missing, they become undefined, reCAPTCHA will not start, and the badge will not be displayed in the bottom right.
- Creating the Form
This is also created as a client component. I will show the full code first and then explain it.
'use client';
import { useGoogleReCaptcha } from "react-google-recaptcha-v3";
export default function PostingForm({ slug }: { slug: string }) {
const [inputtedValue, setInputtedValue] = useState<string>("");
const [isInputting, setIsInputting] = useState<boolean>(true);
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
const [notificationBanner, setNotificationBanner] = useState<React.ReactNode>()
const { executeRecaptcha } = useGoogleReCaptcha();
const handleSubmit = async () => {
setNotificationBanner(null);
if (inputtedValue.trim() === "") {
setNotificationBanner(GenerateNotificationBanner("Comment is required", false));
return;
}
if (!executeRecaptcha) {
setNotificationBanner(GenerateNotificationBanner("Could not execute reCAPTCHA", false));
return;
}
const token = await executeRecaptcha('submitComment');
setIsSubmitting(true);
try {
const response = await fetch('/api/comment-submission', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ slug, comment: inputtedValue, token }),
});
if (response.ok) {
setNotificationBanner(GenerateNotificationBanner("Comment sent", true));
setInputtedValue("");
} else {
const data = await response.json();
setNotificationBanner(GenerateNotificationBanner(`Failed to send comment: ${data.error}`, false));
}
} catch (e) {
setNotificationBanner(GenerateNotificationBanner(`Failed to send comment: ${e}`, false));
} finally {
setIsSubmitting(false);
}
}
return (
<div>
<div className="flex">
<button onClick={() => setIsInputting(true)}>Input Comment</button>
<button onClick={() => setIsInputting(false)}>Preview</button>
</div>
{isInputting ?
<textarea
onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) => setInputtedValue(e.target.value)}
value={inputtedValue}
placeholder="Markdown supported" /> :
<div>
{inputtedValue.trim() !== "" ? <CommentMarkdown content={inputtedValue} /> :
<ExplainingBanner>
Please enter a comment in "Input Comment" first, then try the preview
</ExplainingBanner>}
</div>
}
<div className="items-center flex flex-row-reverse">
<button onClick={handleSubmit} disabled={isSubmitting}>
{isSubmitting ? "Sending..." : "Send"}
</button>
<div className="flex-1">
This site is protected by reCAPTCHA and the Google <a href="https://policies.google.com/privacy">Privacy Policy</a> and <a href="https://policies.google.com/terms">Terms of Service</a> apply.
</div>
</div>
{notificationBanner ? notificationBanner : <></>}
</div>
)
}
A preview function is also implemented. The setInputtedValue function works on the onChange event of the <textarea>, changing the inputtedValue. The preview is displayed only when inputtedValue.trim() !== "", so whitespace is not displayed.
When the send button is pressed, the handleSubmit function is executed. First, it rejects empty strings. After confirming that executeRecaptcha is available, it executes the function. The string argument is likely fine as long as it can be distinguished as an event.
It sends a POST request to /api/comment-submission in the API Route. At that endpoint, it uses the GitHub API to submit the comment to the Issue. The body includes the article slug, the comment body, and the token obtained via the executeRecaptcha function.
If response.ok is received, a success status is displayed. The inputtedValue is cleared at the timing when the request finishes.
Since the authentication and submission logic are handled by the API, the amount of code in the component is minimal.
Creating an Authenticated Comment Submission API
Create /src/app/api/comment-submission/route.ts. Since we are using the App Router, function names must be defined using HTTP methods.
import { NextRequest, NextResponse } from 'next/server';
import { LRUCache } from 'lru-cache';
const rateLimit = new LRUCache<string, number>({
max: 1000,
ttl: 1000 * 60 * 60,
});
const getHeaders = () => {
return {
"Authorization": `token ${process.env.GIT_TOKEN!}`,
"Content-Type": "application/json",
};
};
const authorize = async (token: string) => {
const secretKey = `secret=${process.env.RECAPTCHA_SECRET_KEY!}&response=${token}`;
const data = await fetch("https://www.google.com/recaptcha/api/siteverify", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: secretKey,
}).then(res => res.json());
return data;
}
export async function POST(req: NextRequest) {
const { slug, comment, token } = await req.json();
const ip = req.ip || req.headers.get('x-forwarded-for') || 'unknown';
if (!slug || !comment || !token) {
return NextResponse.json({ error: 'Missing slug or comment body' }, { status: 400 });
}
const requestCount = rateLimit.get(ip) || 0;
if (requestCount > 10) {
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
}
rateLimit.set(ip, requestCount + 1);
const recaptchaJson = await authorize(token);
if (!recaptchaJson.success) {
return NextResponse.json({ error: "ReCAPTCHA verification failed" }, { status: 401 })
}
try {
const issueResponse = await fetch(`https://api.github.com/repos/${process.env.GIT_USERNAME!}/${process.env.GIT_REPO!}/issues`, {
headers: getHeaders(),
});
const issues = await issueResponse.json();
const issue = issues.find((issue: any) => issue.title === slug);
if (!issue) {
return NextResponse.json({ error: `Issue with slug "${slug}" not found` }, { status: 404 });
}
// Adding the comment
const commentsURL = issue.comments_url;
const data = {
body: comment,
};
const response = await fetch(commentsURL, {
method: 'POST',
headers: getHeaders(),
body: JSON.stringify(data),
});
if (response.ok) {
return NextResponse.json({ message: 'Comment added successfully' }, { status: 200 });
} else {
const errorText = await response.text();
return NextResponse.json({ error: `Failed to add comment: ${errorText}` }, { status: response.status });
}
} catch (e) {
console.error('Error adding comment:', e);
return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
}
}
Retrieve the data from the body using req.json().
const { slug, comment, token } = await req.json();
As specified in the Comment Function Design, we obtain the IP address from req to implement posting interval limits per IP address.
At this point, if any required data is missing from the body, a 400 error is returned.
Check the request count for the IP address. Using lru-cache, we grant up to 10 posting request rights per hour to a maximum of 1000 people. If the limit is exceeded, a 429 error is returned. If it is within the limit, the count is incremented by 1 and processing continues.
const requestCount = rateLimit.get(ip) || 0;
if (requestCount > 10) {
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
}
rateLimit.set(ip, requestCount + 1);
Verify the reCAPTCHA authentication result using the token. Since RECAPTCHA_SECRET_KEY is called within the API Route, it is not visible on the client side. If data.success is true, processing continues; if false, it's an unauthorized submission, and a 401 error is returned.
const authorize = async (token: string) => {
const secretKey = `secret=${process.env.RECAPTCHA_SECRET_KEY!}&response=${token}`;
const data = await fetch("https://www.google.com/recaptcha/api/siteverify", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: secretKey,
}).then(res => res.json());
return data;
}
Once the target Issue is found, a POST request is sent to that page. If ok is successfully returned, it is a success.
I have provided branching for different statuses to handle potential issues.
Comment Access Management
This section covers the access rights configuration mentioned in the Comment Function Design.
While you are free to close the comment section, it is important to not provide posting or viewing functionality on the client side. Therefore, we switch components at the server-side level, just like in the <Article /> component.
-
Allow/disallow comment posting via the lock function:
Call a comment section component that does not include reCAPTCHA and the posting form. -
Enable/disable the comment section itself via opening/closing the Issue:
Do not call the comment section component at all from the server side.
Add the following to the {/* Comment section goes here */} part of /src/components/layout/ArticlePage.tsx.
export default async function Article({ data, content, issue, slug }: { data: PostData, content: string, issue?: Issue, slug?: string }) {
const series = data.series ? await getSeries(data.series) : undefined;
return <article className="w-full">
<div className="flex items-center">
<DateCard date={data.date} />
<h1>{data.title}</h1>
</div>
{data.tags ?
<div className="flex flex-wrap">
{data.tags?.map((tag, i) =>
<TagBanner tag={tag} key={i} />)}
</div> :
<></>}
{series ?
<div>
<SeriesCard
slug={data.series}
index={series.posts.findIndex((item) => item.slug === slug)}
/>
</div> : <></>}
<PostMarkdown content={content} />
- {/* Comment section goes here */}
+ {issue && slug ?
+ issue.state === "closed" ?
+ <ExplainingBanner>
+ Comments are disabled
+ </ExplainingBanner> :
+ issue.locked ?
+ <CommentFormNoPosting comments={issue.comments} /> :
+ <CommentForm comments={issue.comments} slug={slug} /> :
+ <></>}
</article>
}
I created conditional branches, giving the highest priority to the closed state.

Comment section disabled (closed)

Posting form disabled (locked)
Implementation: As a Blog
Since it's a blog, I will implement a sitemap and RSS. Additionally, I will generate metadata dynamically.
Implementing Metadata
I define the properties to be added commonly as a function in /src/lib/SEO.ts.
interface Props {
title?: string,
description?: string,
url: string,
imageURL?: string,
keywords?: string[],
type?: OpenGraphType,
}
export function generateMetadataTemplate(props: Props): Metadata {
const { title, description, url, keywords, type } = props;
const outputTitle = title
? `${title} - ${siteName}`
: siteName;
const outputDescription = description
? description
: siteDescription;
const outputType: OpenGraphType = type ? type : "website";
const metadata: Metadata = {
metadataBase: new URL(process.env.NEXT_PUBLIC_URL!),
authors: { name: author.name, url: author.url },
title: outputTitle,
description: outputDescription,
icons: "/favicon.ico",
keywords,
openGraph: {
title: title ? title : siteName,
description: outputDescription,
url: url,
siteName,
type: outputType,
},
};
return metadata;
}
metadataBase is used to complement relative paths.
metadataBase is a convenient option for setting a base URL prefix for metadata fields that require a fully qualified URL. When using metadataBase, you can use relative paths for URL-based metadata fields defined below the current route segment, which would otherwise require an absolute URL. The relative path of a field is combined with metadataBase to form a fully qualified URL. (Machine Translation)
Call it in each page.tsx as follows. For /src/app/post/[...slug]/page.tsx, it looks like this:
export async function generateMetadata({ params }: { params: { slug: string[] } }): Promise<Metadata> {
const slug = decodeURIComponent(params.slug.join('/'));
const { data, excerpt } = await getFileContent(slug);
return generateMetadataTemplate({
title: `${data.title}`,
description: `${excerpt}`,
url: `/post/${params.slug.join('/')}`,
type: "article",
});
}
Implementing RSS
I created an RSS feed accessible at /feed. According to Google, RSS can also be used for sitemap submission.
import Rss from 'rss';
export const dynamic = "force-dynamic";
export const revalidate = 1200;
const baseURL = process.env.NEXT_PUBLIC_URL!;
export async function GET() {
const feed = new Rss({
title: `${siteName} New Posts`,
description: `Post feed for "${siteName}"`,
feed_url: `${baseURL}/feed`,
site_url: baseURL,
language: 'ja'
});
const posts = await getPostsProps();
posts.forEach((post) => feed.item({
title: post.data.title,
description: post.excerpt,
url: `${baseURL}/post/${encodeURIComponent(post.slug)}`,
date: post.data.date ? new Date(post.data.date).toISOString() : new Date(lastModified).toISOString()
}))
return new Response(feed.xml(), {
headers: {
'Content-Type': 'application/xml',
'Cache-Control': `s-maxage=${revalidate}, stale-while-revalidate`
}
});
}
In this way, I added all posts as items.
Implementing a Sitemap
export const dynamic = "force-dynamic";
export const revalidate = 0;
const staticPaths = [
"/post",
"/profile",
"/series",
"/tags"
]
export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
const posts = await getPostsProps();
const tagsWithDate = getTagsWithLatestDate(posts);
const baseURL = process.env.NEXT_PUBLIC_URL!;
const staticPages: MetadataRoute.Sitemap = [
{
url: baseURL,
priority: 1.0,
}
];
staticPaths.forEach((page) => {
staticPages.push({
url: baseURL + page,
priority: 0.9
})
})
const dynamicPages: MetadataRoute.Sitemap = [];
tagsWithDate.forEach((tagWithDate) => {
dynamicPages.push({
url: baseURL + "/tags/" + encodeURIComponent(tagWithDate.tag),
lastModified: tagWithDate.latestDate ? new Date(tagWithDate.latestDate) : lastModified,
changeFrequency: "monthly",
priority: 0.8
})
})
return [...staticPages, ...dynamicPages];
}
I add static pages by iterating through the staticPaths array. Only /tags/[slug] was added as a dynamically generated page. At that time, I retrieve the date of the latest post within that tag.
Some site software only aggregates other pages on the site, which can make it difficult to determine the last updated date for homepages or category pages. In such cases, it is fine to omit the lastmod for those pages.
Based on this, I decided not to add lastmod to staticPages.
Deploying to Vercel
I recommend reviewing your environment variables once before deploying. For example, ensure that the domain you plan to assign is entered in NEXT_PUBLIC_URL in .env.production. Also, run pnpm build to confirm that it builds successfully locally.
Configure the environment variables at the same time as deploying to Vercel.
When selecting your project uploaded to GitHub, there is a field to register Environment Values. Add the following environment variables.
GIT_USERNAME=(YOUR GITHUB USERNAME HERE)
GIT_REPO=(YOUR GITHUB REPOSITORY NAME HERE)
GIT_POSTS_DIR=posts
GIT_IMAGES_DIR=img
GIT_PROFILE_PATH=profile/index.md
GIT_TOKEN=(YOUR PAT HERE)
NEXT_PUBLIC_RECAPTCHA_SITE_KEY=(YOUR TOKEN HERE)
RECAPTCHA_SECRET_KEY=(YOUR TOKEN HERE)
You might see a message saying that since NEXT_PUBLIC_RECAPTCHA_SITE_KEY contains both NEXT_PUBLIC_ and KEY, it will be made public.
All that's left is to deploy.
Conclusion
I will omit CSS as it is not the main topic of this article. I have summarized it as a series on my blog, so please refer to it.
I have built several sites with Next.js. I'm currently in a process of trial and error regarding which servers or services to place dynamic page elements on. Since the GitHub API call limit is stated as 5,000 times per hour, setting revalidate to 0 could quickly make it unusable under heavy access. I want to achieve an appropriate update frequency while adjusting cache times. Thank you very much.
Discussion