」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 【個人網站】Next如何整合Notion資料庫

【個人網站】Next如何整合Notion資料庫

發佈於2024-11-07
瀏覽:725

To integrate a Notion database into a Next.js project, you can use Notion as a content management system (CMS) and display its content on your website. Below is a simple step-by-step guide to help you integrate the Notion database into Next.js.

Basic Preparation

Obtain Notion API Key and Database ID

  1. Get Notion API Key: Go to the Notion Developer Portal and create a new integration. Once created, you will receive an API key.
  2. Get Database ID: Navigate to the Notion database you want to integrate, and copy the URL of the database page. The database ID is the string of characters between https://www.notion.so/ and ?v= in the URL.

[Personal Website] How to Integrate Notion Database in Next

还不清楚的可以看上篇文章:[01.[个人网站]如何使用Notion作为数据库进行全栈开发]

Using the Official SDK

Step 1: Install Dependencies

First, you need to install Notion’s official SDK, @notionhq/client, to communicate with the Notion API. You can install it using npm or yarn:

npm install @notionhq/client
# or
yarn add @notionhq/client

Step 2: Set up the Notion Client

Create a file lib/notion.js in the root directory of your Next.js project and configure the Notion client as follows:

// lib/notion.js
import { Client } from '@notionhq/client';

const notion = new Client({
  auth: process.env.NOTION_API_KEY,
});

export const getDatabase = async (databaseId) => {
  const response = await notion.databases.query({ database_id: databaseId });
  return response.results;
};

Make sure to store your Notion API key in an environment variable NOTION_API_KEY.(.env.local)

NOTION_API_KEY=your_secret_api_key

Step 3: Fetch Database Content

In your Next.js page, you can use getStaticProps or getServerSideProps to fetch the content from the Notion database.

// pages/index.js
import { getDatabase } from '../lib/notion';

export const getStaticProps = async () => {
  const databaseId = process.env.NOTION_DATABASE_ID;
  const posts = await getDatabase(databaseId);

  return {
    props: {
      posts,
    },
    revalidate: 1, // ISR (Incremental Static Regeneration)
  };
};

export default function Home({ posts }) {
  return (
    

My Notion Blog

    {posts.map((post) => (
  • {post.properties.Name.title[0].plain_text}
  • ))}
); }

Ensure that you have your Notion database ID stored in NOTION_DATABASE_ID as an environment variable.

NOTION_DATABASE_ID=your_database_id

Step 4: Deployment and Verification

Finally, deploy your Next.js project to Vercel or another platform, and verify that you can successfully fetch and display data from the Notion database.

Additional Tips

  • You can display different properties of Notion pages (like Name, Tags, Date, etc.) on your page.
  • Consider using getServerSideProps to fetch data on every request or use getStaticProps with ISR (Incremental Static Regeneration) to optimize performance.

By following these steps, you can successfully integrate a Notion database into your Next.js project and use it to manage and display content.

Using Notion API with Wrapped URLs

Lastly, I ended up using this method for convenience when integrating with the react-notion-x components.

Make sure to add your Notion Database ID and Notion API Key to the .env.local file:

NOTION_DATABASE_ID=your_database_id
NOTION_API_KEY=your_secret_api_key

Step 1: Install the necessary dependencies

First, install the necessary dependencies such as notion-types, notion-utils, and got to handle requests to the Notion API.

npm install notion-types notion-utils got p-map

Step 2: Create a file to encapsulate Notion API interactions

In your Next.js project, create a file, for example, lib/NotionAPI.ts, which will encapsulate interactions with the Notion API. This file will contain methods for calling Notion API endpoints to fetch data from pages and collections.

// lib/NotionAPI.ts
import * as notion from "notion-types";
import got, { OptionsOfJSONResponseBody } from "got";
import {
  getBlockCollectionId,
  getPageContentBlockIds,
  parsePageId,
  uuidToId,
} from "notion-utils";
import pMap from "p-map";

// 定义权限记录接口
export interface SignedUrlRequest {
  permissionRecord: PermissionRecord;
  url: string;
}

export interface PermissionRecord {
  table: string;
  id: notion.ID;
}

export interface SignedUrlResponse {
  signedUrls: string[];
}

// 定义NotionAPI类
export class NotionAPI {
  private readonly _apiBaseUrl: string;
  private readonly _authToken?: string;
  private readonly _activeUser?: string;
  private readonly _userTimeZone: string;

  constructor({
    apiBaseUrl = "",
    authToken,
    activeUser,
    userTimeZone = "America/New_York",
  }: {
    apiBaseUrl?: string;
    authToken?: string;
    userLocale?: string;
    userTimeZone?: string;
    activeUser?: string;
  } = {}) {
    this._apiBaseUrl = apiBaseUrl;
    this._authToken = authToken;
    this._activeUser = activeUser;
    this._userTimeZone = userTimeZone;
  }

  // 获取页面内容
  public async getPage(
    pageId: string,
    {
      concurrency = 3,
      fetchMissingBlocks = true,
      fetchCollections = true,
      signFileUrls = true,
      chunkLimit = 100,
      chunkNumber = 0,
      gotOptions,
    }: {
      concurrency?: number;
      fetchMissingBlocks?: boolean;
      fetchCollections?: boolean;
      signFileUrls?: boolean;
      chunkLimit?: number;
      chunkNumber?: number;
      gotOptions?: OptionsOfJSONResponseBody;
    } = {}
  ): Promise {
    const page = await this.getPageRaw(pageId, {
      chunkLimit,
      chunkNumber,
      gotOptions,
    });

    const recordMap = page?.recordMap as notion.ExtendedRecordMap;

    if (!recordMap?.block) {
      throw new Error(`Notion page not found "${uuidToId(pageId)}"`);
    }

    recordMap.collection = recordMap.collection ?? {};
    recordMap.collection_view = recordMap.collection_view ?? {};
    recordMap.notion_user = recordMap.notion_user ?? {};
    recordMap.collection_query = {};
    recordMap.signed_urls = {};

    if (fetchMissingBlocks) {
      while (true) {
        const pendingBlockIds = getPageContentBlockIds(recordMap).filter(
          (id) => !recordMap.block[id]
        );

        if (!pendingBlockIds.length) {
          break;
        }

        const newBlocks = await this.getBlocks(
          pendingBlockIds,
          gotOptions
        ).then((res) => res.recordMap.block);

        recordMap.block = { ...recordMap.block, ...newBlocks };
      }
    }

    const contentBlockIds = getPageContentBlockIds(recordMap);

    if (fetchCollections) {
      const allCollectionInstances: Array = contentBlockIds.flatMap((blockId) => {
        const block = recordMap.block[blockId].value;
        const collectionId =
          block &&
          (block.type === "collection_view" ||
            block.type === "collection_view_page") &&
          getBlockCollectionId(block, recordMap);

        if (collectionId) {
          return block.view_ids?.map((collectionViewId) => ({
            collectionId,
            collectionViewId,
          }));
        } else {
          return [];
        }
      });

      await pMap(
        allCollectionInstances,
        async (collectionInstance) => {
          const { collectionId, collectionViewId } = collectionInstance;
          const collectionView =
            recordMap.collection_view[collectionViewId]?.value;

          try {
            const collectionData = await this.getCollectionData(
              collectionId,
              collectionViewId,
              collectionView,
              {
                gotOptions,
              }
            );

            recordMap.block = {
              ...recordMap.block,
              ...collectionData.recordMap.block,
            };

            recordMap.collection = {
              ...recordMap.collection,
              ...collectionData.recordMap.collection,
            };

            recordMap.collection_view = {
              ...recordMap.collection_view,
              ...collectionData.recordMap.collection_view,
            };

            recordMap.notion_user = {
              ...recordMap.notion_user,
              ...collectionData.recordMap.notion_user,
            };

            recordMap.collection_query![collectionId] = {
              ...recordMap.collection_query![collectionId],
              [collectionViewId]: (collectionData.result as any)
                ?.reducerResults,
            };
          } catch (err: any) {
            console.warn(
              "NotionAPI collectionQuery error",
              pageId,
              err.message
            );
          }
        },
        {
          concurrency,
        }
      );
    }

    if (signFileUrls) {
      await this.addSignedUrls({ recordMap, contentBlockIds, gotOptions });
    }

    return recordMap;
  }

  public async addSignedUrls({
    recordMap,
    contentBlockIds,
    gotOptions = {},
  }: {
    recordMap: notion.ExtendedRecordMap;
    contentBlockIds?: string[];
    gotOptions?: OptionsOfJSONResponseBody;
  }) {
    recordMap.signed_urls = {};

    if (!contentBlockIds) {
      contentBlockIds = getPageContentBlockIds(recordMap);
    }

    const allFileInstances = contentBlockIds.flatMap((blockId) => {
      const block = recordMap.block[blockId]?.value;

      if (
        block &&
        (block.type === "pdf" ||
          block.type === "audio" ||
          (block.type === "image" && block.file_ids?.length) ||
          block.type === "video" ||
          block.type === "file" ||
          block.type === "page")
      ) {
        const source =
          block.type === "page"
            ? block.format?.page_cover
            : block.properties?.source?.[0]?.[0];

        if (source) {
          if (!source.includes("secure.notion-static.com")) {
            return [];
          }

          return {
            permissionRecord: {
              table: "block",
              id: block.id,
            },
            url: source,
          };
        }
      }

      return [];
    });

    if (allFileInstances.length > 0) {
      try {
        const { signedUrls } = await this.getSignedFileUrls(
          allFileInstances,
          gotOptions
        );

        if (signedUrls.length === allFileInstances.length) {
          for (let i = 0; i  {
    const parsedPageId = parsePageId(pageId);

    if (!parsedPageId) {
      throw new Error(`invalid notion pageId "${pageId}"`);
    }

    const body = {
      pageId: parsedPageId,
      limit: chunkLimit,
      chunkNumber: chunkNumber,
      cursor: { stack: [] },
      verticalColumns: false,
    };

    return this.fetch({
      endpoint: "loadPageChunk",
      body,
      gotOptions,
    });
  }

  public async getCollectionData(
    collectionId: string,
    collectionViewId: string,
    collectionView?: any,
    {
      limit = 9999,
      searchQuery = "",
      userTimeZone = this._userTimeZone,
      loadContentCover = true,
      gotOptions,
    }: {
      limit?: number;
      searchQuery?: string;
      userTimeZone?: string;
      loadContentCover?: boolean;
      gotOptions?: OptionsOfJSONResponseBody;
    } = {}
  ) {
    const type = collectionView?.type;

    const isBoardType = type === "board";
    const groupBy = isBoardType
      ? collectionView?.format?.board_columns_by
      : collectionView?.format?.collection_group_by;

    let filters = [];
    if (collectionView?.format?.property_filters) {
      filters = collectionView.format?.property_filters.map(
        (filterObj

: any) => ({
          property: filterObj?.property,
          filter: {
            operator: "and",
            filters: filterObj?.filter?.filters,
          },
        })
      );
    }

    const body = {
      collection: {
        id: collectionId,
      },
      collectionView: {
        id: collectionViewId,
      },
      loader: {
        type: "reducer",
        reducers: {
          collection_group_results: {
            type: "results",
            limit,
            loadContentCover,
          },
        },
        userTimeZone,
        limit,
        loadContentCover,
        searchQuery,
        userLocale: "en",
        ...(filters.length > 0 ? { filters } : {}),
        ...(groupBy
          ? {
              groupBy,
            }
          : {}),
      },
    };

    return this.fetch({
      endpoint: "queryCollection",
      body,
      gotOptions,
    });
  }

  private async fetch({
    endpoint,
    body,
    gotOptions,
  }: {
    endpoint: string;
    body: unknown;
    gotOptions?: OptionsOfJSONResponseBody;
  }) {
    const url = `${this._apiBaseUrl}/${endpoint}`;
    const json = true;
    const method = "POST";

    const headers: Record = {
      "Content-Type": "application/json",
    };

    if (this._authToken) {
      headers.cookie = `token_v2=${this._authToken}`;
    }

    if (this._activeUser) {
      headers["x-notion-active-user-header"] = this._activeUser;
    }

    try {
      const res = await got.post(url, {
        ...gotOptions,
        json,
        method,
        body,
        headers,
      });

      return res.body as R;
    } catch (err) {
      console.error(`NotionAPI error: ${err.message}`);
      throw err;
    }
  }

  private async getSignedFileUrls(
    urls: SignedUrlRequest[],
    gotOptions?: OptionsOfJSONResponseBody
  ): Promise {
    return this.fetch({
      endpoint: "getSignedFileUrls",
      body: { urls },
      gotOptions,
    });
  }

  private async getBlocks(
    blockIds: string[],
    gotOptions?: OptionsOfJSONResponseBody
  ): Promise {
    return this.fetch({
      endpoint: "syncRecordValues",
      body: {
        requests: blockIds.map((blockId) => ({
          id: blockId,
          table: "block",
          version: -1,
        })),
      },
      gotOptions,
    });
  }
}

Step 3: Use the Encapsulated API in Next.js Pages

To fetch Notion database content in your Next.js pages, you can use the encapsulated NotionAPI class and pass the retrieved data to react-notion-x components for rendering.

// pages/[pageId].tsx
import { GetServerSideProps } from 'next';
import { NotionAPI } from '../lib/NotionAPI';
import { NotionRenderer } from 'react-notion-x';
import 'react-notion-x/src/styles.css';

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { pageId } = context.params;
  const notion = new NotionAPI();
  const recordMap = await notion.getPage(pageId as string);

  return {
    props: {
      recordMap,
    },
  };
};

const NotionPage = ({ recordMap }) => {
  return ;
};

export default NotionPage;

Step 4: Configure Routing in Next.js

To ensure that the [pageId].tsx file can dynamically render different Notion pages, you need to set up dynamic routing in Next.js. This will allow you to match the pageId parameter and fetch the corresponding Notion page content.

Here’s how you can configure dynamic routes:

  1. Create a Dynamic Route File in the pages directory:

In your pages directory, create a new file called [pageId].tsx:

pages/[pageId].tsx
  1. Implement Dynamic Page Rendering:

In the [pageId].tsx file, fetch the Notion content based on the pageId from the URL and render it dynamically.

Example code:

import { GetStaticProps, GetStaticPaths } from 'next';
import { NotionRenderer } from 'react-notion-x';
import { getNotionPageData } from '../lib/NotionAPI';
import 'react-notion-x/src/styles.css';

export default function NotionPage({ pageData }) {
  return (
    
); } export const getStaticProps: GetStaticProps = async ({ params }) => { const { pageId } = params!; const pageData = await getNotionPageData(pageId as string); return { props: { pageData, }, revalidate: 10, // Revalidate content every 10 seconds (ISR) }; }; export const getStaticPaths: GetStaticPaths = async () => { return { paths: [], // We’ll use fallback to handle dynamic routes fallback: 'blocking', // Generate pages on the fly if not pre-rendered }; };
  1. Explanation:
  2. getStaticPaths: Since your content is dynamic, we return an empty array for paths and set fallback: 'blocking' to generate pages on demand.
  3. getStaticProps: Fetches the Notion page content based on the pageId passed in the URL.

Summary

By following the steps above, you can now encapsulate Notion API requests and render Notion pages dynamically in your Next.js project using react-notion-x. This setup allows you to efficiently integrate Notion as a CMS while ensuring scalability and maintainability in your Next.js application.

版本聲明 本文轉載於:https://dev.to/jessie_chen/personal-website-how-to-integrate-notion-database-in-next-2i58?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • 如何使用PHP將斑點(圖像)正確插入MySQL?
    如何使用PHP將斑點(圖像)正確插入MySQL?
    在嘗試將image存儲在mysql數據庫中時,您可能會遇到一個可能會遇到問題。本指南將提供成功存儲您的圖像數據的解決方案。 essue values( '$ this-> image_id','file_get_contents($ tmp_image)...
    程式設計 發佈於2025-02-19
  • 如何檢查對像是否具有Python中的特定屬性?
    如何檢查對像是否具有Python中的特定屬性?
    方法來確定對象屬性存在尋求一種方法來驗證對像中特定屬性的存在。考慮以下示例,其中嘗試訪問不確定屬性會引起錯誤: >>> a = someClass() >>> A.property Trackback(最近的最新電話): 文件“ ”,第1行, AttributeError:SomeClass實...
    程式設計 發佈於2025-02-19
  • PHP陣列鍵值異常:了解07和08的好奇情況
    PHP陣列鍵值異常:了解07和08的好奇情況
    PHP數組鍵值問題,使用07&08 在給定數月的數組中,鍵值07和08呈現令人困惑的行為時,就會出現一個不尋常的問題。運行print_r($月份)返回意外結果:鍵“ 07”丟失,而鍵“ 08”分配給了9月的值。 此問題源於PHP對領先零的解釋。當一個數字帶有0(例如07或08)的前綴時,PHP...
    程式設計 發佈於2025-02-19
  • 為什麼Microsoft Visual C ++無法正確實現兩台模板的實例?
    為什麼Microsoft Visual C ++無法正確實現兩台模板的實例?
    [2明確擔心Microsoft Visual C(MSVC)在正確實現兩相模板實例化方面努力努力。該機制的哪些具體方面無法按預期運行? 背景:說明:的初始Syntax檢查在範圍中受到限制。它未能檢查是否存在聲明名稱的存在,導致名稱缺乏正確的聲明時會導致編譯問題。 為了說明這一點,請考慮以下示例:一個...
    程式設計 發佈於2025-02-19
  • 如何以不同的頻率控制Android設備振動?
    如何以不同的頻率控制Android設備振動?
    控制使用頻率變化的Android設備振動是否想為您的Android應用程序添加觸覺元素?了解如何觸發設備的振動器至關重要。您可以做到這一點:生成基本振動以生成簡單的振動,使用振動器對象:這將導致設備在指定的持續時間內振動。 許可要求通過上述技術,您可以創建在您的Android應用程序中自定義振動,以...
    程式設計 發佈於2025-02-19
  • Java是否允許多種返回類型:仔細研究通用方法?
    Java是否允許多種返回類型:仔細研究通用方法?
    在java中的多個返回類型:一個誤解介紹,其中foo是自定義類。該方法聲明似乎擁有兩種返回類型:列表和E。但是,情況確實如此嗎? 通用方法:拆開神秘 [方法僅具有單一的返回類型。相反,它採用機制,如鑽石符號“ ”。 分解方法簽名: :本節定義了一個通用類型參數,E。它表示該方法接受了擴展foo類...
    程式設計 發佈於2025-02-19
  • 為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    為什麼我會收到MySQL錯誤#1089:錯誤的前綴密鑰?
    mySQL錯誤#1089:錯誤的前綴鍵錯誤descript 理解prefix keys primary鍵(movie_id(3))primary鍵(Movie_id) primary鍵(Movie_id) primary鍵(Movie_id) > `這將在整個Movie_ID列上建立標...
    程式設計 發佈於2025-02-19
  • 如何在Java字符串中有效替換多個子字符串?
    如何在Java字符串中有效替換多個子字符串?
    Exploiting Regular ExpressionsA more efficient solution involves leveraging regular expressions.正則表達式允許您定義復雜的搜索模式並在單個操作中執行文本轉換。 示例使用接下來,您可以使用匹配器查找令牌的...
    程式設計 發佈於2025-02-19
  • 如何干淨地刪除匿名JavaScript事件處理程序?
    如何干淨地刪除匿名JavaScript事件處理程序?
    element.addeventlistener(event,function(){/要解決此問題,請考慮將事件處理程序存儲在中心位置,例如頁面的主要對象,請考慮將事件處理程序存儲在中心位置,否則無法清理匿名事件處理程序。 。這允許在需要時輕鬆迭代和清潔處理程序。
    程式設計 發佈於2025-02-19
  • 如何限制動態大小的父元素中元素的滾動範圍?
    如何限制動態大小的父元素中元素的滾動範圍?
    在交互式界面中實現垂直滾動元素的CSS高度限制 考慮一個佈局,其中我們具有與可滾動的映射div一起移動的subollable map div用戶的垂直滾動,同時保持其與固定側邊欄的對齊方式。但是,地圖的滾動無限期擴展,超過了視口的高度,阻止用戶訪問頁面頁腳。 可以限制地圖的滾動,我們可以利用CS...
    程式設計 發佈於2025-02-19
  • 如何使用組在MySQL中旋轉數據?
    如何使用組在MySQL中旋轉數據?
    在關係數據庫中使用mysql組使用mysql組來調整查詢結果。在這裡,我們面對一個共同的挑戰:使用組的組將數據從基於行的基於列的基於列的轉換。通過子句以及條件匯總函數,例如總和或情況。讓我們考慮以下查詢: select d.data_timestamp, sum(data_id = 1 tata...
    程式設計 發佈於2025-02-19
  • 如何從Google API中檢索最新的jQuery庫?
    如何從Google API中檢索最新的jQuery庫?
    從Google APIS 問題中提供的jQuery URL是版本1.2.6。對於檢索最新版本,以前有一種使用特定版本號的替代方法,它是使用以下語法: https://code.jquery.com/jquery-latest.min. js(jquery hosted,minifated)[&& ...
    程式設計 發佈於2025-02-19
  • 如何可靠地檢查MySQL表中的列存在?
    如何可靠地檢查MySQL表中的列存在?
    在mySQL中確定列中的列存在,驗證表中的列存在與與之相比有點困惑其他數據庫系統。常用的方法:如果存在(從信息_schema.columns select * * where table_name ='prefix_topic'和column_name =&...
    程式設計 發佈於2025-02-19
  • 如何使用Python的記錄模塊實現自定義處理?
    如何使用Python的記錄模塊實現自定義處理?
    使用Python的Loggging Module 確保正確處理和登錄對於疑慮和維護的穩定性至關重要Python應用程序。儘管手動捕獲和記錄異常是一種可行的方法,但它可能乏味且容易出錯。 解決此問題,Python允許您覆蓋默認的異常處理機制,並將其重定向為登錄模塊。這提供了一種方便而係統的方法來捕獲...
    程式設計 發佈於2025-02-19
  • 如何使用FormData()處理多個文件上傳?
    如何使用FormData()處理多個文件上傳?
    )處理多個文件輸入時,通常需要處理多個文件上傳時,通常是必要的。可以將fd.append("fileToUpload[]", files[x]);方法用於此目的,允許您在單個請求中發送多個文件。 初始嘗試 在JavaScript中,一種常見的方法是:); 但是,此代碼僅處理第...
    程式設計 發佈於2025-02-19

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3