Notion Helper

1.3.21

Getting Started

notion-helper Documentation

Welcome to the notion-helper documentation. This library provides a heaping spoonful of syntactic sugar for the Notion API.

It primarily gives you a fluent interface for quickly building JSON to create Notion blocks, pages, and property values.

You'll also find functions that can intelligently make API calls for creating new pages and appending blocks. Pass these a valid client object or API call function, and they'll handle the comlicated process of splitting blocks into chunks to deal with the Notion API's limits.

Quick Start

Create a page:

See the notion-helper website for more examples.

Browser Usage

This library works in both Node.js and browser environments!

Node.js Usage (Standard)

Browser Usage (Frontend)

Important: Browsers can't directly call the Notion API due to CORS restrictions. You'll need a backend proxy or serverless function to handle the actual API calls.

🎮 Try the Interactive Example

Want to see it in action? Check out our Interactive Browser Example that lets you run code and see the JSON output in real-time!


API Reference

Object with methods to construct the majority of block types supported by the Notion API.

Block types include audio, bookmark, breadcrumb, bulleted list item, callout, code, column_list, column, divider, embed, file, heading, image, numbered list item, paragraph, pdf, quote, table, table row, table of contents, to-do, toggle, and video. Some block types return null if they are provided with invalid data; you should filter these out your final children array.

Not supported: Link preview, synced block. Equation and Mention are supported within the buildRichTextObj() function, not here.

block
Static Members
audio
bookmark
breadcrumb
bulleted_list_item
callout
code
column_list
column
divider
embed
file
heading_1
heading_2
heading_3
image
numbered_list_item
paragraph
pdf
quote
table
table_row
table_of_contents
to_do
toggle
video

BlockShorthand

src/blocks.mjs

Block shorthand methods – these allow you to call the createBlock() method for the properties of the block object more quickly. Import them directly into a file, or call them on NotionHelper.

BlockShorthand
Static Members
audio(options)
bookmark(options)
bulletedListItem(options)
bullet(options)
callout(options)
code(options)
columnList(options)
column(options)
divider()
embed(options)
file(options)
heading1(options)
heading2(options)
heading3(options)
image(options)
numberedListItem(options)
num(options)
paragraph(options)
pdf(options)
quote(options)
table(options)
tableRow(cells)
tableOfContents(options)
toDo(options)
toggle(options)
video(options)

makeParagraphBlocks

src/blocks.mjs

Simple function to create standard Paragraph blocks from an array of strings without any special formatting. Each Paragraph block will contain a single Rich Text Object.

makeParagraphBlocks(strings: Array<string>): Array<Object>
Parameters
strings (Array<string>) an array of strings.
Returns
Array<Object>: array of Paragraph blocks.
setIcon(value: string): Object
Parameters
value (string) either an emoji character or a URL for an externally-hosted image file.
Returns
Object: An object representing the icon.

Creates a representation of an external link.

createExternal(url: string): Object
Parameters
url (string) The URL of the external link.
Returns
Object: An object containing the external URL.

Creates a representation of an emoji.

createEmoji(emoji: string): Object
Parameters
emoji (string) The emoji character.
Returns
Object: An object containing the emoji.

Creates a representation of a file link.

createFile(id: string): Object
Parameters
id (string) The ID of the file.
Returns
Object: An object containing the file ID.

Object with methods for constructing Notion page metadata, including parent, page, block, property, cover, and icon.

Parent creates a parent object. Page, block, and property create ID objects. Cover creates an external image object, while icon can create an external image object or an emoji object.

page_meta
Static Members
parent
page
block
property
icon
cover

PageShorthand

src/page-meta.mjs

Page shorthand methods - these allow you to call the createMeta() method for the properties of the page_meta object more quickly. Import them directly into a file, or call them on NotionHelper.

PageShorthand
Static Members
parentDb(database_id)
parentPage(page_id)
pageId(page_id)
blockId(block_id)
propertyId(property_id)
cover(url)
icon(url)

Object with methods for constructing each of the possible property types within a Notion database page.

Property types include title, rich_text, checkbox, date, email, files, multi_select, number, people, phone_number, relation, select, status, and url.

page_props
Static Members
title
rich_text
checkbox
date
email
files
multi_select
number
people
phone_number
relation
select
status
url

PropertyShorthand

src/page-meta.mjs

Property shorthand methods - these allow you to call the setProp() method for the properties of the page_props object more quickly. Import them directly into a file, or call them on NotionHelper.

PropertyShorthand
Static Members
title(value)
richText(value)
checkbox(value)
date(start, end?)
email(value)
files(files)
multiSelect(values)
number(value)
people(people)
phoneNumber(value)
relation(values)
select(value)
status(value)
url(value)

validateValue

src/page-meta.mjs

Validates values passed to the setProp() methods above. Performs some transformation in certain cases.

validateValue(value: any, type: string)
Parameters
value (any) the value being passed to setProp(), which invokes this function
type (string) the type of value expected by this Notion API property

quickPages

src/pages.mjs
quickPages($0: Object, options: Object, parent: string, parent_type: string, pages: (Array<Object> | Object), schema: Object, childrenFn: function): Array<Object>
Parameters
$0 (Object)
Name Description
$0.parent any
$0.parent_type any
$0.pages any
$0.schema any
$0.childrenFn any
options (Object)
parent (string) The ID of the parent page or database.
parent_type (string) "page_id" or "database_id".
pages ((Array<Object> | Object)) an array of simple objects, each of which will be turned into a valid page object. Each can have property types that match to valid Notion page properties, as well as a "cover", "icon", and "children" property. The "children" prop's value should be either a string or an array. You can also pass a single object, but the function will still return an array.
schema (Object) an object that maps the schema of the pages objects to property names and types in the parent. Saves you from needing to specify the property name and type from the target Notion database for every entry in your pages object. For each property in your pages object that should map to a Notion database property, specify the key as the property name in the pages object and set the value as an array with the Notion property name as the first element and the property type as the second. Non-valid property types will be filtered out. Optionall, you can specify custom keys for the icon (["Icon", "icon"]), cover (["Cover", "cover"]), and children array (["Children", "children"]).
childrenFn (function) a callback you can specify that will run on any array elements present in a "children" property of any object in the pages array. If that "children" property contains a single string, it'll run on that as well. If omitted, any "children" values will be converted to Paragraph blocks by default.
Returns
Array<Object>: An array of page objects, each of which can be directly passed as the children for a POST request to https://api.notion.com/v1/pages (or as the single argument to notion.pages.create() when using the SDK).
Example
const database = "abcdefghijklmnopqrstuvwxyz"

const tasks = [ {
  icon: "😛",
  task: "Build Standing Desk",
  due: "2024-09-10",
  status: "Not started"
} ]

const schema = {
  task: [ "Name", "title" ],
  due: [ "Due Date", "date"],
  status: [ "Status", "status" ]
}

const pageObjects = quickPages({
     parent: database,
     parent_type: "database_id",
     pages: tasks,
     schema: schema,
     childrenFn: (value) => NotionHelper.makeParagraphs(value)
})

NotionBuilder

src/pages.mjs

A builder object for Notion content with fluent interface methods.

NotionBuilder

Type: Object

Example
const notionBuilder = createNotionBuilder();

// Build a new Notion page with various blocks
const result = notionBuilder
  .parentDb('database-id')
  .title('Page Title', 'Hello World')
  .paragraph('This is the first paragraph.')
  .heading1('Main Heading')
  .build();

createNotionBuilder

src/pages.mjs

Creates a fluent interface builder for constructing Notion objects, including pages, properties, and blocks.

Fluent Interface Methods:

The returned builder provides chainable methods organized into categories:

Page Setup Methods:

  • parentDb(database_id) - Sets parent database
  • parentPage(page_id) - Sets parent page
  • pageId(page_id) - Adds page ID for updates
  • blockId(block_id) - Adds block ID for block operations
  • propertyId(property_id) - Adds property ID for property operations
  • cover(url) - Sets page cover image
  • icon(url) - Sets page icon

Property Methods:

  • property(name, type, value) - Adds custom property
  • title(name, value) - Adds title property
  • richText(name, value) - Adds rich text property
  • checkbox(name, value) - Adds checkbox property
  • date(name, value) - Adds date property
  • email(name, value) - Adds email property
  • files(name, value) - Adds files property
  • multiSelect(name, value) - Adds multi-select property
  • number(name, value) - Adds number property
  • people(name, value) - Adds people property
  • phoneNumber(name, value) - Adds phone number property
  • relation(name, value) - Adds relation property
  • select(name, value) - Adds select property
  • status(name, value) - Adds status property
  • url(name, value) - Adds URL property

Block Methods:

  • paragraph(content, options, url) - Adds paragraph block
  • heading1(content, options, url) - Adds H1 block
  • heading2(content, options, url) - Adds H2 block
  • heading3(content, options, url) - Adds H3 block
  • bulletedListItem(content, options, url) - Adds bulleted list item
  • numberedListItem(content, options, url) - Adds numbered list item
  • toDo(content, checked, options, url) - Adds to-do block
  • callout(content, emoji, options, url) - Adds callout block
  • quote(content, options, url) - Adds quote block
  • code(content, language) - Adds code block
  • divider() - Adds divider block
  • image(url, caption) - Adds image block
  • video(url, caption) - Adds video block
  • audio(url, caption) - Adds audio block
  • file(url, caption) - Adds file block
  • pdf(url, caption) - Adds PDF block
  • bookmark(url, caption) - Adds bookmark block
  • embed(url, caption) - Adds embed block
  • table(tableArray) - Adds table block
  • tableRow(cellContents) - Adds table row
  • columnList(columnArray) - Adds column list
  • column(columnContent) - Adds column
  • toggle(content, children, options, url) - Adds toggle block

Structure Management:

  • startParent(parentBlock) - Begins nested block structure
  • endParent() - Ends current nesting level
  • build() - Finalizes and returns the built object

Return Object:

Returns an object with two possible properties:

  • content (always returned) - can be a full page object, an array of blocks, or a properties object
  • additionalBlocks - array containing block chunks that exceed Notion's limits for subsequent requests
createNotionBuilder(options: Object?): NotionBuilder
Parameters
options (Object?) Configuration options for the builder
Name Description
options.strict boolean (default false) If true, throws errors for invalid data. Otherwise gracefully handles nulls.
options.limitNesting boolean (default true) If true, limits nested children to 2 levels (Notion API limit).
options.limitChildren boolean (default true) If true, limits children arrays to 100 blocks, putting excess in additionalBlocks.
options.allowBlankParagraphs boolean (default false) If true, allows empty paragraph blocks.
Returns
NotionBuilder: A builder object with fluent interface methods for constructing Notion content.
Example
// Basic page creation
const page = createNotionBuilder()
  .parentDb('database-id')
  .title('Name', 'My Task')
  .select('Status', 'In Progress')
  .date('Due Date', '2024-12-01')
  .paragraph('This is a task description.')
  .toDo('Complete the first step', false)
  .toDo('Review with team', false)
  .build();

// Complex nested structure
const complexPage = createNotionBuilder()
  .parentDb('database-id')
  .title('Project Name', 'Website Redesign')
  .heading1('Project Overview')
  .paragraph('This project involves redesigning our main website.')
  .heading2('Phase 1: Research')
  .startParent(toggle('Research Tasks', []))
    .toDo('Conduct user interviews', false)
    .toDo('Analyze competitor websites', false)
  .endParent()
  .heading2('Phase 2: Design')
  .callout('Important: Get stakeholder approval before development', '⚠️')
  .build();

// Handle large content with additionalBlocks
const result = page.content;
const extraBlocks = page.additionalBlocks;

// Create page first, then append additional blocks if needed
const notion = new Client({ auth: process.env.NOTION_TOKEN });
const newPage = await notion.pages.create(result);

if (extraBlocks && extraBlocks.length > 0) {
  for (const blockChunk of extraBlocks) {
    await notion.blocks.children.append({
      block_id: newPage.id,
      children: blockChunk
    });
  }
}
builder

Type: NotionBuilder

Static Members
parentDb(database_id)
parentPage(page_id)
pageId(page_id)
propertyId(property_id)
blockId(block_id)
cover(url)
icon(url)
property(name, type, value)
title(name, value)
richText(name, value)
checkbox(name, value)
date(name, start, end)
email(name, value)
files(name, files)
multiSelect(name, values)
number(name, value)
people(name, people)
phoneNumber(name, value)
relation(name, pages)
select(name, value)
status(name, value)
url(name, value)
startParent(blockType, options)
endParent()
addBlock(blockType, options)
addExistingBlock(existingBlock)
blank()
paragraph(options)
heading1(options)
heading2(options)
heading3(options)
bulletedListItem(options)
bullet(options)
numberedListItem(options)
num(options)
toDo(options)
toggle(options)
code(options)
quote(options)
callout(options)
divider()
image(options)
video(options)
audio(options)
file(options)
pdf(options)
bookmark(options)
embed(options)
tableOfContents(options)
table(options)
tableRow(options)
endTable()
breadcrumb()
columnList(options)
endColumnList()
column(options)
endColumn()
loop(blockTypeOrCallback, arr)
build()
createPage(creationCallback, appendCallback)
reset()

createNotion

src/pages.mjs
createNotion(options: Object): NotionBuilder
Deprecated: Use createNotionBuilder() instead. This function is maintained for backwards compatibility.
Parameters
options (Object) The options for creating a Notion builder.
Name Description
options.strict boolean (default false) If true, the builder will throw errors when passed invalid or null data.
options.limitNesting number (default true) If true, limits the number of nested children block arrays to 2.
options.limitChildren boolean (default true) If true, the final content object's children array will have a maximum of 100 blocks.
options.allowBlankParagraphs boolean (default false) If true, calling .paragraph("") will result in an empty paragraph block.
Returns
NotionBuilder: A builder object with methods for constructing and managing Notion content.

These functions take user-provided callback functions for API-specific requests, such as page-creation.

This will allow the library to handle requests directly, which will eventually enable deep tree-traversal and the construction of very complex pages and blocks structures.

Needed request types:

Auth

  • Create a token (post)

blocks X Append block children (patch)

  • Retrieve a block (get)
  • Retrieve block children (get)
  • Update a block (patch)
  • Delete a block (delete)

More block tasks

  • Handle nested columns (API can't handle a column_list block at the last nesting level) X Improve performance of block-append algorithm. (In a good spot now, though could be better using an in-memory tracker tree)

page X Create a page (post)

  • Retrieve a page (get)
  • Retrieve a page property (get)
  • Update page properties (patch)

database

  • Create a database (post)
  • Query a database (post) -- Build a filter -- Build a sort
  • Retrieve a database (get)
  • Update a database (patch) -- Update database properties

users

  • List all users (get)
  • Retrieve a user (get)
  • Retrieve your token's bot user (get)

comments

  • Create comment (post)
  • Retrieve comments (get)

search

  • Search by title (post)
request
Static Members
pages
blocks

Object with methods for making requests to the Notion API.

Each method requires that you passe either a Client object created with the Notion SDK (https://github.com/makenotion/notion-sdk-js) or a custom apiCall function.

request
Static Members
pages
blocks

RequestShorthand

src/requests.mjs

Request shorthand methods - these allow you to call the methods of the request object directly. Import them directly into a file, or call them on NotionHelper.

RequestShorthand
Static Members
createPage(options)
appendBlocks(options)

buildRichTextObj

src/rich-text.mjs

Builds a Rich Text Object. See: https://developers.notion.com/reference/rich-text

buildRichTextObj(input: (string | Object), options: Object?): Array<Object>
Parameters
input ((string | Object)) The text content or input object. If string, the input can be normal text or an equation. If object, it can be a text, equation, or mention object.
options (Object? = {}) Options for configuring the rich text object
Name Description
options.annotations Object? Options for the Annotation object
options.annotations.bold boolean? Bold text
options.annotations.italic boolean? Italic text
options.annotations.strikethrough boolean? Strikethrough text
options.annotations.underline boolean? Underlined text
options.annotations.code boolean? Code-style text
options.annotations.color string? String specifying the text's color or background color. Options: "blue", "brown", "default", "gray", "green", "orange", "pink", "purple", "red", "yellow". All except "default" can also be used as a background color with "[color]_background" - example: "blue_background". See: https://developers.notion.com/reference/rich-text#the-annotation-object
options.url string? The URL for this object, if any. Creates a clickable link.
options.type string (default "text") An optional type for the Rich Text Object. Supports text, equation, and mention.
Returns
Array<Object>: Array with a single Rich Text Object
Example
// Simple text
buildRichTextObj("Hello World")

// Text with URL
buildRichTextObj("Watch this very important video", { url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ" })

// Text with annotations
buildRichTextObj("Bold and brown", { 
  annotations: { bold: true, color: "brown" }
})

// Text with URL and annotations
buildRichTextObj("Bold blue link", {
  url: "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
  annotations: { bold: true, color: "blue" }
})

// Equation
buildRichTextObj("E = mc^2", { type: "equation" })

// Mention
buildRichTextObj({ type: "user", user: { id: "user_id" } }, { type: "mention" })

enforceRichText

src/rich-text.mjs

Enforces Rich Text format for content.

enforceRichText(content: (string | Object | Array)): Array
Parameters
content ((string | Object | Array)) The content to be enforced as Rich Text.
Returns
Array: An array of Rich Text Objects.

enforceRichTextObject

src/rich-text.mjs

Enforces a single Rich Text Object format.

enforceRichTextObject(obj: (string | Object)): Object
Parameters
obj ((string | Object)) The object to be enforced as a Rich Text Object.
Returns
Object: A Rich Text Object.

isSingleEmoji

src/utils.mjs

Checks if a string contains only a single emoji.

isSingleEmoji(string: string): boolean
Parameters
string (string)
Returns
boolean:

isValidURL

src/utils.mjs

Checks if a string is a valid URL.

isValidURL(string: string): boolean
Parameters
string (string)
Returns
boolean:

isValidUUID

src/utils.mjs

Checks if a string is a valid UUID.

isValidUUID(string: string): boolean
Parameters
string (string)
Returns
boolean:

validateImageURL

src/utils.mjs

Checks if an image URL is both a valid URL and has a supported image file type.

validateImageURL(url: url): boolean
Parameters
url (url) the URL to be checked
Returns
boolean:

validateVideoURL

src/utils.mjs

Checks if a video URL is both a valid URL and will be accepted by the API, based on a list of supported file extensions and embed websites.

validateVideoURL(url: url): boolean
Parameters
url (url) the URL to be checked
Returns
boolean:

validateAudioURL

src/utils.mjs

Checks if a audio URL is both a valid URL and will be accepted by the API, based on a list of supported file extensions.

validateAudioURL(url: url): boolean
Parameters
url (url) the URL to be checked
Returns
boolean:

validatePDFURL

src/utils.mjs

Checks if a PDF URL is both a valid URL and ends with the .pdf extension.

validatePDFURL(url: url): boolean
Parameters
url (url) the URL to be checked
Returns
boolean:

enforceStringLength

src/utils.mjs

Enforces a length limit on a string. Returns the original string in a single-element array if it is under the limit. If not, returns an array with string chunks under the limit.

enforceStringLength(string: string, limit: number): Array<string>
Parameters
string (string) the string to be tested
limit (number) optional string-length limit
Returns
Array<string>: array with the original string, or chunks of the string if it was over the limit.

validateDate

src/utils.mjs

Validates Date object or string input that represents a date, and converts it to an ISO-8601 date string if possible.

validateDate(dateInput: any, date: (string | Date)): string
Parameters
dateInput (any)
date ((string | Date)) a Date object or string representing a date
Returns
string:

Checks a provided array of child blocks to see how many nested levels of child blocks are present. Used by requests.blocks.children.append to determine if recursive calls need to be used.

getDepth(arr: Array<Object>, level: number): number
Parameters
arr (Array<Object>) The array of child blocks to be depth-checked.
level (number = 1) The current level.
Returns
number:

getTotalCount

src/utils.mjs

Gets the total number of blocks within an array of child blocks, including child blocks of those blocks (and so on). Used to ensure that requests do not exceed the 1,000 total block limit of the Notion API.

getTotalCount(arr: Array<Object>): number
Parameters
arr (Array<Object>) The array of block objects to be counted.
Returns
number:

getLongestArray

src/utils.mjs

Gets the length of the longest array within a nested block array.

getLongestArray(arr: Array<Object>, count: number): number
Parameters
arr (Array<Object>) The array to check
count (number = 0) The length of the array one level up from the array being checked, or 0 if this is the initial call of the function
Returns
number:

getPayloadSize

src/utils.mjs

Gets the size in bytes of a block array when converted to JSON. Used to ensure API requests don't exceed Notion's payload size limits.

getPayloadSize(arr: Array<Object>): number
Parameters
arr (Array<Object>) The array of block objects to measure
Returns
number: Size in bytes