Since the arrival of MDX, there's been a lot of excitement in the React developer community and the potential use cases for it, most notably, for things like building a blog. If you've been thinking about building a blog with MDX, you may be also considering which technology stack to use.
After some careful consideration myself, I found that building a blog with the Next.js framework had great built-in support for MDX. It also has the capability to support any future directions a blog might need to go.
In this guide, you'll find everything you need to know to build a successful blog with MDX and Next.js, including:
This article will focus primarily on using remote MDX to build blog pages with MDX.
What is an MDX blog?
MDX is a great way to combine standard HTML Markdown and React JSX components within the same page content.
This gives the ability to create more robust and interactive page content while also keeping Markup simple and easy to read and edit.
Why is MDX important for blogs?
Blogs have become one of the primary ways to generate organic traffic to your site. Creating highly SEO optimized blog pages can have a tremendous impact on your page ranking.
MDX can also be used in areas like:
Product marketing
Marketing campaigns
Landing pages
Sales presentations
And other forms of commercial presentation.
Imagine being able to easily embed some sales or marketing campaign banners and charts into an easy to maintain Markdown page.
Why use Next.js for blogs?
The Next.js framework eliminates the need for tons of boilerplate code to get up and running quickly and is fully optimized for rapid development and versatility.
The other benefits include:
Static Site Generation (SSG), allowing for pure HTML rendered pages.
Server Side Rendering (SSR), using advanced forms of React Server Components (RSC).
API built-in support, if your blog should need to access external resources.
Dynamic Routing using the app router, which can makes creating pages much easier.
Authentication and Authorization if this is eventually needed.
Getting started building a blog
If you don't already have a Next.js application set up, you can easily create one to follow along with these examples.
Bash
1npx create-next-app@latest
You will see some options when creating the app. I recommend using TailwindCSS which is what I'll be using for this article.
Next, I'll be installing the following pacakges which I'll be using in the article.
Bash
1npm install next-mdx-remote globby moment @tailwindcss/typography
A few blog building tips
Before we get started, here's some key things I've learned when building blogs that can really improve the process:
Use a lib directory for config, utilities, services and other non-UI code.
Learn about the advantages of using the Next.js framework over standard React tools such as create-react-app.
Jul 6, 2024
Stay in the loop
Get the latest articles delivered to your inbox. No spam, unsubscribe anytime.
components
Try to keep any custom components as leaf (a.k.a dumb components) components and pass the data they need as props rather than using fetch inside them.
Keep a common content location under your project root, for example /content and then use sub-directories for more specific content, like /content/blog/sports or /content/blog/finance.
Also, for this article, I will use the default path alias conventions using Typescript defined in the tsconfig.json file.
tsconfig
JSON
1{
2 "compilerOptions": {
3 "paths": {
4 "@/*": [
5 "./*"
6 ]
7 }
8 }
9}
Simple Blog demo
For this article I'll be creating a simple blog that talks about food related topics and will include the following pages and components:
Blog grid: This page will list all of the available posts as cards in a grid column format. This page will show single column for mobile and three columns on medium size screens.
Blog detail: This page will display the page MDX Markdown and any Front Matter associated with this post.
Blog header: A reusable blog header that will display any Front Matter with title.
Blog card: A reusable blog card that will be used in the grid view to list any posts and display any Front Matter with title, author and published date.
Blog grid listing page
Blog detail page
Blog project structure
Here's the outline of the project structure we'll use to build this blog.
Bash
1your-project
2 ├── app
3 │ ├── blog
4 │ │ ├── [slug]
5 │ │ │ └── page.tsx
6 │ │ ├── layout.tsx
7 │ │ └── page.tsx
8 │ └── layout.tsx (root layout)
9 ├── lib
10 │ └── mdx
11 │ ├── config.ts
12 │ └── types.ts
13 ├── components
14 │ ├── markdown.tsx
15 │ ├── card.tsx
16 │ └── header.tsx
17 └── content
18 └── blog
19 └── food
20 ├── recipes
21 │ └── best-summer-recipes.mdx
22 └── food-reviews.mdx
Blog project code
Here's all of the code for the blog. I'll annotate some of the key points for these code blocks.
Let's start with the two app router pages, which will share a layout.tsx.
/blog - routes to the blog grid card listing page.
/blog/[slug] - routes to the actual blog post by slug name.
Using slugs will have SEO benefits and will also help visitors decide whether to click on a link. Make your slug names readable and a preview of what the link contains.Bad: /blog/food-details
Good: /blog/top-food-reviews
Good: /blog/top-food-reviews-in-california
This page displays a grid listing of blog posts using cards and does the following:
Finds all the MDX files under the /content/blog directory using a glob pattern matcher.
Parses each file and extracts the frontmatter content object using the compileMDX from the next-mdx-remote/rsc.
Creates an array and then filters it based on published and draft status.
The next-mdx-remote/rsc modules are specifically for compliling using React Server Components (RSC). Since Next.js 13, all modules are by default server side rendered. In this example all of the blog pages are fully rendered as RSC.
Blog card
TSX
1importLinkfrom'next/link';
2import{Blog}from'@/lib/mdx/types';
3importmomentfrom'moment';
4
5functionBlogCard({ title, slug, author, date }:Blog){
35 Ooops... the blog post <i>{slug}</i> was not found{' '}
36</p>
37</div>
38);
39};
40
41const blogContent =getDocumentBySlug(slug);
42
43const mdxRemoteOptions:MDXRemoteProps={
44...defaultMdxOptions,
45 source: blogContent,
46};
47
48return(
49<div>
50<divclassName="p-4">
51<Linkhref="/blog">More Blogs</Link>
52</div>
53<divclassName="prose p-3">
54{!blogContent ?(
55<NotFoundslug={slug}/>
56):(
57<MDXRemote{...mdxRemoteOptions}></MDXRemote>
58)}
59</div>
60</div>
61);
62}
63
64exportdefaultBlogPage;
Let's break this page down, since there's a lot happening here.
This is a dynamic route page where all of the blog post content is loaded by the slug param and displayed and does the following:
Gets the slug from the params prop.
Finds the MDX file using a glob pattern by slug and takes the first array index.
Creates an options object using the MDXRemoteProps options.
Adds the options object as props for the <MDXRemote> which basically calls compileMDX behind the scenes and then renders the MDX serialized content as HTML.
The mdxRemoteOptions derives its defaults from a config object located in the lib directory but can be overriden here if needed.
Here's a quick breakdown on the available options object:
scope - Pass in any variables and reference them in MDX using {myVariable} expression.
source - MDX content string from the file.
components - Adds two components BlogHeader and Markdown.
parseFrontmatter - Signals to parse the Front Matter meta data, otherwise meta data will be rendered as plain text.
mdxOptions - Add any available Remark or Rehype plugins to transform and enhance your MDX Markdown content.
Since TailwindCSS omits base styles for most HTML elements, it comes with the prose typography plugin from @tailwind/typography to wrap any section of content with great styles.
You may have noticed that I wrapped all of the MDX content insided the prose class wrapper to apply these styles.
To add the prose typography, you'll need to add the following plugin to your tailwind.config.ts.
This page puts all of the HTML element components in a Markdown component and spreads the values in the options.
These HTML component definitions are completely optional. The prose class will provide a good amount of styles but occasionally you may want to customize the theme.
Blog types
TSX
1exporttypeBlog={
2 title?:string;
3 description?:string;
4 author?:string;
5 slug?:string;
6 tags?:string[];
7 keywords?:string[];
8 categories?:string[];
9 date?:string;
10 draft?:boolean;
11 published?:boolean;
12};
Here's the Blog TypeScript type that will define the Front Matter structure. This will provide some intellesence when destructuring the frontmatter object.
Blog header component
TSX
1import{Blog}from'@/lib/mdx/types';
2importmomentfrom'moment';
3
4functionBlogHeader({ title, author, date }:Blog){
This will be the only custom MDX component for this demo but it will demonstrate how to access and use the frontmatter object that's available in the MDX scope.
This component accepts a Blog type as props, so we'll be able to spread the frontmatter object as props and show the author and published date.
MDX content pages
And finally, here's the MDX sample blog post content that requires .mdx extension for each of the MDX post pages under the /content/blog directory.
One thing to note is that the file name must match the slug key in the Front Matter meta info without the extension.
Also, the Front Matter needs to be at the top of the page and between the --- open and close delimiter section.
Markdown
1---
2title: Food Reviews
3description: Food reiews for the year.
4authors: Harry Dunne
5date:2024-03-15T07:52:57.880Z
6slug: food-reviews
7published:true
8draft:false
9tags:
10- Dining Review 2024
11keywords:
12- Top Food Reviews
13- Food 2024
14categories:
15- Food Reviews
16---
17
18<Header{...frontmatter}/>
19
20# Top Dining Experiences In 2024
21
22We've compiled some of the best dining experiences in this year.
23
24## Reviews in 2024
25
26Best reviews for restaurants around the country in 2024. Top 5 places ranked.
27- Big Jim's Steak House
28- Five Points Pizza
29- The Vortex
30- Five Sisters Blues Cafe
31- Five Loaves Cafe
32
33>✭✭✭✭✭ - *"A Delightful dining experience." - L. Christmas*
34
35<br/>
36<br/>
Markdown
1---
2title: Best Recipes for Summer
3description: Best recipes for summer picnics and outings
4authors: Lloyd Christmas
5date:2024-03-15T07:52:57.880Z
6slug: best-summer-recipes
7published:true
8draft:false
9tags:
10- BBQ
11keywords:
12- Top BBQ
13- Best Ribs
14categories:
15- Summer Recipes
16---
17
18<Header{...frontmatter}/>
19
20# Top BBQ and Grill Ideas for Summer
21
22We've selected some of the best BBQ and grilling ideas for summer.
23
24## 5 Tasty BBQ Ideas
25
26- Shortcut BBQ Ideas
27- BBQ and pulled pork
28- Texas Brisket
29- Rib dry rub
30- Tri-tip plates
Running the blog
At this stage when all of the code is added to the project, you'll be able to run the blog demo by starting the dev server.
Bash
1npm run dev
Point a browser to localhost:3000/blog and you'll see the blog grid listing.
So now that we have a basic blog set up, next we'll take a look at how to optimize this blog application.
SEO performance optimization
So far all of the pages and code are completely server side rendered (SSR) since all of the code modules are using RSC by default.
This means that everything is compiled completely on the server before it's sent to the browser.
To eliminate the compile step and full pre-render these blog pages as pure static HTML, we'll need to use a process called static site generation (SSG)
Static site generation (SSG)
Since we're using a dynamic [slug] param in the route. we need to know all of the slug params ahead of time in order to pre-render these pages.
In Next.js 13 and higher, they solve this problem by providing the generateStaticParams function which will be called during the build process.
This function should return a list of all of the blog post slug params.
Step 1
Let's add the following function to the /app/blog/[slug]/page.tsx page we defined earlier.
Finds all of the files with the .mdx extension under the /content/blog directory.
Creates an array of slug names.
Maps the array of slug names to an array of params.
TSX
1return[
2{
3 slug:"best-summer-recipes"
4},
5{
6 slug:"food-reviews"
7}
8]
Each of the param objects in the returned array will be used to generate each blog post page during the build step. The content will be statically generated as HTML.
Step 2
Now run the build command.
Bash
1npm run build
You will see the following terminal output showing that all of the slugs we're generated successfully. This is indicated by the solid circle ● (SSG).
Bash
1Route (app) Size First Load JS
2┌ ○ / 142 B 84.4 kB
3├ ○ /_not-found 881 B 85.2 kB
4├ ○ /blog 177 B 91.2 kB
5└ ● /blog/[slug] 177 B 91.2 kB
6 ├ /blog/food-reviews
7 └ /blog/best-summer-recipes
8+ First Load JS shared by all 84.3 kB
9 ├ chunks/1dd3208c-f9971ff387577daf.js 53.4 kB
10 ├ chunks/997-8593090b208bf1ae.js 29 kB
11 └ other shared chunks (total) 1.87 kB
12
13
14○ (Static) prerendered as static content
15● (SSG) prerendered as static HTML (uses getStaticProps)
Step 3
Now that we built the static bundle, we can test the performance out by starting the Next.js server in production mode.
Bash
1npm run start
Point a browser to localhost:3000/blog and browse all of the blog posts and they will load very quickly since it's all pure html.
This is a very important factor in SEO optimization as search engines will consider response time as a ranking factor.
Conclusion
By now you should have a good understanding of how to build a basic blog with MDX using Next.js.
The next-mdx-remote package is very flexible and can be used to load content from virtually anywhere.
There's some pretty good extensions in Visual Studio Code for working with Front Matter. I think it compliments MDX nicely without the need for a database or external CMS. You can always move in that direction over time.
Hope this article helps. Good luck on your blogging!