Static Site Generation (SSG) in Next.js

Ramkumar Khubchandani
2 min readDec 31, 2023

--

Here’s a step-by-step guide to creating a blog using static site generation (SSG) in Next.js, with coding examples:

1. Set up a Next.js project:

  • Open your terminal and run:
npx create-next-app my-blog
  • Replace my-blog with your desired project name.

2. Create a blog post page:

  • Create a file named blog-post.js inside the pages directory.
  • Add the following code to blog-post.js:
import { useRouter } from 'next/router';

export async function getStaticPaths() {
// Define paths for blog posts based on your data source
const paths = [
{ params: { slug: 'my-first-post' } },
{ params: { slug: 'my-second-post' } },
];
return { paths, fallback: false }; // Set fallback to false to only generate defined paths
}

export async function getStaticProps(context) {
const { slug } = context.params;

// Fetch blog post data based on the slug
const post = await fetchPost(slug);

return {
props: { post },
};
}

function BlogPost({ post }) {
const router = useRouter();

return (
<div>
<h1>{post.title}</h1>
<p>{post.date}</p>
<div dangerouslySetInnerHTML={{ __html: post.content }} />
<p>
<a href="/">Back to home</a>
</p>
</div>
);
}

export default BlogPost;

3. Implement data fetching:

  • Replace fetchPost(slug) with your actual data fetching logic (e.g., from an API or Markdown files).

4. Build and export the static site:

  • Run the following commands:
npm run build
npm run export

5. Deploy the static files:

  • The exported static files will be in the out directory.
  • Deploy these files to a hosting service that supports static sites (e.g., Vercel, Netlify, GitHub Pages).

Key points to remember:

  • getStaticPaths defines the dynamic routes for your blog posts.
  • getStaticProps fetches data at build time for each route.
  • fallback: false ensures only pre-rendered pages are generated.
  • Use dangerouslySetInnerHTML with caution for trusted HTML content.

Additional tips:

  • Use a Markdown parser for content management.
  • Consider CSS-in-JS solutions for styling.
  • Implement pagination for longer lists of posts.
  • Use getStaticProps for SEO optimization.

Do you want to learn more like this ?

Follow me or message me on Linkedin.

--

--

Ramkumar Khubchandani
Ramkumar Khubchandani

Written by Ramkumar Khubchandani

Frontend Developer|Technical Content Writer|React|Angular|React-Native|Corporate Trainer|JavaScript|Trainer|Teacher| Mobile: 7709330265|ramkumarkhub@gmail.com

No responses yet