Skip to content

Storyblok integration pattern with Next.js

Operator pattern for integrating Storyblok with a Next.js frontend: stories, components, the Visual Editor, draft vs published, and the deploy boundary.

Storyblok is a SaaS headless CMS that pairs with whichever frontend framework you’re already using — Next.js, Nuxt, Astro, plain HTML. Its differentiator is the Visual Editor: editors see the live frontend rendered inside the admin UI, with click-to-edit on every component. This article is the operator’s pattern for the Next.js side of that integration: how stories map to routes, what the Visual Editor needs from your iframe, how draft vs published works at deploy time, and the webhook plumbing that keeps the CDN in sync.

How to verify

A correct Storyblok + Next.js integration shows:

curl -s "https://api.storyblok.com/v2/cdn/stories/home?token=<public-token>" | jq '.story.name'
# "Home"

curl -sI https://example.org/ | grep -i x-vercel-cache
# x-vercel-cache: HIT

curl -sI -X POST "https://example.org/api/revalidate?secret=..." \
  -d '{"story_id": 12345, "full_slug": "home"}'
# 200

# In the Visual Editor, the preview iframe sets:
# Storyblok-Editor: true header

If the Visual Editor shows a blank iframe with a CSP error in the console, the frontend’s CSP doesn’t include app.storyblok.com in frame-ancestors — fix that or the editor experience is broken.

What’s happening

Storyblok content is structured as “stories” (think pages or content entries) made up of “blocks” (reusable components). Both are configured in Storyblok’s admin: you define a “block” with fields (text, image, asset, link, bloks-of-blocks), and stories instantiate blocks in a tree. The frontend resolves a story by slug, walks the block tree, and renders each block with a corresponding React/Vue/Astro component.

There are two API surfaces. The Content Delivery API (api.storyblok.com/v2/cdn/...) serves published content via a global CDN — fast, cacheable. The Management API (mapi.storyblok.com) is for the Storyblok UI and any custom scripting (bulk imports, content migrations) — it requires a personal access token, not the public preview token. Your Next.js app reads exclusively from the CDN.

Draft vs published is a query-string toggle. ?version=published returns the latest published state; ?version=draft returns work-in-progress. Your frontend uses published for visitor traffic and draft only when called from the Visual Editor iframe. Storyblok injects a _storyblok query param when loading your preview URL inside the editor; the frontend reads that and switches to draft mode.

The Visual Editor is an iframe of your frontend embedded in the admin. It uses postMessage to tell your frontend “the editor clicked block 7” and your frontend uses postMessage back to tell the editor “block 7 is at this DOM position.” A small Storyblok bridge JS library handles both sides.

The procedure

  1. Install the Storyblok SDK.

    npm install @storyblok/react @storyblok/js
  2. Initialize the client. In a Next.js app, this happens in a StoryblokProvider at the root layout:

    // app/StoryblokProvider.tsx
    import { storyblokInit, apiPlugin } from '@storyblok/react/rsc';
    import Hero from '@/components/Hero';
    import Page from '@/components/Page';
    
    storyblokInit({
      accessToken: process.env.STORYBLOK_PUBLIC_TOKEN,
      use: [apiPlugin],
      components: { hero: Hero, page: Page },
    });
  3. Resolve stories by slug.

    // app/[...slug]/page.tsx
    import { getStoryblokApi } from '@storyblok/react/rsc';
    
    export default async function Page({ params }: { params: { slug: string[] } }) {
      const slug = params.slug?.join('/') || 'home';
      const sbParams = { version: 'published' as const };
      const { data } = await getStoryblokApi().get(`cdn/stories/${slug}`, sbParams, {
        next: { tags: [`story:${slug}`] },
      });
      return <StoryblokStory story={data.story} />;
    }
  4. Wire draft mode for the Visual Editor. A middleware checks for the _storyblok query param and sets a draft cookie:

    // middleware.ts
    import { NextResponse } from 'next/server';
    export function middleware(req: Request) {
      const url = new URL(req.url);
      if (url.searchParams.has('_storyblok')) {
        const res = NextResponse.next();
        res.cookies.set('sb-preview', '1', { sameSite: 'none', secure: true });
        return res;
      }
    }

    In the page, switch to version: 'draft' when the preview cookie is set.

  5. Configure the Visual Editor preview URL. In Storyblok > Settings > Visual Editor, set the location to https://example.org/?_storyblok (or a preview-specific URL like https://preview.example.org/). Storyblok loads that URL inside the iframe with the _storyblok query string.

  6. Write the revalidation webhook. In Storyblok > Settings > Webhooks, add a webhook for “Story published” pointing at https://example.org/api/revalidate:

    // app/api/revalidate/route.ts
    import { revalidateTag } from 'next/cache';
    export async function POST(req: Request) {
      const sig = req.headers.get('webhook-signature');
      if (!verifySignature(sig, await req.text())) return new Response('forbidden', { status: 403 });
      const { full_slug } = await req.json();
      revalidateTag(`story:${full_slug}`);
      return Response.json({ ok: true });
    }

    The webhook signature secret is configured in the same settings page — don’t skip it; without verification, anyone who finds the webhook URL can invalidate your cache.

  7. Set CSP to allow the editor. Your frontend headers must include frame-ancestors 'self' https://app.storyblok.com or the editor’s iframe shows a blank page.

  8. Pin tokens by environment. Two tokens minimum: a public “preview” token for the editor + your CMS reads, and a separate one for production builds that only sees the published version. Never use a personal access token in browser code.

Common pitfalls

  • The Storyblok bridge JS must be loaded only inside the editor iframe, not on production pages — visible artifacts otherwise. Use a feature flag tied to the draft cookie.
  • Webhook delivery is at-least-once — revalidateTag is idempotent, but if your handler also writes to a database, dedupe by event id.
  • Draft content rendered by accident on a production page leaks unpublished copy. Always default to published and gate draft behind explicit cookie/server check.
  • The CDN cache TTL on Storyblok side is short (~5 min for the JSON API), but cv cache versioning lets you flush instantly — pass cv: Date.now() on the next read after a webhook fires.
  • Blocks renamed in Storyblok don’t auto-rename in your component registry — a renamed block silently renders nothing until you map the new name in storyblokInit.

For teams running Storyblok with a Next.js frontend, Stack Harbor operates the integration — webhook signatures verified, draft/published gates enforced, CSP audited at release, token rotation scheduled — so the editorial team can use the Visual Editor without the engineering team firefighting drift. That model lives under managed operations, with related Sanity and Headless WordPress notes alongside.