Architecture overview
Navigating global states is one of the most common hurdles when migrating to a headless architecture. In a traditional content management system (CMS), headers and footers are built directly into the site's theme. Storyblok, however, is a headless CMS—it acts as a database for content and doesn't build the webpage or dictate the layout.
Because global components—such as headers, complex mega-menus, and footers—appear on every single page, they cannot be tied to a standard home or about page entry. Model this data using a dedicated global settings story to act as the single source of truth. This structure guarantees that the frontend makes efficient application programming interface (API) calls on every page load, and it provides a flexible, intuitive visual editing experience for the marketing team.
Before building the schemas, review how the data is nested. In a headless environment, a complex dropdown menu is a tree of blocks inside a single JSON object. Review the following structural map to understand how the global settings story connects to the deep navigation nodes:
Prerequisites and setup
Before proceeding with the content model and code implementation, ensure your development environment meets the following requirements:
- A Next.js 15 project utilizing the App Router.
- A registered Storyblok space with a designated development token.
- The official React SDK installed in your project.
1. Initialize Your Next.js Project
Open your terminal and run the following command to create a brand new Next.js 15 application. Press Enter to accept the default prompts (TypeScript, Tailwind CSS, App Router).
npx create-next-app@latest my-storyblok-site
cd my-storyblok-site
2. Install the Storyblok SDK
To install the SDK, run the following command in your terminal:
npm install @storyblok/react
@storyblok/react SDK.To allow the Next.js frontend to securely communicate with the Storyblok API, you must configure your preview token. Create a .env.local file in the root of your Next.js project and add your space's access token:
NEXT_PUBLIC_STORYBLOK_TOKEN=your_preview_token_here
Step-by-step execution
1. Configure the visual editor
To establish the global configuration, set up the root story within the Storyblok interface:
- Navigate to Content in your Storyblok space.
- Create a new folder named Settings.
- Generate a new story inside the folder named Global.
- Set the story slug to
/settings/global.
This dedicated entry acts as the central hub for the application's layout. Because this story manages site-wide configurations, it's also the ideal location to house default search engine optimization (SEO) metadata, such as fallback meta descriptions, Open Graph images, or global favicon assets.
2. Build the content model
To build a complex, multi-level navigation system, define a nested schema inside Storyblok. Instead of using flat key-value data sources or shallow reference fields, use a single-instance configuration story combined with nested components (blocks).
Configure the following schema requirements:
Global settings
This content type block acts as the root schema container.
| Property | Type | Description |
|---|---|---|
header | Blocks | Restricted strictly to the header component. |
footer | Blocks | Restricted strictly to the footer component. |
default_seo | Plugin | Optional field for site-wide metadata plugins. |
global_settings schema in the Block Library. This visualizes how the header and footer blocks must be nested to structure your layout data.Header
This nestable block houses the branding and the top level of the navigation grid.
| Property | Type | Description |
|---|---|---|
logo | Asset | Accepts image files for the company logo. |
nav_items | Blocks | Allowed components restricted to nav_item and nav_dropdown. |
logo (Asset) and nav_items (Blocks) fields.Nav item
This nestable block represents a single, interactive hyperlink (for example, "Home" or "Pricing").
| Property | Type | Description |
|---|---|---|
label | Text | The visible link name. |
link | Multilink | Handles internal stories, external URLs, and mailto links. |
Nav dropdown
This nestable block is the parent container for a mega-menu or dropdown (for example, "Products"). By placing a blocks field inside another block, you create the recursive parent-child structure required for deep navigation.
| Property | Type | Description |
|---|---|---|
label | Text | The dropdown trigger text. |
sub_items | Blocks | Allowed components restricted to nav_item. |
nav_dropdown component. Note the vital step of explicitly selecting the "Nestable block" radio button.3. Optimize the editor experience
Headless architectures frequently fracture the content editing experience, forcing marketing teams to edit form fields blindly without seeing the visual output. This content model resolves that disconnect by natively integrating with Storyblok's Visual Editor.
By keeping the entire navigation structure inside a single story using nestable blocks, content editors can open the /settings/global file and interact with the header visually. They can drag and drop nav_item blocks inside a nav_dropdown to reorder the menu. To update link labels, editors select the text directly in the visual preview, bypassing the sidebar form fields entirely.
This visual feedback loop relies on the ...storyblokEditable(item) spread operator implemented in the Next.js frontend. The storyblokEditable utility parses the hidden _editable JSON property returned by the Storyblok API and attaches specific HTML data attributes (data-blok-c and data-blok-uid) to the Document Object Model (DOM) elements. The Visual Editor bridge reads these injected attributes to draw real-time bounding boxes around the navigation links. When an editor selects a bounding box on the screen, the interface instantly opens the corresponding nested block in the sidebar.
Because layout.tsx is an asynchronous Server Component, the visual editor updates upon editor save events or via the Next.js Draft Mode preview URL. Direct, real-time typing reactivity on every keystroke requires client-side state hooks (such as useStoryblokState). Therefore, global root layouts rely on save events to trigger layout re-renders while still maintaining interactive visual bounding boxes and sidebar selection.
4. Initialize the Storyblok bridge
To enable the real-time visual editing experience, initialize the SDK using a provider component. The @storyblok/react/rsc package provides a storyblokInit function that instantiates the client and loads the Storyblok Bridge for Server Components.
Within this initialization, pass the apiPlugin inside the use array. Under the hood, the apiPlugin attaches the core Storyblok API client (storyblok-js-client) to the React SDK. This integration handles rate limit orchestration, resolves cache versioning, and enables the getStoryblokApi utility to securely fetch content using the provided access token, abstracting complex representational state transfer (REST) interactions away from the UI layer.
Create a StoryblokProvider.tsx file to wrap your application:
"use client";
import { storyblokInit, apiPlugin } from "@storyblok/react/rsc";
storyblokInit({
accessToken: process.env.NEXT_PUBLIC_STORYBLOK_TOKEN,
use: [apiPlugin],
});
export default function StoryblokProvider({ children }: { children: React.ReactNode }) {
return <>{children}</>;
}
5. Fetch the global configuration
Fetch the global data in the root app/layout.tsx file. Next.js 15 doesn't cache fetch requests by default. Use the tags option to cache the heavy mega-menu payload at the edge. This prevents the application from exhausting Storyblok API rate limits on every page route.
In production environments, external APIs experience latency or failure. Implement a try/catch block to handle potential network errors gracefully and provide a fallback UI, ensuring the application layout doesn't crash when attempting to retrieve the navigation structure.
import { draftMode } from "next/headers";
import StoryblokProvider from "./components/StoryblokProvider";
import Navigation from "./components/Navigation";
import "./globals.css";
async function getGlobalConfig() {
try {
const { isEnabled } = await draftMode();
const version = isEnabled ? "draft" : "published";
const res = await fetch(
`https://api.storyblok.com/v2/cdn/stories/settings/global?version=${version}&token=${process.env.NEXT_PUBLIC_STORYBLOK_TOKEN}`,
{
next: { tags: ["storyblok-global"] }
}
);
if (!res.ok) {
throw new Error("Failed to fetch Storyblok configuration");
}
return await res.json();
} catch (error) {
console.error(error);
return null; // Return null to trigger fallback state
}
}
export default async function RootLayout({ children }: { children: React.ReactNode }) {
const data = await getGlobalConfig();
const headerData = data?.story?.content?.header?.[0];
const footerData = data?.story?.content?.footer?.[0];
return (
<html lang="en">
<StoryblokProvider>
<body className="antialiased text-gray-900 bg-white">
<header className="w-full p-6 border-b border-gray-200">
<nav className="max-w-5xl mx-auto flex justify-between items-center">
{headerData?.logo?.filename && (
<img src={headerData.logo.filename} alt="Site Logo" className="h-8 w-auto" />
)}
{headerData ? (
<Navigation items={headerData.nav_items} />
) : (
<p>Navigation unavailable</p>
)}
</nav>
</header>
<main className="min-h-screen">{children}</main>
<footer className="w-full p-8 bg-gray-100 text-sm">
<div className="max-w-5xl mx-auto">
{footerData && <Navigation items={footerData.nav_items} />}
</div>
</footer>
</body>
</StoryblokProvider>
</html>
);
}
layout.tsx file. This serves as a visual check for your file structure and React integration.To make this fully functional inside the Storyblok Visual Editor iframe, ensure you have a simple Next.js draft mode route handler to toggle the preview session:
import { draftMode } from "next/headers";
export async function GET() {
const draft = await draftMode();
draft.enable();
return new Response("Draft mode enabled");
}
6. Invalidate the cache with webhooks
If the global layout caches at the edge, it requires an on-demand revalidation trigger to update when a content editor publishes changes. Without this trigger, the cache serves stale navigation data indefinitely.
To resolve this, create a Next.js Route Handler at app/api/revalidate/route.ts to listen for Storyblok webhooks, verify the payload, and purge the corresponding cache tag:
import { revalidateTag } from "next/cache";
import { NextResponse } from "next/server";
export async function POST(request: Request) {
const payload = await request.json();
// Verify the webhook payload/secret from Storyblok here
if (payload.action === "published") {
revalidateTag("storyblok-global");
return NextResponse.json({ revalidated: true, now: Date.now() });
}
return NextResponse.json({ revalidated: false, now: Date.now() });
}
7. Map components dynamically with TypeScript
Unlike traditional monolithic platforms where templates are hardcoded to specific URLs, a headless frontend receives a polymorphic array of JSON blocks. The structure of this array is unpredictable, dictated solely by how the editor arranges the blocks in the CMS.
To render this flexible data, the frontend utilizes dynamic component mapping evaluated against strict TypeScript interfaces. The Navigation component iterates over the items array and evaluates the component property string attached to each object. By checking if (item.component === "nav_dropdown") before rendering a nested list, you decouple the visual layout from the underlying data structure.
This component is designated as a client component ("use client") because it requires browser APIs to manage the interactive state (aria-expanded) of the dropdown menus. Keeping this leaf component on the client while preserving the fetch logic in the server layout optimizes bundle sizing.
Define explicit TypeScript interfaces that mirror the Storyblok schema to enforce type safety. To meet production accessibility standards, implement a useEffect hook to manage keyboard and mouse events. If a user tabs into the menu and activates the Escape key, or interacts outside the dropdown container, the active menu panel closes automatically.
"use client";
import Link from "next/link";
import { useState, useEffect, useRef } from "react";
import { storyblokEditable } from "@storyblok/react/rsc";
export interface StoryblokLink {
id?: string;
url?: string;
linktype?: "story" | "url" | "email";
cached_url?: string;
target?: "_blank" | "_self";
}
export interface NavItemBlock {
_uid: string;
component: "nav_item";
label: string;
link: StoryblokLink;
_editable?: string;
}
export interface NavDropdownBlock {
_uid: string;
component: "nav_dropdown";
label: string;
sub_items: NavItemBlock[];
_editable?: string;
}
export type NavigationItem = NavItemBlock | NavDropdownBlock;
export default function Navigation({ items }: { items: NavigationItem[] }) {
const [openDropdown, setOpenDropdown] = useState<string | null>(null);
const menuRef = useRef<HTMLUListElement>(null);
useEffect(() => {
function handleKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") setOpenDropdown(null);
}
function handleClickOutside(event: MouseEvent) {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
setOpenDropdown(null);
}
}
document.addEventListener("keydown", handleKeyDown);
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("keydown", handleKeyDown);
document.removeEventListener("mousedown", handleClickOutside);
};
}, []);
if (!items || items.length === 0) return null;
return (
<ul ref={menuRef} className="flex gap-6 relative">
{items.map((item) => {
// Render a flat navigation link
if (item.component === "nav_item") {
const href = item.link.linktype === "story"
? `/${item.link.cached_url}`
: item.link.url;
return (
<li key={item._uid} {...storyblokEditable(item)}>
<Link
href={href}
target={item.link.target || "_self"}
className="hover:text-blue-600 transition-colors"
>
{item.label}
</Link>
</li>
);
}
// Render an interactive dropdown and recursively map its children
if (item.component === "nav_dropdown") {
const isOpen = openDropdown === item._uid;
return (
<li key={item._uid} {...storyblokEditable(item)} className="relative">
<button
aria-haspopup="menu"
aria-expanded={isOpen}
onClick={() => setOpenDropdown(isOpen ? null : item._uid)}
className="flex items-center gap-1 hover:text-blue-600"
>
{item.label}
<svg className={`w-4 h-4 transition-transform ${isOpen ? "rotate-180" : ""}`} fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
</button>
{isOpen && (
<div className="absolute top-full left-0 mt-2 w-48 bg-white border border-gray-200 shadow-lg rounded-md p-4 z-50">
<div className="flex flex-col gap-3">
<Navigation items={item.sub_items} />
</div>
</div>
)}
</li>
);
}
return null;
})}
</ul>
);
}
Troubleshooting: Mixed-content errors
When running the Next.js development server on localhost:3000 (HTTP) and accessing it via the Storyblok Visual Editor (HTTPS), your browser may block the iframe due to mixed-content security policies. This results in a "localhost refused to connect" error.
mkcert HTTPS proxy fix.To resolve this on macOS, configure an HTTPS proxy using tools like mkcert and local-ssl-proxy to serve your local environment over a secure connection.
Live demo
Header Navigation
The header successfully renders the Storyblok Navigation structure, showing the "Products" dropdown containing "Security" and "Analytics", along with the "Home" link.
Footer Links
The footer correctly displays the fallback structure with explicitly added links for "Privacy Policy" and "Terms of Service".
Next steps
By shifting the architectural approach away from fragmented reference components and toward a single nested settings object, you construct a highly scalable global navigation system. Integrating this content model with the Next.js App Router caching primitives ensures the application remains highly performant, while storyblokEditable empowers the marketing team to orchestrate complex layouts directly inside the Visual Editor.
To scale this architecture for enterprise requirements, expand the fetching logic in layout.tsx to accept localization parameters. By passing a specific locale string to the Storyblok API call, you enable field-level translations, allowing a single global story to deliver dynamically translated mega-menus across international deployments.