Part 18: Transitioning from JSON to Markdown in Next.js: An Easy Guide

[Pages] Loading Data

[Pages] Loading Data

In modern web development, content management often benefits from using Markdown due to its simplicity and readability. Initially, you might have started with JSON for storing post data in your Next.js application, but transitioning to Markdown can offer more flexibility, especially for content that requires frequent updates or is managed by non-developers. In this guide, we'll explore how to make this transition by using the "Marked" library to parse Markdown files into HTML.

Why Use Markdown?

Markdown is a lightweight markup language that provides an easy way to format text using a plain-text editor. Its syntax is simple and can be easily converted to HTML, making it a popular choice for writing blog posts, documentation, and more.

Step-by-Step Transition Process

  1. Install the Marked Library

    To convert Markdown files to HTML, we will use the "Marked" library, which is straightforward and efficient. First, let's add it to our project:

    npm install marked

    Make sure to update your package.json to include this dependency:

    // package.json
    {
      "dependencies": {
        "marked": "^9.1.3",
        "next": "^14.0.0",
        "react": "^18.2.0",
        "react-dom": "^18.2.0"
      }
    }
  2. Update the Data Fetching Logic

    We'll modify the getPost function to read from Markdown files instead of JSON. marked function will help us convert Markdown content into HTML.

    // lib/posts.js
    import { readFile } from 'fs/promises';
    import { marked } from 'marked';
    
    export async function getPost(slug) {
      const source = await readFile(`content/posts/${slug}.md`, 'utf8');
      const html = marked(source);
      return {
        body: html,
      };
    }
  3. Adjust the Page Component

    Update your page component to render the HTML content correctly. We'll use React's dangerouslySetInnerHTML to insert the parsed HTML directly into the DOM:

    // pages/posts/first-post.js
    import Head from 'next/head';
    import { getPost } from '../../lib/posts';
    
    export async function getStaticProps() {
      const post = await getPost('first-post');
      return {
        props: { post },
      };
    }
    
    function FirstPostPage({ post }) {
      return (
        <>
          <Head>
            <title>{`${post.title || 'Untitled'} - My Blog`}</title>
          </Head>
          <main>
            <h1>{post.title || 'Untitled'}</h1>
            <article dangerouslySetInnerHTML={{ __html: post.body }} />
          </main>
        </>
      );
    }
    
    export default FirstPostPage;

    Here, dangerouslySetInnerHTML is utilized to inject HTML into the component. It's named this way to remind developers about potential security risks like XSS (Cross-Site Scripting) attacks. However, since our content is from trusted Markdown files, it is safe to use here.

  4. Test the Changes

    After making these updates, restart your Next.js development server and check that the Markdown content is correctly rendered. You should see your Markdown-formatted headers and text displayed as intended.

  5. Clean Up

    Since we've transitioned to Markdown, the previous JSON files used for posts, such as content/posts/first-post.json, can now be deleted from your project.

Conclusion

Switching from JSON to Markdown for content management in your Next.js application offers increased flexibility and ease of use. The Marked library simplifies the process of parsing Markdown into HTML, while React's dangerouslySetInnerHTML allows us to render this HTML effectively. This setup is especially beneficial for blogs, documentation, or any application where content needs to be easily readable and editable. As you continue developing your Next.js application, remember that Markdown's simplicity can greatly enhance your content management workflow.

Last updated