Skip to content
All posts

Building Scalable Storybook Stories with Next.js App Router: A Container-First Approach

Next.js App Router revolutionised how we structure React applications with Server Components, layouts, and nested routing. But when it comes to Storybook, many developers struggle to maintain that same clean architecture.

Matt Claffey · 5 min read
Building Scalable Storybook Stories with Next.js App Router: A Container-First Approach

Next.js App Router revolutionised how we structure React applications with Server Components, layouts, and nested routing. But when it comes to Storybook, many developers struggle to maintain that same clean architecture. Stories become cluttered with inline providers, mock data scattered everywhere, and testing scenarios that are impossible to reproduce.

More importantly, poorly structured Storybook setups become a barrier to collaboration. Designers can’t explore components independently. Product managers can’t review UI states without spinning up the entire application. QA teams struggle to test edge cases. The very tool that should bring teams together ends up widening the gap.

This guide walks through a production-tested pattern for building maintainable Storybook stories that mirror your Next.js architecture, share mock data between development and testing, and — critically — create a shared language between technical and non-technical team members.

TL;DR

  • Use Next.js page/layout patterns in Storybook with shared decorators
  • Mock API calls with MSW, shared between app and Storybook
  • Leverage Storybook parameters to drive story variants
  • Use play functions to test interactive scenarios
  • Keep stories clean — no inline providers or mock handlers
  • Create a shared playground for designers, PMs, QA, and developers

Follow this pattern and your Storybook becomes both technically maintainable and a powerful collaboration tool that brings your entire team together.

Prerequisites

This guide assumes you already have:

  • Next.js 16+ with App Router configured
  • Storybook 10+ installed and running
  • Basic understanding of React Context and Suspense

We won’t cover basic setup — this is about the architecture that comes next.

The Mental Model

> Container → Decorator → Story Flow

Next.js App (Real)               Storybook (Stories)
├─ layout.tsx (context)     →   ├─ Decorator (context)
├─ page.tsx (container)     →   ├─ Story (component)
└─ component.tsx (UI)            └─ Parameters (config)

MSW Handlers (Shared)
├─ /mock/handlers/
├─ /mock/data/variants/
└─ Used by both environments
  • Next.js layouts provide context
  • Storybook decorators mirror that pattern
  • MSW handlers serve both development and stories
  • Parameters drive story behaviour without code duplication

Project Structure

Here’s the folder structure we’ll be working with:

src/
├── app/
│   ├── (routes)/
│   │   ├── dashboard/
│   │   │   ├── layout.tsx          # Context providers
│   │   │   └── page.tsx            # Container component
│   └── features/
│       └── Dashboard/
│           ├── components/
│           │   ├── DashboardWidget.tsx
│           │   └── DashboardWidget.stories.tsx
│           ├── context/
│           │   └── DashboardContext.tsx
│           └── api/
│               └── dashboard.ts
├── mock/
│   ├── handlers/
│   │   ├── dashboard/
│   │   │   └── handlers.ts         # MSW request handlers
│   │   └── handlers.ts              # Combined exports
│   ├── data/
│   │   └── dashboard/
│   │       └── variants.ts          # Pre-configured data states
│   └── node.ts                      # MSW server (development)
├── storybook/
|    └── Decorators/
|        └── DashboardProviderDecorator.tsx
├── public
    └── mockServiceWorker.js

Step 1: Next.js Pages as Containers

In Next.js App Router, pages act as containers that compose providers, fetch data, and render UI components. This is where context lives.

Layout for Global Context

// app/(routes)/dashboard/layout.tsx
import { ThemeProvider } from '@/providers/ThemeProvider'

export default function DashboardLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return <ThemeProvider>{children}</ThemeProvider>
}

Page as Container

// app/(routes)/[id]/dashboard/page.tsx
import { DashboardProvider } from '@/features/Dashboard/context/DashboardContext'
import { DashboardWidget } from '@/features/Dashboard/components/DashboardWidget'

export default async function DashboardPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const { id } = await params // Account UUID like '123e4567-e89b-12d3-a526-426614174000'

  return (
     <DashboardProvider accountId={id}>
        <DashboardWidget />
     </DashboardProvider>
  )
}

💡 Key Insight: Layouts and pages are composition points. Components stay pure and testable. This same pattern translates perfectly to Storybook decorators.

Step 2: Mocking API Calls with Modern React

API Layer with Fetch

export interface DashboardData {
  id: string
  metrics: {
    totalUsers: number
    activeUsers: number
    revenue: number
  }
  lastUpdated: string
}

export async function getDashboardData(
  accountId: string,
): Promise<DashboardData> {
  const response = await fetch(`/api/accounts/${accountId}/dashboard`)

  if (!response.ok) {
    throw new Error('Failed to fetch dashboard data')
  }

  return response.json()
}

Context Provider Pattern

// features/Dashboard/context/DashboardContext.tsx
'use client'
import { createContext, useContext, useState, useEffect } from 'react'
import { getDashboardData, DashboardData } from '../api/dashboard'
const DashboardContext = createContext<DashboardData | null>(null)
export function DashboardProvider({
  accountId,
  children
}: {
  accountId: string
  children: React.ReactNode
}) {
  // Fetch at provider level using the account UUID
  const [data, setData] = useState<DashboardData | null>(null)

  useEffect(() => {
    getDashboardData(accountId).then(setData)
  }, [accountId])

  if (!data) return <p>Loading</p>

  return (
    <DashboardContext.Provider value={data}>
      {children}
    </DashboardContext.Provider>
  )
}
export function useDashboard() {
  const context = useContext(DashboardContext)
  if (!context) {
    throw new Error('useDashboard must be used within DashboardProvider')
  }
  return context
}

Component with useDashboard**() Hook**

// features/Dashboard/components/DashboardWidget.tsx
'use client'

import { useDashboard } from '@/features/Dashboard/context/DashboardContext'

export function DashboardWidget() {
  const data = useDashboard()

  return (
    <div className="dashboard-widget">
      <h2>Dashboard Metrics</h2>
      <div className="metrics">
        <div>Total Users: {data.metrics.totalUsers}</div>
        <div>Active Users: {data.metrics.activeUsers}</div>
        <div>Revenue: ${data.metrics.revenue}</div>
      </div>
      <p>Last updated: {data.lastUpdated}</p>
    </div>
  )
}

⚠️ Important: Suspense boundaries should be at the page level, not in individual components. This prevents waterfall loading and improves perceived performance.

Step 3: Mock Service Worker for Shared Scenarios

MSW is the secret sauce. It intercepts fetch requests in both your development environment and Storybook, allowing you to define mock scenarios once and use them everywhere.

Setting Up MSW

// mock/node.ts (for development)
import { setupServer } from 'msw/node'
import { handlers } from './handlers/handlers'

export const server = setupServer(...handlers)

// Start MSW server in instrumentation.ts (Next.js)
// and in .storybook/preview.tsx (Storybook)

Storybook Configuration

// .storybook/main.ts
import type { StorybookConfig } from '@storybook/nextjs'

const config: StorybookConfig = {
  stories: ['../src/**/*.stories.tsx'],
  addons: ['@storybook/addon-essentials'],
  framework: {
    name: '@storybook/nextjs',
    options: {},
  },
  staticDirs: ['../public'],
}

export default config
import type { Preview } from '@storybook/react'
import { initialize, mswLoader } from 'msw-storybook-addon'
import { handlers } from '../src/mock/handlers/handlers'

initialize({ onUnhandledRequest: 'warn' })

const preview: Preview = {
  loaders: [mswLoader],
  parameters: {
    msw: {
      handlers,
    },
  },
}

export default preview

Data Variants Pattern

Instead of creating mocks inline, define variants of your data states:

// mock/data/dashboard/variants.ts
import { DashboardData } from '@/features/Dashboard/api/dashboard'

export const dashboardVariants = {
  default: {
    id: 'dash-001',
    metrics: {
      totalUsers: 1250,
      activeUsers: 842,
      revenue: 45600,
    },
    lastUpdated: new Date().toISOString(),
  } as DashboardData,

  highTraffic: {
    id: 'dash-002',
    metrics: {
      totalUsers: 15000,
      activeUsers: 12500,
      revenue: 250000,
    },
    lastUpdated: new Date().toISOString(),
  } as DashboardData,

  lowActivity: {
    id: 'dash-003',
    metrics: {
      totalUsers: 150,
      activeUsers: 12,
      revenue: 1200,
    },
    lastUpdated: new Date().toISOString(),
  } as DashboardData,

  error: null, // Used to trigger error states
}

export type DashboardVariant = keyof typeof dashboardVariants

MSW Handlers with Conditional Logic

// mock/handlers/dashboard/handlers.ts
import { http, HttpResponse } from 'msw'
import { dashboardVariants } from '@/mock/data/dashboard/variants'

export const dashboardHandlers = [
  // GET dashboard data by account ID
  http.get('/api/accounts/:id/dashboard', ({ params }) => {
    const { id } = params

    // Map account UUIDs to different dashboard states
    const accountDataMap: Record<string, any> = {
      '123e4567-e89b-12d3-a526-426614174000': dashboardVariants.default,
      '987fcdeb-51a2-43f1-b8c6-d3e4f5a6b7c8': dashboardVariants.highTraffic,
      'a1b2c3d4-e5f6-4a5b-9c8d-7e6f5a4b3c2d': dashboardVariants.lowActivity,
      'a1b2c3d4-e5f6-4a5b-9c8d-123444444444': 'error',
    }

    const data = accountDataMap[id as string]

    if (!data) {
      return new HttpResponse(null, {
        status: 404,
        statusText: 'Dashboard not found',
      })
    }

    if (data === 'error') {
      return new HttpResponse(null, {
        status: 500,
        statusText: 'Internal Server Error',
      })
    }

    return HttpResponse.json(data)
  }),

  // POST to update dashboard (mutations)
  http.post('/api/accounts/:id/dashboard', async ({ params, request }) => {
    const { id } = params
    const body = await request.json()

    return HttpResponse.json({ ...body, id }, { status: 200 })
  }),
]
// mock/handlers/handlers.ts
import { dashboardHandlers } from './dashboard/handlers'
import { userHandlers } from './users/handlers'

export const handlers = [...dashboardHandlers, ...userHandlers]

💡 Why This Matters:

  • Single source of truth for mock data
  • Account UUID-based routing matches your real Next.js app
  • Clean RESTful patterns /api/accounts/:id/dashboard
  • Works identically in dev and Storybook

Step 4: Decorator Pattern in Storybook

Decorators in Storybook mirror the layout/page pattern from Next.js. They wrap your components with the necessary context providers.

Creating a Shared Decorator

// storybook/Decorators/DashboardProviderDecorator.tsx
import type { Decorator } from '@storybook/react'
import { DashboardProvider } from '@/features/Dashboard/context/DashboardContext'
import { Suspense } from 'react'

export const DashboardProviderDecorator: Decorator = (Story, context) => {
  // Get account ID from story parameters, default to a test UUID
  const accountId = context.parameters.accountId

  return (
    <Suspense fallback={<div>Loading...</div>}>
      <DashboardProvider accountId={accountId}>
        <Story />
      </DashboardProvider>
    </Suspense>
  )
}

Using Parameters to Drive Variants

// features/Dashboard/components/DashboardWidget.stories.tsx
import type { Meta, StoryObj } from '@storybook/react'
import { DashboardWidget } from './DashboardWidget'
import { DashboardProviderDecorator } from '@/storybook/Decorators/DashboardProviderDecorator'

const meta: Meta<typeof DashboardWidget> = {
  title: 'Features/Dashboard/DashboardWidget',
  component: DashboardWidget,
  decorators: [DashboardProviderDecorator],
}

export default meta
type Story = StoryObj<typeof DashboardWidget>

export const Default: Story = {
  parameters: {
    accountId: '123e4567-e89b-12d3-a526-426614174000',
  },
}

export const HighTraffic: Story = {
  parameters: {
    accountId: '987fcdeb-51a2-43f1-b8c6-d3e4f5a6b7c8',
  },
}

export const LowActivity: Story = {
  parameters: {
    accountId: 'a1b2c3d4-e5f6-4a5b-9c8d-7e6f5a4b3c2d',
  },
}

export const Error: Story = { 
  parameters: {
    accountId: 'a1b2c3d4-e5f6-4a5b-9c8d-123444444444',
  },
}

✅ Clean Story Files:

  • No inline context providers
  • No inline MSW handlers
  • No mock data duplication
  • Account ID parameter is all you need
  • MSW handlers defined once in handler file
  • Variants defined once, used everywhere
  • Decorators handle all complexity

Step 5: Play Functions for Interactive Testing

Play functions allow you to simulate user interactions and test component behaviour within Storybook.

Interactive Story Example

// features/Dashboard/components/DashboardWidget.stories.tsx
import { userEvent, within, expect } from '@storybook/test'

export const WithRefreshAction: Story = {
  parameters: {
    accountId: '123e4567-e89b-12d3-a526-426614174000',
    msw: {
      handlers: [
        // Handle refresh request
        http.post('/api/accounts/123e4567-e89b-12d3-a526-426614174000/dashboard/refresh', () => {
          return HttpResponse.json({
            ...dashboardVariants.default,
            lastUpdated: new Date().toISOString(),
          })
        }),
      ],
    },
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement)

    // Wait for component to load
    await expect(canvas.getByText('Dashboard Metrics')).toBeInTheDocument()

    // Find and click refresh button
    const refreshButton = canvas.getByRole('button', { name: /refresh/i })
    await userEvent.click(refreshButton)

    // Verify loading state appears
    await expect(canvas.getByText('Refreshing...')).toBeInTheDocument()

    // Verify updated timestamp appears
    await expect(canvas.getByText(/last updated/i)).toBeInTheDocument()
  },
}

Testing Form Interactions

export const FormSubmission: Story = {
  parameters: {
    accountId: '123e4567-e89b-12d3-a526-426614174000',
    msw: {
      handlers: [
        http.post('/api/accounts/123e4567-e89b-12d3-a526-426614174000/dashboard/settings', async ({ request }) => {
          const body = await request.json()
          return HttpResponse.json({ success: true, settings: body })
        }),
      ],
    },
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement)

    // Open settings panel
    const settingsButton = canvas.getByRole('button', { name: /settings/i })
    await userEvent.click(settingsButton)

    // Fill form
    const thresholdInput = canvas.getByLabelText(/alert threshold/i)
    await userEvent.clear(thresholdInput)
    await userEvent.type(thresholdInput, '5000')

    // Submit
    const saveButton = canvas.getByRole('button', { name: /save/i })
    await userEvent.click(saveButton)

    // Verify success message
    await expect(canvas.getByText(/settings saved/i)).toBeInTheDocument()
  },
}

🎯 Play Functions Enable:

  • Visual regression testing
  • Interaction testing
  • User journey validation
  • Automatic accessibility checks

Advanced Patterns

Global vs Story-Specific Decorators

Sometimes you need decorators applied to all stories (like theme providers), while others are specific to certain features.

Global Decorators

import type { Preview } from '@storybook/react'

const preview: Preview = {
  decorators: [ThemeProviderDecorator],
  parameters: {},
}

export default preview

Story-Specific Decorators

// features/Dashboard/components/DashboardWidget.stories.tsx
const meta: Meta<typeof DashboardWidget> = {
  title: 'Features/Dashboard/DashboardWidget',
  component: DashboardWidget,
  decorators: [
    DashboardProviderDecorator, // Only for Dashboard stories
  ],
}

Decorators are applied in order: global decorators first (outermost), then story-specific decorators (innermost).

Passing Dashboard ID as a Prop

The key to the pattern is that the account ID flows through the entire stack:

Story Parameter (accountId: '987fcdeb-51a2-43f1-b8c6-d3e4f5a6b7c8')
  ↓
Decorator reads parameter
  ↓
DashboardProvider receives accountId prop
  ↓
getDashboardData(accountId) called
  ↓
MSW handler matches route /api/accounts/:id/dashboard
  ↓
Returns corresponding variant based on UUID

This creates a clean, predictable flow where the account UUID is the single source of truth, mirroring how your real application would work.

Dynamic Handlers Based on Parameters

Instead of using window objects, pass the account UUID through the URL:

// Each story specifies a unique account UUID
export const HighTrafficAccount: Story = {
  parameters: {
    accountId: '987fcdeb-51a2-43f1-b8c6-d3e4f5a6b7c8',
  },
}

This pattern provides:

  • Type-safe account UUIDs matching real database IDs
  • RESTful API patterns (/api/accounts/:id/dashboard)
  • Clear mapping between UUIDs and data scenarios
  • Realistic testing with production-like identifiers

Composing Multiple Decorators

// features/Dashboard/components/DashboardWidget.stories.tsx
const meta: Meta<typeof DashboardWidget> = {
  title: 'Features/Dashboard/DashboardWidget',
  component: DashboardWidget,
  decorators: [
    DashboardProviderDecorator,
    AuthProviderDecorator,
    ThemeProviderDecorator,
  ],
}

Decorators are applied in order, from last to first (innermost to outermost).

Testing Multiple API States

export const SequentialLoading: Story = {
  parameters: {
    accountId: '123e4567-e89b-12d3-a526-426614174000',
    msw: {
      handlers: [
        // Initial slow request
        http.get('/api/accounts/123e4567-e89b-12d3-a526-426614174000/dashboard', async () => {
          await delay(2000)
          return HttpResponse.json(dashboardVariants.default)
        }),
        // Secondary fast request
        http.get('/api/dashboard/notifications', () => {
          return HttpResponse.json({ count: 5 })
        }),
      ],
    },
  },
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement)

    // Main content should still be loading
    await expect(canvas.getByText('Loading...')).toBeInTheDocument()

    // But notifications loaded immediately
    await expect(canvas.getByText('5 notifications')).toBeInTheDocument()

    // Wait for main content
    await expect(canvas.getByText('Dashboard Metrics')).toBeInTheDocument()
  },
}

Common Mistakes to Avoid

❌ Inline providers in story files

❌ Duplicating mock data across stories

❌ Not using Suspense boundaries

❌ Tightly coupling stories to specific implementations

❌ Forgetting to clear MSW state between stories

✅ Use shared decorators

✅ Define variants once, reference everywhere

✅ Wrap providers in Suspense at decorator level

✅ Test behaviour, not implementation

✅ Reset MSW handlers in beforeEach if needed

Final Takeaway

The winning pattern looks like this:

  1. Layouts/Pages: Define context at the container level

  2. Decorators: Mirror that structure in Storybook

  3. MSW: Share mock handlers between dev and Storybook

  4. Variants: Pre-configure data states once

  5. Parameters: Drive story behavior declaratively

  6. Play Functions: Test interactions visually

For Developers

When done correctly, you get:

  • 🏗️ Architecture that scales with your app
  • 🎨 Stories that stay clean and maintainable
  • 🔄 Mock scenarios shared across environments
  • 🧪 Visual testing with user interactions
  • 📚 Living documentation that stays up-to-date

For The Entire Team

But the real power lies in what this unlocks for collaboration:

For Designers:

  • Review components in isolation without running the full app
  • Explore every UI state (loading, error, empty, success) instantly
  • Validate designs against real data variants
  • Catch inconsistencies before they reach production

For Product Managers:

  • Demo features to stakeholders without backend dependencies
  • Review user journeys with interactive play functions
  • Understand edge cases through pre-configured scenarios
  • Make informed decisions with visual evidence

For QA Teams:

  • Test every component state systematically
  • Reproduce bugs in isolation
  • Validate accessibility requirements
  • Document test cases visually

For Leadership:

  • Share progress with stakeholders via published Storybook
  • Get early feedback before features are fully integrated
  • Reduce miscommunication between design and development
  • Speed up onboarding for new team members

Storybook stops being a developer tool and becomes a shared workspace where everyone speaks the same language. Designers see their work implemented. Product managers validate requirements. QA finds issues earlier. Developers build with confidence.

If you’re building serious Next.js apps in 2025+, this pattern isn’t just about clean code — it’s about bringing your entire team together around a single source of truth.

Resources


Originally published on Medium.