Netlify CMS & Next.js Series - Adding markdown content

Netlify CMS & Next.js Series - Adding markdown content

We're going to be using markdown to create our pages so lets add a markdown loader:

yarn add frontmatter-markdown-loader -D

Add markdown content

Create a content folder and some sample content:

filename: content/index.md

---
header:
  title: Software development for modern businesses - devfair
  description: devfair is your full stack software development experience
  logo: /images/devfair-logo.svg
hero:
  detail: Work with professional software developers and scrum masters to make your 
    project a reality. Minimise risk, cost and time compared to traditional 
    development. Have complete control and insight into your development process, just 
    like the best tech companies in the world.
  heading: Build software like the world's top tech companies do
  image: /images/hero.svg
---

next.config.js

Next we need to tell next.js how to handle markdown files and where to find them. We do this by creating a next.config.js file and adding the following code:

filename: next.config.js

module.exports = {
    webpack: (cfg) => {
        cfg.module.rules.push(
            {
                test: /\.md$/,
                loader: 'frontmatter-markdown-loader',
                options: { mode: ['react-component'] }
            }
        )
        return cfg;
    }
}

Add markdown content to the home page

We can now import the markdown content into the index.tsx file:

filename: index.tsx

import Head from "next/head";
import { attributes } from "../content/index.md";

export default function Index() {
  const { header, hero } = attributes;

  return (
    <div className="p-4">
      <Head>
        <title>{header.title}</title>
        <meta name="description" content={header.description} />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main>
        <h1 className="text-6xl">{hero.heading}</h1>

        <p className="mt-0 mb-4 text-gray-600">{hero.detail}</p>
      </main>
    </div>
  );
}

NOTE at this point you may see a typescript error around the markdown input:

TS2307: Cannot find module '../content/index.md' or its corresponding type declarations.

To fix this error you need to add a declaration to the next-env.d.ts:

filename: next-env.d.ts

/// <reference types="next" />
/// <reference types="next/types/global" />
declare module "*.md";

Rendered markdown

You should now see the markdown from content/index.md rendered on the index page:

markdown-screenshot.png