NeatCode

Blog Post

Blog System in NextJS 14

Johnathon Rohweder

Johnathon Rohweder

Published: 7/23/2024

This site, and more specifically the blog system I've added, uses a cool feature within NextJS. The MDX feature within NextJS allows anyone, with a little setup, to create a beautiful blog system or even a full website system using just markdown files.

But Why?

A blog system with hard-coded or produced HTML/CSS documents can be time-consuming and inefficient. Using markdown to create blog posts allows anyone to quickly write basic text and instantly create a blog post with simple styles and effects.

How to do it:

The MDX feature is fully supported within NextJS itself and is quite simple to set up.

My Environment:
  • NextJS: 14.2.5
  • Tailwind: 3.4.1

While Tailwind isn't required, the typography plugin allows easy and instant styles for the markdown result when using MDX, as the given result is quite unstyled.

To install Tailwind typography (using npm):
npm install -D @tailwindcss/typography
After installing, add the plugin to your tailwind.config.js like this:
/** @type {import('tailwindcss').Config} */
module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('@tailwindcss/typography')
    // ...
  ]
};
Now install the MDX dependencies:
npm install @next/mdx @mdx-js/loader @mdx-js/react
Next, create a file at the base of your NextJS app named mdx-components.js:
export function useMDXComponents(components) {
  return {
    ...components
  };
}

This is where you can add custom styles for each part of the markdown file.

Modify your next.config.mjs file like this:
import nextMDX from '@next/mdx';

const withMDX = nextMDX({ extension: /\.mdx?$/, options: {} });

/** @type {import('next').NextConfig} */
const nextConfig = {
  pageExtensions: ['ts', 'tsx', 'js', 'jsx', 'md', 'mdx']
};

export default withMDX(nextConfig);

This enables .mdx files to be properly picked up and used.
Finally, you can create your .mdx file just as you would page.js in your directory, like this:

about
  |-  page.mdx

Styling:

You may notice that your markdown output is very basic, lacking any styles. That's where Tailwind comes in. Adding the following line to the end of your page.mdx file instantly styles the markdown, providing instant usability:

export default ({ children }) => <div className="prose">{children}</div>;


This line works because MDX allows MD and JavaScript, enabling you to add components or do what is shown above. Now you should be able to efficiently make blog posts or even a whole webpage using just markdown. Enjoy!

NeatCode

Isometric Data Vectors by Vecteezy