Publish a post from Notion without a deploy
See how this site used to publish from Notion with server-side fetching, caching and a local fallback.
Update, November 2026. This site now publishes posts from MDX files in Git.
I used to publish a post by ticking a box in Notion. The site fetched rows on the server and showed the published ones, so an edit could go live without waiting for a deploy. A copy in the repo kept posts available when Notion was down.
The examples use TanStack Start 1.169, @notionhq/client 5.27 and Node 22.
Before you start
- A Notion internal integration and its secret, stored as
NOTION_TOKENin your server's environment. Never ship it to the browser. - A page in your workspace shared with that integration. The database goes under it.
- A route that renders on the server and can run code before it renders: a loader, a server function, a request handler.
Create the Posts database
Use a database with one data source for these examples. Add the properties that the server reads.
Title(title): the page title.Slug(text): the URL segment, kebab-case.Deck(text): one sentence shown under the title and in lists.Date(date): what the list sorts by.Tags(multi-select).Published(checkbox): the example queries only ticked rows, so an unticked row is a draft you can still read in Notion.
The body of the page is the post: paragraphs, headings, lists, code blocks, quotes and images. Nothing else is needed.
Query it on the server
Starting with API version 2025-09-03, queries target a data source inside a database. Retrieve the database to find the source ID, then filter by Published and sort by Date.
import { Client } from '@notionhq/client'
const notion = new Client({
auth: process.env.NOTION_TOKEN,
notionVersion: '2025-09-03',
})
async function dataSourceId(databaseId: string) {
const db = await notion.databases.retrieve({ database_id: databaseId })
const id = 'data_sources' in db ? db.data_sources[0]?.id : undefined
if (!id) throw new Error('The database has no accessible data source.')
return id
}
export async function fetchPosts(databaseId: string) {
const data_source_id = await dataSourceId(databaseId)
const pages = []
let cursor: string | undefined
do {
const res = await notion.dataSources.query({
data_source_id,
start_cursor: cursor,
page_size: 100,
filter: { property: 'Published', checkbox: { equals: true } },
sorts: [{ property: 'Date', direction: 'descending' }],
})
pages.push(...res.results)
cursor = res.has_more ? (res.next_cursor ?? undefined) : undefined
} while (cursor)
return pages
}Follow next_cursor while has_more is true. The query returns rows with their properties. Load a post’s body using blocks.children.list with the page ID, paginate that response too, and fetch child blocks where your renderer needs them.
Keep the token on the server. Put fetchPosts in a server-only module and import it into your server function. Call the function from the route loader.
import { createServerFn } from '@tanstack/react-start'
import { fetchPosts } from './notion.server'
export const getPosts = createServerFn({ method: 'GET' }).handler(() =>
fetchPosts(process.env.NOTION_POSTS_DATABASE_ID!),
)export const Route = createFileRoute('/writing/')({
loader: () => getPosts(),
component: WritingPage,
})Set NOTION_POSTS_DATABASE_ID to your database ID and wire up the list page. Without caching, an unticked row disappears on the next server load.
Cache for a minute, let the CDN hold it longer
Asking Notion on every request means every page waits on a network call. Two caches fix that, and they do different jobs.
The server process kept its last result fresh for 60 seconds. The first request after that triggered a refresh while the server returned the previous result. The CDN got this header.
Cache-Control: public, s-maxage=60, stale-while-revalidate=600s-maxage sets the freshness lifetime for a shared cache. stale-while-revalidate permits the cache to serve the old response for another ten minutes while it validates in the background. Vercel consumes shared-cache directives from Cache-Control, so check x-vercel-cache for the outcome at the edge.
Set the header on the route that renders the posts. In TanStack Start:
export const Route = createFileRoute('/writing/')({
loader: () => getPosts(),
headers: () => ({
'cache-control': 'public, s-maxage=60, stale-while-revalidate=600',
}),
component: WritingPage,
})On the deployed site, repeat the request and look for x-vercel-cache: HIT on a cacheable response.
Keep a typed fallback in the repo
Notion will be down one day, or the token will be rotated, or you will clone the repo on a machine with no environment file. The site should still build and still show posts. Keep a copy in the shape the renderer expects. This wrapper assumes a notionEnabled configuration check and a cached helper that implements the server memo.
async function withFallback<T>(key: string, remote: () => Promise<T[]>, local: readonly T[]) {
if (!notionEnabled) return [...local]
try {
return await cached(key, 60, remote)
} catch (error) {
console.error(`[content] ${key}: Notion failed, serving local fallback`, error)
return [...local]
}
}Call this wrapper from getPosts with a cache key, a function that calls fetchPosts, and your local copy. The wrapper serves the repo copy if Notion is off or the first load fails. If a background refresh fails, the memo retains its last value. An empty successful query stays empty, so unpublishing every row does not bring old posts back.
When it does not work
- The query returns a 404. Check the ID and add the integration under Connections on the parent page. For an empty result, check the
Publishedfilter. - Images render for an hour, then break. Notion-hosted file URLs expire after one hour. A cached page can outlive the file URL. Fetch a fresh URL before it expires or use images hosted at stable URLs.
- A new post does not show up. Both cache layers can serve old content. For immediate publishing, refresh the origin memo and purge the CDN entry.