將 Notion 作為無頭 CMS(Headless CMS)與 Next.js 結合實戰

2024 年 3 月 30 日

使用Notion作為您的CMS

在本文中,我將向您展示如何將此平臺與Notion整合,以將其用作我在Dealo上的文章的CMS。Notion在組織和撰寫內容方面是一個很好的工具。

所有這裡展示的程式碼都將使用Next.js和Notion JS使用者端。

建立您的Notion整合

這個標題可能聽起來有些令人困惑,但這就是Notion稱呼它的方式。一個Notion整合是訪問您的內容的門戶,它將為您提供連線所需的API金鑰。用他們自己的話來說:

“整合定義了公共API如何與您的Notion工作區進行程式化互動。它們需要被授權(即,獲得明確的許可)才能對您的工作區進行任何更改。”

因此,您的第一步是建立一個整合。您可以閱讀Li 現在讓我們來玩一下 Notion。首先,您需要一種方法來組織您的文章。我建議使用表格範本,這將允許您為文章新增屬性,如状态、类别、关键词、标语(简短描述)等,然後您可以用於過濾、後設資料等。Notion 結構的最大優點之一是,您仍然可以為任何行寫一篇完整的文章。

建立表格後,您需要連線剛剛建立的整合,方法如下: https://developers.notion.com/docs/create-a-notion-integration#。對於這種用例,整合將是内部的,只需要讀取許可權。根據使用者許可權,我在本文中不會使用任何與使用者相關的資訊。如果您想要顯示文章的作者,您將需要訪問它。 建立頁面

現在進入編碼部分。 第一步是建立列出所有文章的根頁面。

這是我們將使用的資料夾結構(我正在使用應用程式路由器):

app / └── blog / ├── [slug] ├── layout.tsx └── page.tsx

正如您所看到的,這是一個非常簡單的結構。 如果您想要新增層次結構,比如按類別分組等,結構仍然會類似,儘管層次更多。

我不會詳細介紹layout.tsx元件的細節,因為頁面的外觀取決於您。 我們將首先關注page.tsx。

由於這是關於部落格的內容,頁面不需要是動態的,將在構建時生成。 這將有助於 SEO 和頁面載入時間。

現在讓我們看一些程式碼。 這是根頁面的程式碼:

import { Client } from ‘@notionhq/client’;

const NOTION_API_KEY = ‘your api key’; const NOTION_BLOG_DATABASE = ‘the table id’;

const notion = new Client({ auth: NOTION_API_KEY });

export default async function RootBlogPage() { const blogs = ( await notion.databases.query({ database_id: env.NOTION_BLOG_DATABASE, filter: { property: ‘status’, status: { equals: ‘Done’ } }, sorts: [ { property: ‘created_at’, direction: ‘ascending’, }, ], }) ).results as DatabaseObjectResponse[]; //…

這是如何從表中列出文章。注意過濾和排序;這是我提到使用表方法的好處之一,因為頁面有更多屬性可供使用。

要獲取NOTION_BLOG_DATABASE id,您可以從表中複製可共享連結並從中獲取。連結看起來像這樣:

https://www.notion.so/467bef11d2bf4877928f9be8447104a3?v=77da2764f80c46d590017de202c226a4&pv 下面,您将以您喜欢的任何布局显示文章。我使用了一个简单的两列网格和带有最少信息的卡片。

```jsx
<main className="max-w-[980px] mx-auto">
  <div className="grid grid-cols-2 gap-24">
    {blogs.map((blog: any) => (
      <Link key={blog.id} href={`/blog/${(buildSlug(blog))}`}>
        <div
          key={blog.id}
          className={cn(
            'flex flex-col p-6 h-full rounded border border-neutral-200 dark:border-slate-800',
            'hover:border-emerald-600 dark:hover:border-emerald-500 transition-border duration-200',
          )}
        >
          <h2 className="text-2xl">{blog.properties.Name?.title[0].plain_text}</h2>
          <div className="flex flex-row gap-2 mt-1">
            {blog.properties.keywords.multi_select.map((tag: any) => (
              <Code key={tag.id}>{tag.name}</Code>
            ))}
          </div>
        </div>
      </Link>
    ))}
  </div>
</main>
``` ```jsx
<main>
  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
    {blogs.map((blog) => (
      <Link href={`/blog/${buildSlug(blog)}`} key={blog.id}>
        <div className="border border-gray-200 p-4 rounded-lg">
          <h2 className="text-lg font-semibold">{blog.properties.Name.title[0].plain_text}</h2>
          <span className="mt-2 mb-4">{formatDate(blog.properties.created_at.created_time)}</span>
          <p className="text-neutral-600 dark:text-neutral-300">{blog.properties.tagline.rich_text[0].plain_text}</p>
        </div>
      </Link>
    ))}
  </div>
</main>

構建 buildSlug 函式我用來規範化連結的格式。您希望有人類可讀的連結,但同時也需要文章的ID,以便實現自我修復的URL。自我修復的URL通過修復損壞的連結並保持頁面與內容的最新狀態來幫助SEO,例如:如果標題更改了。您可以在這篇文章中閱讀更多。

這是函式:

export function buildSlug(blog: any) {
  const slug: string = blog.properties.Name?.title[0].plain_text.toLowerCase().replace(/ /g, '-');
  const cleanId = blog.id.replace(/-/g, '');
  return `${slug}-${cleanId}`;
}

渲染文章

現在讓我們渲染文章。 讓我們看看將呈現每篇文章的頁面。這是一個更復雜的頁面,因為它需要處理將Notion塊轉換為HTML標籤,以及新增後設資料。

這是處理後設資料的函式。它需要是一個函式,而不是一個簡單的const匯出,因為它需要獲取每篇文章的特定資料。這是一個簡單的實現,仍然缺少關鍵的後設資料,如開放圖形和Twitter相關標籤。

export async function generateMetadata(props: Props): Promise<Metadata> {
  const { params: { slug } } = props;
  const articleId = slug.split('-').pop();

  if (!articleId) {
    return {};
  }

  const blog: any = await notion.pages.retrieve({
    page_id: articleId,
  });
  const title = blog.properties.Name.title[0].plain_text;

  return {
    title,
    description: blog.properties.tagline.rich_text[0].plain_text,
    keywords: blog.properties.keywords.multi_select.map((tag: any) => tag.name),
  };
}

接下來是generateStaticParams。這個將 ```javascript export async function 生成靜態引數() { const 部落格文章 = ( await notion.databases.query({ database_id: env.NOTION_BLOG_DATABASE, filter: { property: ‘status’, status: { equals: ‘Done’ } }, sorts: [ { property: ‘created_at’, direction: ‘ascending’, }, ], }) ).results as DatabaseObjectResponse[];

return 部落格文章.map((部落格) => ({ slug: 構建Slug(部落格), })) }

现在,要渲染实际文章,我们将创建一个页面,查询Notion页面信息以及构成文章本身的块。

```javascript
export default async function 部落格詳情頁面(props: Props) {
  const { params: { slug } } = props;
  const 文章Id = slug.split('-').pop();

  if (!文章Id) {
    return notFound();
  }

  co
``` const page = await notion.pages.retrieve({
    page_id: articleId,
  });

  const blocks = [];
  let cursor = undefined;

  do {
    const response = await notion.blocks.children.list({
      block_id: articleId,
      start_cursor: cursor,
    });
    blocks.push(...response.results);
    cursor = response.next_cursor;
  } while (cursor);

  const elements = await processNotionBlocks(blocks as BlockObjectResponse[]);

  return (
    <main className="max-w-[780px] mx-auto">
      <div className="mb-24">
        <Link href="/blog">
          <Button variant="outline">
            <IconArrowLeft size={14} className="mr-2"/>
            返回文章列表
          </Button>
        </Link>
      </div>
      <h1 className="text-5xl mb-6 mt-4">
        {page.properties.Name.title[0].plain_text}
      </h1>
      <div className="flex flex-row gap-2 mb-3">
        {page.properties.keywords.multi_select.map((tag: any) => (
          <Code key={tag.id}>{tag.name}</Code>
        ))}
      </div> ```javascript
async function processNotionBlocks(blocks: BlockObjectResponse[]) {
  const elements = [];

  for (let i = 0; i < blocks.length; i++) {
    const block = blocks[i] as BlockObjectResponse;

    if (block.type === 'heading_1') {
      elements.push(
        <h1 key={block.id} className="text-4xl mt-8 mb-8">
          {block.heading_1.rich_text.map((text) => text.plain_text).join('')}
        </h1>
      );
    }

    if (block.type === 'heading_2') {
      elements.push(
        <h2 key={block.id} className="text-3xl mt-8 mb-8">
          {block.heading_2.rich_text.map((text) => text.plain_text).join('')}
        </h2>
      );
    }

    if (block.type === 'paragraph') {
      elements.push(
        <p key={block.id} className="mb-4">
          {block.paragraph.text.map((text) => text.plain_text).join('')}
        </p>
      );
    }

    if (block.type === 'bulleted_list_item') {
      elements.push(
        <li key={block.id} className="list-disc ml-4">
          {block.bulleted_list_item.text.map((text) => text.plain_text).join('')}
        </li>
      );
    }

    if (block.type === 'numbered_list_item') {
      elements.push(
        <li key={block.id} className="list-decimal ml-4">
          {block.numbered_list_item.text.map((text) => text.plain_text).join('')}
        </li>
      );
    }

    if (block.type === 'to_do') {
      elements.push(
        <div key={block.id} className="flex items-center mb-2">
          <input type="checkbox" className="mr-2" defaultChecked={block.to_do.checked} />
          <p className={block.to_do.checked ? 'line-through mb-4' : 'mb-4'}>
            {block.to_do.text.map((text) => text.plain_text).join('')}
          </p>
        </div>
      );
    }

    if (block.type === 'image') {
      elements.push(
        <img key={block.id} src={block.image.file.url} alt={block.image.caption[0].plain_text} className="w-full mt-4 mb-4 object-cover" />
      );
    }

    if (block.type === 'divider') {
      elements.push(<hr key={block.id} className="border-t border-gray-300 my-4" />);
    }
  }

  return elements;
}
``` ```tsx
    if (block.type === 'heading_3') {
      elements.push(
        <h3 key={block.id} className="text-2xl mt-4 mb-4">
          {block.heading_3.rich_text.map((text) => text.plain_text).join('')}
        </h3>
      );
    }

    if (block.type === 'paragraph') {
      if (block.paragraph.rich_text.length === 0) {
        elements.push(<br key={block.id}/>);
        continue;
      }
      elements.push(
        <p key={block.id} className="mb-2">
          {block.paragraph.rich_text.map((text, index) => {
            if (text.annotations.code) {
              return (
                <code
                  key={`${block.id}-${index}`}
                  className={cn(
                    'bg-emerald-200 dark:bg-emerald-800 rounded-sm px-1',
                    {
                      'font-bold': text.annotations.bold,
                      italic: text.annotations.italic,
                      'line-through': text.annotations.strikethrough,
                      underline: text.annotations.underline,
                    }
                  )}
                >
                  {text.plain_text}
                </code>
              );
            }
            return (
              <span
                key={`${block.id}-${index}`}
                className={cn({
                  'font-bold': text.annotations.bold,
                  italic: text.annotations.italic,
                  'line-through': text.annotations.strikethrough,
                  underline: text.annotations.underline,
                })}
              >
                {text.plain_text}
              </span>
            );
          })}
        </p>
      );
    }

    if (block.type === 'quote') {
      const quoteChildren = await notion.blocks.children.list({
        block_id: block.id,
      });
      const quoteElements = await processNotionBlocks(quoteChildren.results as BlockObjectResponse[]);
      elements.push(
        <blockquote key={block.id} className="my-6 pl-4 border-l-4 border-emerald-500 dark:border-emerald-700">
          {block.quote.rich_text.map((text) => text.plain_text).join('')}
          {quoteElements}
        </blockquote>
      );
    }

    if (block.type === 'code') {
      elements.push(
        <pre key={block.id} data-el="code-block" className="group p-6 my-6 rounded bg-neutral-50 dark:bg-slate-900 overflow-x-auto">
          <code className="text-sm font-mono py-[1px] px-1 rounded-sm bg-emerald-200 dark:bg-emerald-800 group-data-[el=code-block]:bg-neutral-50 group-data-[el=code-block]:dark:bg-slate-900">
            {block.code.rich_text.map((text) => text.plain_text).join('')}
          </code>
        </pre>
      );
    }

    if (block.type === 'bulleted_list_item') {
      elements.push(
        <ul key={block.id} className="list-disc list-outside pl-6 mb-2">
          <li>{block.bulleted_list_item.rich_text.map((text) => text.plain_text).join('')}</li>
        </ul>
      );
    }

    if (block.type === 'numbered_list_item') {
      elements.push(
        <ol key={block.id} className="list-decimal list-outside pl-6 mb-2">
          <li>{block.numbered_list_item.rich_text.map((text) => text.plain_text).join('')}</li>
        </ol>
      );
    }

    return elements;
  }
``` ```javascript
if (block.type === 'heading_3') {
  elements.push(
    <h3 key={block.id} className="text-2xl mt-4 mb-4">
      {block.heading_3.rich_text.map((text) => text.plain_text).join('')}
    </h3>
  );
}

if (block.type === 'paragraph') {
  if (block.paragraph.rich_text.length === 0) {
    elements.push(<br key={block.id}/>);
    continue;
  }

  elements.push(
    <p key={block.id} className="mb-2">
      {block.paragraph.rich_text.map((text, index) => {
        if (text.annotations.code) {
          return (
            <code
              key={`${block.id}-${index}`}
              className={cn(
                'bg-emerald-200 dark:bg-emerald-800 rounded-sm px-1',
                {
                  'font-bold': text.annotations.bold,
                  italic: text.annotations.italic,
                  'line-through': text.annotations.strikethrough,
                  underline: text.annotations.underline,
                }
              )}
            >
              {text.plain_text}
            </code>
          );
        }
        return (
          <span
            key={`${block.id}-${index}`}
            className={cn({
              'font-bold': text.annotations.bold,
              italic: text.annotations.italic,
              'line-through': text.annotations.strikethrough,
              underline: text.annotations.underline,
            })}
          >
            {text.plain_text}
          </span>
        );
      })}
    </p>
  );
}

if (block.type === 'quote') {
  const quoteChildren = await notion.blocks.children.list({
    block_id: block.id,
  });
  const quoteElements = await processNotionBlocks(quoteChildren.results as BlockObjectResponse[]);
  elements.push(
    <blockquote key={block.id} className="my-6 pl-4 border-l-4 border-emerald-500 dark:border-emerald-700">
      {block.quote.rich_text.map((text) => text.plain_text).join('')}
      {quoteElements}
    </blockquote>
  );
}

if (block.type === 'code') {
  elements.push(
    <pre key={block.id} data-el="code-block" className="group p-6 my-6 rounded bg-neutral-50 dark:bg-slate-900 overflow-x-auto">
      <code className="text-sm font-mono py-[1px] px-1 rounded-sm bg-emerald-200 dark:bg-emerald-800 group-data-[el=code-block]:bg-neutral-50 group-data-[el=code-block]:dark:bg-slate-900">
        {block.code.rich_text.map((text) => text.plain_text).join('')}
      </code>
    </pre>
  );
}

if (block.type === 'bulleted_list_item') {
  elements.push(
    <ul key={block.id} className="list-disc list-outside pl-6 mb-2">
      <li>{block.bulleted_list_item.rich_text.map((text) => text.plain_text).join('')}</li>
    </ul>
  );
}

if (block.type === 'numbered_list_item') {
  elements.push(
    <ol key={block.id} className="list-decimal list-outside pl-6 mb-2">
      <li>{block.numbered_list_item.rich_text.map((text) => text.plain_text).join('')}</li>
    </ol>
  );
}

return elements;
}

你可以(應該)完善這個函式,使其更加簡單,因為可能會有更多的塊型別需要支援,你可以看到它可能會變得難以控制,但作為初始步驟,這樣做是可以的。

結語

這就是如何將Notion設定為你的內容管理系統。值得一提的是,你可能已經注意到,我沒有提供任何API來接收Notion中新文章建立或更新時的通知。這是因為他們沒有webhooks API。

這意味著只有在專案中進行構建時,你的文章才會被新增或更新。希望這不會成為一個嚴重問題,但值得注意。

感謝您一直堅持到最後。

祝好,程式設計愉快。

❓ 常見問題與答疑 (FAQ)

高頻疑難解析與避坑指南
A

完全不需要。绝大多数核心功能在免费 Starter 计划中均可完整体验与实操练习,无需额外付费购买付费团队版。