How to use Notion as Code
By Flavio
Tagged: Tools
Learn how Notion as Code defines teamspaces, pages, databases, views, entries, and custom agents in TypeScript, then deploys them with the Notion CLI.
Notion just launched Notion as Code, which lets you define a whole Notion workspace in TypeScript and deploy it through the Notion API.
You aren’t limited to creating pages. Teamspaces, databases, database views, entries, and custom agents can all live in Git, so you can review workspace changes in a pull request and apply the same setup to another workspace.
Previously, automating Notion with the API meant writing imperative scripts: create a database, save the returned ID, create some pages, handle partial failures, and figure out what happens when you run the script a second time. Notion as Code gives us a declarative layer instead. You describe the workspace you want, and the Notion CLI tracks the real IDs so it updates the same resources on the next run, much like infrastructure as code does for servers and cloud resources.
A beta warning before we start
Notion announced this feature as a beta, and the official template repository still calls the underlying system alpha and experimental. They also published a How to use Notion as Code guide for the beta, though the public Notion CLI reference doesn’t list the notion-as-code commands yet.
Because access is still rolling out, the API may reject requests in some environments, or your installed CLI might not have the command yet. If you run into errors right away, check whether your account has beta access before spending time debugging your TypeScript.
Start in a test workspace, too. This tool creates real teamspaces, databases, pages, and agents, and a typo is a lot easier to clean up in an empty workspace.
What Notion as Code is
A Notion as Code project is a small TypeScript codebase. Running the TypeScript doesn’t call the Notion API directly. Calls like notion.teamspace() and notion.database() record intents.
When you build the project, those intents get written to:
dist/intents.json
From there, the Notion CLI reads that file and applies your intents to the workspace.
The setup has three pieces:
- your TypeScript files, which describe the workspace you want
- local state, which maps your stable names to real Notion IDs
- the Notion workspace itself, where the real resources live
Say your code calls a database projects-database. Notion assigns it a long internal ID, and the local state file remembers the link between the two. Next time you apply the project, the CLI looks up that mapping and updates the existing database instead of creating a duplicate.
What it is not
Notion as Code isn’t a workspace backup, and it isn’t a live two-way sync between Notion and Git.
It only manages the resources included in your project. People on your team can still open Notion, write inside pages, leave comments, change statuses, and work the way they normally do.
Think of the repo as the source of truth for your workspace architecture, rather than every sentence, task, or meeting note. If you put constantly changing tasks into TypeScript, your Git history turns into noise fast. My advice is to stick to the stable structure (teamspaces, hub pages, database schemas, views, templates, and agents) and let people own the day-to-day content inside Notion.
Install the Notion CLI
Notion as Code runs through the ntn CLI. On macOS and Linux, the recommended way to install it is:
curl -fsSL https://ntn.dev | bash
If you prefer npm (which currently requires Node.js 22 or newer), you can install it with:
npm install --global ntn
On Windows, you can install it with Winget:
winget install Notion.ntn
Once that finishes, verify the installation with:
ntn --version
You can see all the installation options in the Notion CLI installation guide.
Log in to a workspace
Start the login flow with:
ntn login
The CLI opens your browser so you can authorize a workspace. Make sure the code in the browser matches the one in your terminal before approving it. Your token gets saved in the OS credential store (Keychain on macOS). You’ll need full workspace membership for this, since guests and restricted members can’t log in through the CLI.
If you’re working on a remote server without a local browser, run this instead:
ntn login --no-browser
That prints a URL and a verification code. Open the URL on another device, approve the login, and run the polling command shown in your terminal. For CI pipelines and unattended scripts, the authentication guide covers personal access tokens.
Start from the official template
Clone the template repository to get started:
git clone https://github.com/makenotion/notion-as-code-template my-notion-workspace
cd my-notion-workspace
npm install
Here are the main files inside:
src/main.ts
src/content.ts
src/lib/notion.ts
src/lib/types.d.ts
AGENTS.md
src/main.ts is the entry point. src/lib/ holds the vendored runtime and TypeScript types. Don’t edit those files, because they tell your editor, TypeScript, and coding agents what the beta supports.
The repo also includes an AGENTS.md file that spells out how coding agents should work inside the project. Notion as Code pairs well with agents, and having explicit rules right in the repo keeps them on track.
Define a teamspace
Let’s set up an Engineering teamspace. First, define a stable workspace anchor that the CLI connects to whichever workspace you logged into:
import { notion } from './lib/notion'
const workspace = {
type: 'resourceId',
resourceId: 'acme-workspace',
} as const
Next, add the teamspace:
const engineering = notion.teamspace({
resourceId: 'engineering-teamspace',
parent: workspace,
name: 'Engineering',
accessLevel: 'open',
icon: {
type: 'notion_icon',
description: 'code',
color: 'blue',
},
description: 'Projects, decisions, and technical documentation.',
})
Notice how there are two separate names here:
engineering-teamspaceis the stable resource ID your code usesEngineeringis the display name people see in Notion
You can change the name property whenever you want, as long as you keep resourceId the same. Treat resourceId like a database primary key: pick lowercase names that describe what the resource is for, and avoid putting mutable titles, dates, or people’s names in it unless they’re permanently part of its identity.
Add a page with Markdown content
You can add a page right through the teamspace handle:
engineering.addPage({
resourceId: 'engineering-home',
properties: {
title: notion.text('Engineering home'),
},
icon: {
type: 'emoji',
emoji: '🛠️',
},
content: `# Welcome
This is the home of the engineering team.
## Start here
- Read the technical principles
- Find the current projects
- Record an architectural decision
`,
})
The page title goes in properties.title, while the Markdown string becomes the page body. Notion supports an extended Markdown dialect here, so you can include Notion blocks and rich text features on top of standard headings and lists.
When a page gets long, keep its content in a separate file:
export const engineeringHome = `# Welcome
This is the home of the engineering team.
`
Then import it into main.ts:
import { engineeringHome } from './content'
That keeps your workspace definition easy to read, and Git diffs stay clean when someone edits the page copy.
Create a database schema
Next, let’s build a Projects database with a title, status, priority, and target date:
const projectsDatabase = engineering.addDatabase({
resourceId: 'projects-database',
name: 'Projects',
icon: {
type: 'notion_icon',
description: 'target',
color: 'purple',
},
description: 'The projects owned by the engineering team.',
dataSources: [
{
resourceId: 'projects-data-source',
name: 'Projects',
properties: [
{
resourceId: 'project-name-property',
name: 'Name',
type: 'title',
},
{
resourceId: 'project-status-property',
name: 'Status',
type: 'status',
options: {
todo: [
{ name: 'Not started', color: 'gray', default: true },
],
inProgress: [
{ name: 'In progress', color: 'blue' },
],
complete: [
{ name: 'Done', color: 'green' },
],
},
},
{
resourceId: 'project-priority-property',
name: 'Priority',
type: 'select',
options: [
{ name: 'High', color: 'red' },
{ name: 'Medium', color: 'yellow' },
{ name: 'Low', color: 'green' },
],
},
{
resourceId: 'project-target-property',
name: 'Target',
type: 'date',
},
],
},
],
})
Just like teamspaces and pages, database properties have their own stable resource IDs. When a board view groups items, it points to project-status-property instead of the visible Status label, so you can rename the label later without breaking anything that references it.
Seed database entries
To add rows to that database, grab its data source handle first:
const projects = projectsDatabase.getDataSource(
'projects-data-source'
)
Then add a page:
projects.addPage({
resourceId: 'project-new-checkout',
properties: {
Name: notion.text('Build the new checkout'),
Status: notion.status('In progress'),
Priority: notion.select('High'),
Target: notion.date('2026-08-15'),
},
})
Because the TypeScript types know your database schema, your editor will catch a misspelled property name or a mismatched value type before anything touches Notion.
You don’t have to hardcode every entry inline, either. The build runs under Node.js, so you can import JSON, read a CSV file, read environment variables, or install an npm package. The official template includes a JSON file and loops over its rows, like this:
import projectRows from './data/projects.json' with { type: 'json' }
for (const project of projectRows) {
projects.addPage({
resourceId: project.id,
properties: {
Name: notion.text(project.name),
Status: notion.status(project.status),
Priority: notion.select(project.priority),
Target: notion.date(project.target),
},
})
}
Only the recorded intents get sent to Notion while all the file-reading code stays local. That makes this a handy option for migrations or repeatable setups built from a CSV, a JSON config file, or an internal data source.
Add database views
A database is a lot more useful when the views people expect are already wired up. Let’s add a table view and a board view to our Projects database:
projectsDatabase.addView({
resourceId: 'projects-table-view',
name: 'All projects',
type: 'table',
dataSourceResourceId: 'projects-data-source',
properties: [
{ property: 'project-name-property', visible: true },
{ property: 'project-status-property', visible: true },
{ property: 'project-priority-property', visible: true },
{ property: 'project-target-property', visible: true },
],
})
projectsDatabase.addView({
resourceId: 'projects-board-view',
name: 'Projects by status',
type: 'board',
dataSourceResourceId: 'projects-data-source',
groupBy: {
property: 'project-status-property',
type: 'status',
emptyGroupVisibility: 'hide',
},
properties: [
{ property: 'project-priority-property', visible: true },
{ property: 'project-target-property', visible: true },
],
})
The beta supports table, board, calendar, list, gallery, and timeline views, and you can attach sorts and filters to them. For example, if you have a central Docs database shared across a company, each teamspace can get its own pre-filtered view for its team. Everyone shares the same schema, and each team gets the slice they care about without anyone having to rebuild those views by hand.
Define a custom agent
You can define custom agents right alongside your pages and databases. Here’s an agent set up to review project pages:
notion.customAgent({
resourceId: 'project-reviewer-agent',
name: 'Project reviewer',
icon: {
type: 'emoji',
emoji: '🔎',
},
instructions: `# Project reviewer
Review project pages for missing context.
Check that each project has:
- a clear outcome
- an owner
- a target date
- a definition of done
Ask questions when information is missing.
`,
sharedResources: [projectsDatabase.resourceId],
})
The agent gets access to whatever you list in sharedResources, and Notion turns its Markdown instructions into a hidden instruction page for the agent runtime.
The beta types also expose a model property, though right now the accepted values are internal codenames that can change, and the template warns they still need a stable public naming scheme. Skip model for now so the agent inherits the workspace default until that settles down.
Type-check before applying
Before deploying anything, run the type-checker to catch TypeScript errors without touching Notion:
npm run typecheck
Then build the project to write the recorded intents to dist/intents.json:
npm run build
Open dist/intents.json and read through what it generated. Right now, inspecting that file is the closest thing you get to a deployment preview.
A good workflow here is:
- edit the TypeScript
- type-check it
- build the intents
- review the diff and generated intents
- apply to Notion
You can run the first four steps as often as you like, then pause and double-check the output before running the final apply.
Apply the workspace
Deploy your workspace with:
ntn notion-as-code apply .
The CLI builds the project, sends the intents to Notion, and saves local state. Try changing a page title or adding a database property and running the command again. Because the resourceId stays the same, the CLI updates the existing resource instead of creating a second copy.
If you need machine-readable output for scripts or CI, use:
ntn notion-as-code apply . --json
Understand state names
By default, deployment state is saved under the name default. You can pick a different state name when applying:
ntn notion-as-code apply . --name staging
The Notion CLI stores state inside its configuration directory, separated by environment, workspace ID, and state name.
You can list your saved states with:
ntn notion-as-code list
Inspect a specific state with:
ntn notion-as-code state show staging
Remove one with:
ntn notion-as-code state rm staging
Be careful with that last command. Deleting local state doesn’t mean the CLI will rediscover your existing resources in Notion. Without that ID mapping, the next apply has nothing to match against and can create a brand new set of duplicates.
Put the definition in Git
Once your first apply goes through, commit the project to Git:
git add src package.json package-lock.json
git commit -m "Define the engineering workspace"
From that point on, workspace changes follow the same workflow you already use for application code:
- create a branch
- edit the TypeScript
- run the type checker
- review the diff
- merge it
- apply it
Having a Git diff makes it much easier to answer questions the Notion UI leaves murky, like who added a property, why a teamspace exists, when an agent’s instructions changed, or whether the Finance view was supposed to include archived projects.
Just keep in mind that a Git revert isn’t a full Notion rollback. Rolling back the TypeScript and re-applying can restore fields managed by your definition, but it can’t guarantee you’ll get back manual edits, deleted pages, comments, or content that was never in code. Keep your regular workspace backups in place.
Use it with a coding agent
Because the interface is plain TypeScript, coding agents fit right in. An agent can inspect your current definition, read the vendored types, make a focused edit, run the type checker, and show you the diff before anything changes in Notion.
The launch demo uses this pattern. Its prompt asks for several teamspaces, central Docs and Meetings databases, filtered team views, and two custom agents, and it tells the agent to give you a TypeScript outline for review before deploying anything.
Separating authoring from deployment is the part that matters most here. Don’t give an agent a vague prompt and let it run apply right away. Put a few clear rules in AGENTS.md first:
- Read src/lib/types.d.ts before using a new resource type.
- Keep every resourceId stable and unique.
- Run npm run typecheck after each change.
- Run npm run build and inspect dist/intents.json.
- Never run ntn notion-as-code apply without explicit approval.
Agents are great at writing repetitive schema code, while you stay in charge of the workspace architecture and the final apply.
Use it in CI carefully
The CLI accepts a personal access token through the NOTION_API_TOKEN environment variable, so you can store it in your CI secret manager and run apply after a merge.
My advice is not to start with full automation. Try apply in a test workspace first so you see how it behaves, then add a protected deployment job that requires approval. Here’s what a safer pipeline looks like:
Pull request:
type-check -> build -> review intents
After merge:
manual approval -> apply
Keep NOTION_API_TOKEN out of logs and committed .env files, and don’t let pull requests from untrusted forks run with the workspace token. Because the TypeScript project can read local files and environment variables, treat changes to it the same way you treat changes to deployment code.
Decide what code owns
Before rolling this out to a team, draw a clear line between what code owns and what people edit in Notion. Say your code creates a page called “Engineering principles”, a teammate improves it in Notion, and later someone updates the content string in Git and applies it. Without an agreement ahead of time, you won’t know which version should win.
Dividing your resources into three groups makes that line easy to keep.
Code-owned structure
Teamspaces, database schemas, standard views, page templates, agent instructions, and navigation hubs belong in Git. Whenever you need to update them, edit the code, review the diff, and apply.
Human-owned content
Project updates, meeting notes, comments, research, and daily documents belong in Notion. Create a home for them in code, then let people work directly in Notion.
Imported data
For data generated from JSON, CSV, or another system, pick one source of truth. If another system owns the records, make it clear that the Notion copy is derived so teammates don’t edit both versions and expect the beta to sort out the conflict.
Plan for drift
People will still make manual edits in Notion. Some are harmless, like adding a meeting note or updating a project status. Others conflict with your definition, like renaming a property, deleting a view, or changing an agent’s instructions directly in the UI.
Don’t treat the current beta like a mature Terraform replacement. The public template documents create and update behavior, without a full plan, import, drift detection, and destroy workflow. Don’t assume that removing a resource from TypeScript will safely delete it from Notion, or that running apply can rebuild every manual change.
Test those cases in a disposable workspace before writing team policy around them. Until drift handling matures, stick to one rule: if code owns a resource, edit it through code.
Good uses for Notion as Code
This setup makes the most sense whenever you need to spin up the same workspace structure more than once.
If you run an agency, you can keep a client template in Git so every new client gets the same project database, meeting system, docs hub, and onboarding agent. Course creators can spin up a fresh workspace for each cohort with pages, databases, views, and support agents starting from a known state. Companies with regional teams can roll out the same schemas and permissions across offices while letting local teams own their content.
It also works well for disposable demo workspaces. Instead of handing salespeople a workspace copied by hand six months ago, a product team can generate a fresh one with realistic sample data. Even on your own, versioning a personal operating system in Git keeps it easy to reproduce.
Including custom agents in the same definition pushes this well past static templates. Alongside folders and databases, you can reproduce each agent’s instructions, the resources it can access, and the job it’s meant to do.
The deeper idea
The goal isn’t to turn all of Notion into code. Notion works because people can open it and collaborate without deploying anything.
What moves into code is the design of the environment where that work happens. That gives you a clean split:
- people create knowledge in Notion
- code creates the structure around that knowledge
- Git records why the structure changed
- agents help maintain both sides
For years, teams have treated workspace design as a one-time setup task. Someone builds a complicated Notion system, records a walkthrough video, and hopes nobody breaks it. Putting that layout in a TypeScript file means you can review it, test it, copy it, and improve it over time. A coding agent can help update the definition, and every new workspace can start from the current version instead of an old duplicate.
Want me to talk about your product? You can sponsor this site.
Related posts about tools: