Back to blogs
Creating a Blog Project with Next.js and Postiva
Ali Osman Delişmen
  • 4 months ago
  • 2 min read

Creating a Blog Project with Next.js and Postiva

In this tutorial, we'll walk through the steps to create a blog project using Next.js and Postiva. We'll cover setting up the project, installing necessary libraries, and configuring Postiva.

Step 1: Setting Up the Next.js Project

First, create a new Next.js project with Tailwind CSS:

npx create-next-app my-blog --tailwind --app
cd my-blog

Step 2: Installing the Postiva Client

npm install @postiva/client next-mdx-remote

Step 3: Configuring Postiva

import { createClient } from '@postiva/client';

const postivaClient = createClient({
  apiKey: process.env.POSTIVA_API_KEY,
  workspaceId: process.env.POSTIVA_WORKSPACE_ID,
});


export default postivaClient;

Obtaining Your API Key and Workspace ID

• Workspace ID: Navigate to the settings page of your workspace.

• API Key: Go to the workspace service keys section and generate a new key.

Add these credentials to your .env file:

POSTIVA_API_KEY=your_api_key_here
POSTIVA_WORKSPACE_ID=your_workspace_id_here

Step 4: Fetching and Displaying Content

Now, you can use the Postiva client to fetch and display blog content. Create a new page in your pages directory, for example app/page.tsx:

import Link from 'next/link';
import postivaClient from '../libs/postiva';

export default async function Home() {
  const posts = await postivaClient.contents.getContents();

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-3xl font-bold">Blog Posts</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id} className="border-b py-2">
            <Link href={`/posts/${post.id}`}>
              <a className="text-blue-500 hover:underline">{post.title}</a>
            </Link>
          </li>
        ))}
      </ul>
    </div>
  );
}

Step 5: Creating a Blog Detail Page with MDX

To create a blog detail page and render MDX content, first, create a new file app/posts/[id]/page.tsx. This file will handle displaying individual blog posts based on their ID.

import { MDXRemote } from 'next-mdx-remote/rsc';
import postivaClient from '../../../libs/postiva';

export default async function PostDetail({ params }) {
  const { slug } = params;
  const post = await postivaClient.contents.getContentBySlug(slug);

  return (
    <div className="container mx-auto p-4">
      <h1 className="text-3xl font-bold">{post.title}</h1>
      <MDXRemote source={post.body} />
    </div>
  );
}

This will fetch the post details based on the slug from the URL and render them on the page using MDX.

Conclusion

You have now created a basic blog project using Next.js 13 and Postiva. You can expand this by adding more features, styles, and functionality as needed. For more details on type definitions, visit the Postiva API Documentation.

Happy coding!