MDX Blog with Next.js 13 and Contentlayer (Part 1)

Minh-Tri Le

Minh-Tri Le on Jan 28, 2022

next.js

mdx

blog

typescript

react

markdown

Next.js version 13 introduced the /app directory, a new way of defining routes in your application.
In this article, we'll go over the basics of using Contentlayer to render MDX files with Next.js 13 and TypeScript.
The code we'll be writing in this article is available on GitHub.

Context

First, let's quickly go through some technical concepts in case you didn't work with MDX and Next.js a lot:
  • MDX is essentially a set of unified plugins. unified is a generic interface for processing content as structured data. Thanks to this, I was able to write granular plugins to customize how I use MDX quite extensively.
  • Next.js is built on top of Webpack and loads MDX from Contentlayer.
  • Contentlayer Contentlayer makes working with content easy for developers. It't content SDK to transforms MDX file to JSON data so can consume by Next js app.

Part 1 : Setup project

Next js app

First, we'll need to create a new Next.js 13 app:
npx create-next-app@latest --experimental-app
# or
yarn create next-app --experimental-app
# or
pnpm create next-app --experimental-app
We will test to make sure the app is working. We will use yarn for this tutorial. However, if you like, you may just easily use NPM. Run the code below:
yarn dev
You should see our app available on http://localhost:3000.
Result

Add Tailwind

We will use Tailwind CSS for styling as we go without much extra effort, letโ€™s quickly set up Tailwind for our project. Run the command below to install Tailwind:
yarn add -D tailwindcss postcss autoprefixer
After the installation is complete, run the init command below to generate both tailwind.config.js and postcss.config.js.
Now within your tailwind.config.js file, add the following:
/tailwind.config.js
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
Add TailwindCSS styling to global.css
/styles/global.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Lastly, we need to install @tailwindcss/typography to enable Tailwind styles to be applied to our Markdown(MDX) files.
yarn add @tailwindcss/typography
We then need to add it as a plugin to our Tailwind configurations. Go to tailwind.config.js and add the code below.
plugins: [
    require('@tailwindcss/typography'),
],
Now letโ€™s move on to set up Contentlayer Part 2.

Comments