Building a Simple Blog with Next.js Link to heading

Next.js is a powerful React framework that enables developers to build server-side rendered and statically generated web applications with ease. In this tutorial, we will walk through the process of building a simple blog application using Next.js. We will cover the essential features, including setting up the project, creating pages, fetching data, and styling the blog.

Table of Contents Link to heading

  1. Introduction
  2. Setting Up the Project
  3. Creating Blog Pages
  4. Fetching Data
  5. Styling the Blog
  6. Deploying the Blog
  7. Conclusion

Introduction Link to heading

Next.js is a framework built on top of React that provides a range of features, such as server-side rendering, static site generation, and API routes. It simplifies the development process by offering an out-of-the-box solution for common web development tasks. In this tutorial, we will leverage these features to build a simple, yet functional blog application.

Setting Up the Project Link to heading

To get started, we need to set up a new Next.js project. Using create-next-app, we can quickly scaffold a new project.

npx create-next-app my-blog
cd my-blog
npm run dev

This will create a new Next.js project in the my-blog directory and start the development server. Open http://localhost:3000 to view your application.

Creating Blog Pages Link to heading

Next.js uses a file-based routing system. Each file inside the pages directory corresponds to a route in the application. Let’s create a few pages for our blog.

Home Page Link to heading

Create a new file named index.js inside the pages directory:

// pages/index.js
import Link from 'next/link';

export default function Home() {
  return (
    <div>
      <h1>Welcome to My Blog</h1>
      <ul>
        <li>
          <Link href="/posts/first-post">
            <a>First Post</a>
          </Link>
        </li>
      </ul>
    </div>
  );
}

This will create a simple home page with a link to our first blog post.

Blog Post Page Link to heading

Next, create a folder named posts inside the pages directory and add a file named first-post.js:

// pages/posts/first-post.js
export default function FirstPost() {
  return (
    <div>
      <h1>First Post</h1>
      <p>This is the content of the first post.</p>
    </div>
  );
}

Now, if you navigate to http://localhost:3000/posts/first-post, you should see the content of your first blog post.

Fetching Data Link to heading

To make our blog dynamic, we need to fetch data from an external source. For this example, we’ll use a simple JSON file to store our blog posts.

Creating a JSON File Link to heading

Create a new folder named data at the root of your project and add a file named posts.json:

// data/posts.json
[
  {
    "id": "first-post",
    "title": "First Post",
    "content": "This is the content of the first post."
  }
]

Fetching Data in Next.js Link to heading

Next.js provides a function called getStaticProps that allows us to fetch data at build time. We’ll use this function to fetch our blog posts.

// pages/index.js
import Link from 'next/link';
import fs from 'fs';
import path from 'path';

export default function Home({ posts }) {
  return (
    <div>
      <h1>Welcome to My Blog</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <Link href={`/posts/${post.id}`}>
              <a>{post.title}</a>
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

export async function getStaticProps() {
  const filePath = path.join(process.cwd(), 'data', 'posts.json');
  const jsonData = fs.readFileSync(filePath);
  const posts = JSON.parse(jsonData);

  return {
    props: {
      posts,
    },
  };
}

This will fetch the posts from the posts.json file and pass them as props to the Home component.

Styling the Blog Link to heading

To style our blog, we’ll use CSS modules, which are supported out of the box in Next.js. Create a new folder named styles at the root of your project and add a file named Home.module.css:

/* styles/Home.module.css */
.container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  font-size: 2rem;
  color: #333;
}

ul {
  list-style-type: none;
}

li {
  margin: 1rem 0;
}

Then, import the styles in your index.js file:

// pages/index.js
import Link from 'next/link';
import fs from 'fs';
import path from 'path';
import styles from '../styles/Home.module.css';

export default function Home({ posts }) {
  return (
    <div className={styles.container}>
      <h1>Welcome to My Blog</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <Link href={`/posts/${post.id}`}>
              <a>{post.title}</a>
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

export async function getStaticProps() {
  const filePath = path.join(process.cwd(), 'data', 'posts.json');
  const jsonData = fs.readFileSync(filePath);
  const posts = JSON.parse(jsonData);

  return {
    props: {
      posts,
    },
  };
}

Deploying the Blog Link to heading

Next.js applications can be deployed to various hosting providers, including Vercel, Netlify, and more. For this tutorial, we’ll deploy our blog to Vercel, which is the company behind Next.js.

  1. Push your project to a Git repository (e.g., GitHub, GitLab).
  2. Go to Vercel and sign up for an account.
  3. Import your project from the Git repository.
  4. Follow the prompts to deploy your application.

Your blog should now be live on the internet!

Conclusion Link to heading

In this tutorial, we covered the basics of building a simple blog with Next.js. We set up a new project, created pages, fetched data, and styled our blog. Next.js provides a powerful and flexible framework for building web applications, and we only scratched the surface of its capabilities.

For further learning, you can explore more advanced features of Next.js, such as dynamic routing, API routes, and server-side rendering.

References Link to heading

  1. Next.js Documentation
  2. CSS Modules
  3. Deploying with Vercel

Next.js Logo