Your Website Title

or Esc to go back

Blog

Building a Simple Blog with Next.js

Published at Fri Jan 31 2025 00:00:00 GMT+0000
#nextjs#react#blog

Creating Your First Next.js Blog

Next.js is a popular React framework for building server-side rendered applications. Let’s create a simple blog.

  1. Create a Project:

    npx create-next-app@latest my-blog
    cd my-blog
  2. Create Blog Pages: Create a pages/blog/[slug].js file:

    import { useRouter } from 'next/router';
    
    export default function Post() {
      const router = useRouter();
      const { slug } = router.query;
    
      // In a real application, you would fetch the post data
      // based on the slug.  For this example, we'll just display it.
      return (
        <div>
          <h1>Blog Post: {slug}</h1>
          <p>Content of the blog post goes here.</p>
        </div>
      );
    }
  3. Create a Blog Index Page: Create pages/blog/index.js:

    import Link from 'next/link';
    
    export default function Blog() {
      const posts = [
        { slug: 'first-post', title: 'My First Post' },
        { slug: 'second-post', title: 'Another Post' },
      ];
    
      return (
        <div>
          <h1>Blog</h1>
          <ul>
            {posts.map((post) => (
              <li key={post.slug}>
                <Link href={`/blog/${post.slug}`}>
                  {post.title}
                </Link>
              </li>
            ))}
          </ul>
        </div>
      );
    }
  4. Run the Development Server:

    npm run dev

This will start the development server. Navigate to http://localhost:3000/blog to see the blog index page, and click on the links to view individual posts. This example demonstrates basic routing in Next.js. In a real-world scenario, you would fetch the blog post content from a database or CMS. Next.js also offers powerful features like static site generation (SSG) and server-side rendering (SSR) for improved performance.

author
Hursh Gupta

I'm a student and developer from India, writing actuarial exams from the CAS. I love crafting innovative digital solutions and creating applications that solve real-world problems.