How To Make This Blog Site
Oct 23, 2024
HomeThis site creates statically generated and search engine optimized posts out of markdown files, displays them nicely, and provides a way to view them all.
Everything from the title to the URL slug to the text content is all part of one markdown file.
Add a file to the /posts
folder, and a new post is born.
How do we build it?
All we really need is this example from the Next.js SSG (Static Site Generation) documentation. Statically generating blogs are not hard!
Here, I'll explain how it all works.
If at any point you need more context, see my site's Github repository.
0. Code environment
This is a Next.js site built with tailwind.css and shadcn/ui, and hosted on Vercel for free. If you've got that set up then following along will be a breeze. If you don't, start here and you'll be caught up in 2 minutes.
1. Support front matter
Front matter is used as metadata for all kinds of files, including markdown files. For our blog, we'll be adhering to these custom-defined types, and using gray-matter for actually reading the front matter.
2. Parse the markdown
The next step is using remark to convert our markdown files into HTML. Specifically, remark-html gets the job done in just one line:
const HTML = await remark().use(html).process(MARKDOWN).toString();
3. Create the posts
Only three things now need to happen for the posts to be made.
- Generate the post's metadata with generateMetadata.
- Generate the post's url slug from its file name using generateStaticParams.
- Serve the post's page contents, which come from the code on the previous step.
4. Style the posts
The last technical aspect of our static blog generation is styling the interface. Luckily, CSS modules and the @apply
directive make the job easy. After adding our styles to a CSS module and importing it like so, we're off to the races!
import markdownStyles from "./markdown-styles.module.css";
export default function PostBody({ content }: { content: string }) {
return (
<article
className={markdownStyles["markdown"]}
dangerouslySetInnerHTML={{ __html: content }}
/>
);
}
Is that it?
Yup! If you'd like to take a closer look at the code, feel free to explore the files here on github or give it a star if you found this helpful. The code is quite clean, so you should have no trouble navigating it.
While this post does provide the basics to get you up and running, I did skip over a number of web essentials. Be sure to take a look at RSS feeds, sitemaps, robots, and manifests, if you want to do everything right. Heck, you could even make a humans.txt like me and Google while you're busy checking every box.
Thanks for reading my first blog post!