Leveraging Notion as a Powerful Headless CMS

February 18, 2024 (1y ago)

image

Introduction

Hey devs! Whether you're building personal projects or powering client websites, managing content efficacement is crucial. Let's dive into how we can harness Notion's api to create efficient and dynamic websites. Fun fact, this blog is using Notion as CMS.

Prerequisites

Step 1: Secure Your Secret Token

Step 2: Structure Your Content: The Notion Database

Step 3: Install the Notion Package:

Terminal Time: Open your project's terminal and run the following command to install the @notionhq/client package:

npm install @notionhq/client
 
OR
 
yarn add @notionhq/client

Step 4: Fetching Database Data: Content on Demand

Now, let's write code to retrieve content from your Notion database:

import { Client } from "@notionhq/client";
 
async function fetchData() {
  const notion = new Client({ auth: process.env.NOTION_SECRET });
 
  try {
    const response = await notion.databases.query({
      database_id: process.env.DATABASE_ID,
      filter: {
        // Optional filtering (e.g., published content)
        and: [
          {
            property: "Published",
            checkbox: {
              equals: true,
            },
          },
          // Add more filters as needed
        ],
      },
      sorts: [
        {
          property: "Date",
          direction: "descending", // Latest posts first
        },
      ],
    });
 
    const data = response.results;
 
    // Process your fetched data here!
    return data;
  } catch (error) {
    console.error("Error fetching data:", error);
    // Handle errors gracefully
  }
}

Step 5: Fetching Individual Page Data: Delving Deeper

To retrieve content from specific Notion pages (e.g., individual blog posts), we'll need the unique page ID

async function fetchPageData(pageId) {
  const notion = new Client({ auth: process.env.NOTION_SECRET });
 
  try {
    const response = await notion.blocks.children.list({
      block_id: pageId,
    });
 
    const pageData = response.results;
 
    // Process your fetched page data here!
    return pageData;
  } catch (error) {
    console.error("Error fetching page data:", error);
    // Handle errors gracefully
  }
}

Conclusion

In this blog we have learned how to fetch data from Notion API. Use the fetched data in your frontend. Remember, the journey doesn't end here. Explore Notion Developer Docs to find more about Notion API features and keep yourself up to date.