Next.js Blog with SSG

Creating a barebones Next.js (SSG) blog with Sevalla's static hosting is easy-peasy.

·by John Doe

Sevalla is the intuitive platform and the perfect home for your web projects.

Deploy effortlessly:


Setting Up the Project

To get started with your Next.js blog, follow these steps:

  1. Initialize a new Next.js project:

    npx create-next-app@latest my-nextjs-blog
    cd my-nextjs-blog
    
  2. Install necessary dependencies:

    npm install gray-matter remark remark-html
    
  3. Create your first blog post:

    Inside the content/blog directory, create a new file called first-post.mdx and add the following content:

    ---
    title: "My First Post"
    date: "2024-09-24"
    ---
    
    Welcome to my first blog post using Next.js and MDX!
    
  4. Configure Next.js to handle MDX files:

    Install the necessary plugins:

    npm install @next/mdx @mdx-js/loader
    

    Update your next.config.js:

    const withMDX = require("@next/mdx")({
      extension: /\.mdx?$/,
    });
    module.exports = withMDX({
      pageExtensions: ["js", "jsx", "md", "mdx"],
    });
    
  5. Create a page to display your blog posts:

    Create a new file pages/blog/[slug].js:

    import fs from "fs";
    import path from "path";
    import matter from "gray-matter";
    import { serialize } from "next-mdx-remote-client/serialize";
    import { MDXRemote } from "next-mdx-remote-client";
    
    export default function Post({ source, frontMatter }) {
      return (
        <div>
          <h1>{frontMatter.title}</h1>
          <MDXRemote {...source} />
        </div>
      );
    }
    
    export async function getStaticPaths() {
      const files = fs.readdirSync(path.join("content/blog"));
      const paths = files.map((filename) => ({
        params: {
          slug: filename.replace(".mdx", ""),
        },
      }));
      return {
        paths,
        fallback: false,
      };
    }
    
    export async function getStaticProps({ params: { slug } }) {
      const markdownWithMeta = fs.readFileSync(
        path.join("content/blog", slug + ".mdx"),
        "utf-8",
      );
      const { data: frontMatter, content } = matter(markdownWithMeta);
      const mdxSource = await serialize(content);
      return {
        props: {
          source: mdxSource,
          frontMatter,
        },
      };
    }
    
  6. Run your development server:

    npm run dev
    

Visit http://localhost:3000/blog/first-post to see your first blog post live!

And that's it! You've successfully created a barebones Next.js blog with SSG using Sevalla's static hosting. Happy blogging!