Notion is a service that I’m currently using to build a blog and this page shows my progress on using the Notion JavaScript library to connect to the Notion API to retrieve and update my Notion account data.
I will be using Bun to create a hello world example for using the Notion library. To start off I will create a new Typescript project.
npm init
Next is to install the notion JavaScript library.
npm install @notionhq/client
Create an .env file and add the following NOTION_TOKEN key, the value will be added in the next step.
While logged into your Notion account go to the integrations page at https://www.notion.so/my-integrations.
Select the API block and you can find the token value to add to the NOTION_TOKEN key in the .env file.
Select the capabilities section to update the permissions for API access set the user data as read access.
Go back to the index.ts and add the following code.
const { Client } = require('@notionhq/client')
const notion = new Client({
auth: process.env.NOTION_TOKEN
})
;(async () => {
const listUsersResponse = await notion.users.list({})
console.log('listUsersResponse', listUsersResponse)
})()
console.log('Notion!')
In the terminal, you should see an output relating to the user account associated with the notion token.
This next snippet will get a notion database, loop through all the pages of the database, and then output the page ID.
;(async () => {
const database = await notion.databases.query({
database_id: process.env.NOTION_DATABASE_ID
})
for (const page of database.results) {
console.log('Page ID', page.id)
}
})()
The next task is to use those page IDs to get notion page content in Markdown format. A node package notion-to-md is needed to achieve this.
More information on the library can be found at https://github.com/souvikinator/notion-to-md.
npm install notion-to-md
Replace the index.ts file with the following which will go through all the pages from the database and output each page in markdown format.
const { Client } = require('@notionhq/client')
const { NotionToMarkdown } = require('notion-to-md')
const notion = new Client({
auth: process.env.NOTION_TOKEN
})
const n2m = new NotionToMarkdown({ notionClient: notion })
;(async () => {
const database = await notion.databases.query({
database_id: process.env.NOTION_DATABASE_ID
})
for (const page of database.results) {
console.log('Page ID', page.id)
const mdblocks = await n2m.pageToMarkdown(page.id)
const mdString = n2m.toMarkdownString(mdblocks)
console.log('Page markdown', mdString.parent)
}
})()
console.log('Notion!')
With the page content, you should be able to use it for your applications.