Stori.
Notion API kết hợp cùng NextJS
5 min read

Notion API kết hợp cùng NextJS

APINotionNextJS

Tạo Notion Integration

Truy cập https://www.notion.so/my-integrations và tạo mới một integration. Trong ví dụ, một integartion mới được tạo ra với tên api

Note image

Tạo Notion Database

Truy cập ứng dụng Notion và tạo mới một Database. Bảng database cần đầy đủ các trường dưới đây:

  • Title (type - Title)
  • Published (type - Checkbox)
  • Description (type - Text)
  • Category (type - Select)
  • Keywords (type - Multi-select)
  • Created time (type - Created time)
  • Last updated (type - Last updated)
  • Author (type - Person)
  • Tạo một trang mới trong database vừa tạo:

    Note image

    Cấp quyền truy cập integration api trong trang notes

    Chọn nút có dấu 3 chấm ở góc trên cùng bên phải của ứng dụng Notion:

    Note image

    Đi tới phần Connections → Add Connections → Chọn integration đã tạo ở mục 1.

    Note image

    Triển khai dự án

  • Clone repo từ github
  • git clone https://github.com/codarkat/blog-notion-api.git
  • Copy file .env.example thành file .env
  • Cập nhật file .env
  • // NOTION_SECRET - Lấy mã từ mục Secrets trong integration đã tạo ở phần 1
    NOTION_SECRET=
    // DATABASE_NOTES_ID
    // Đọc tài liệu trong phần "Where can I find my database's ID"
    // https://developers.notion.com/docs/working-with-databases
    DATABASE_NOTES_ID=
  • Chạy chương trình
  • npm install
    npm run dev
  • Truy cập đường dẫn: http://localhost:3000/
  • Giải thích một số đoạn code

    1. File index.js

    export const getStaticProps = async () => {
      const notion = new Client({
        auth: process.env.NOTION_SECRET,
      });
    
      const data = await notion.databases.query({
        database_id: process.env.DATABASE_NOTES_ID,
        filter: {
          property: PUBLISHED_PROPERTY,
          checkbox: {
            equals: true,
          },
        },
      });
    
      const notes = [];
    
      data.results.forEach((result) => {
        notes.push(result.properties[TITLE_PROPERTY].title[0].plain_text);
      });
      return {
        props: {
          notes,
          data,
        },
      };
    };

    Đoạn code sử dụng getStaticProps (https://nextjs.org/docs/basic-features/data-fetching/get-static-props), thư viện @notionhq/client. Hàm sẽ gọi đến api của Notion với các biến môi trường đã được thiết lập. Cụ thể sẽ truy vấn tất cả các query với trường Public ở trạng thái true. Sau đó data sẽ được “làm sạch” để nhận lại tiêu đề của mỗi note (query). Các thành phần trong props sẽ được gửi đến phía client để tiếp tục xử lý (xuất giao diện, …).

    const Note = ({ notes, data }) => {
      console.log(data);
      return notes.map((note) => (
        <p key={note}>
          <Link href={`/${slugify(note).toLowerCase()}`}>
            <a>{note}</a>
          </Link>
        </p>
      ));
    };

    Note sẽ nhận props đã được nói đến phía trên. Hiển thị các thẻ Link truy cập đến các note cụ thể với slug của nó. Console sẽ hiện phần data để phục vụ quá trình debug.

    2. File [slug].js

    Sử dụng dynamic routes trong NextJS - [slug].js. Đoạn code gọi api gần như tương đồng với file index . Tuy nhiên trong file này sử dụng getServerSideProps (https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props) thay vì getStaticProps. Nguyên nhân là url hình ảnh trả về của Notion là dynamic url và hết hạn sau một thời gian. Các phần còn lại được viết để lọc data sau khi gọi API (Lưu ý: Các function mới phục vụ logic (getImg, getText, …) không viết trong các function components)

    Tham khảo

    https://github.com/codarkat/blog-notion-api

    https://developers.notion.com/reference/intro

    Share this article

    Share:
    Read Next Article