Goals
We had a short list of goals for this project:
- Produce semantic HTML (or as close to it as we can get).
- Keep pages fetched from Notion performant.
- Support all blocks that make sense.
- Helper methods to fetch enough data about a page.
Non-goals (for now)
- Support linking between Notion pages. We do however support external links.
- Support page properties. This may come later.
Using
Installation
Getting an API key from Notion
This is a bit out of scope for this article, but Notion has a good article on how to get your API key:
Note that you also have to share the pages you want to access using the API with your integration for it to work.
Retrieving a page
We strongly recommend creating an endpoint to provide the block data to the page where it should be displayed. The advantage of creating an endpoint is that you can set the data to be cached at the CDN/edge level.
The other alternative is to load the data directly from the Notion API in the
load
function of the page, but that does not allow for easy caching of the Notion data.
At its smallest, the endpoint you should create would look something like this (in this project, this is a simplified version of
src/routes/api/page/[name]/server.ts
):
The
page()
helper method will retrieve the page, and all of its block (nested blocks if necessary). If you visit this endpoint, it will return an object with two properties:
page
and
blocks
.
Once you have this endpoint in place, you need to call it from your
load
function (
+page.ts
):
Now, in your
+page.svelte
:
Helper methods
Databases
If you have a Notion database, you can use the
listPages
and
pageFromSlug
helpers from
@beat-no/svelte-notion-blocks/server
. To use it, you have to define a
Database
object to use, but its syntax is relatively simple:
-
slug_property
should be the name of the database property in Notion (same capitalization as you see in the Notion UI) that will be used for uniquely identifying a database item.
-
query
is the full query object from Notion’s API. It specifies which database to query, and any filters and sorts that are applied. When you use it withpageFromSlug
, the helper method will add an extra filter toquery.filter.and
to find the correct slug.
You use this object with the helpers like this:
page
will contain the properties of the page, and
blocks
will be a list of all the blocks on the page (including nested child blocks).
See
src/routes/api/blocks/+server.ts
for an example with
listPages
, and
src/routes/api/blocks/[type]/+server.ts
for an example of
pageFromSlug
.
Pages
You can retrieve any page with its blocks from Notion using
page
.