ScreenshotNeo

BlogHow-to

How to Set Up Chromatic with Storybook in Next.js

Set up Storybook in Next.js, publish it to Chromatic, establish visual baselines, and automate builds with GitHub Actions.

By the ScreenshotNeo team4 October 20269 min read

From your Next.js project root, run npm create storybook@latest and follow the prompts. For most projects, choose Storybook’s Vite-based @storybook/nextjs-vite framework; keep the Webpack-based @storybook/nextjs framework when your project depends on custom Webpack or Babel behavior that cannot move to Vite. Then install Chromatic, create or select a Chromatic project, and publish the first Storybook build to establish visual baselines. In CI, store the Chromatic project token as a secret.

Storybook runs components in isolation for local development. Chromatic publishes that Storybook build to its hosted service and compares later snapshots with the established baselines. A reported visual change needs review: it may be an intended update or a regression.

1. Check the project requirements

Start in the repository root, where the Next.js package.json lives. Storybook’s current Next.js installation documentation lists Next.js 14+ and Node.js 20+ among its requirements. Version support changes, so check the current Storybook Next.js framework guide against your project’s installed versions before installing.

node --version
npm --version

If the project uses another package manager, use its corresponding commands below and keep the same package manager in CI.

Package manager Install Storybook Install Chromatic CI install
npm npm create storybook@latest npm install --save-dev chromatic npm ci
pnpm pnpm create storybook@latest pnpm add --save-dev chromatic pnpm install --frozen-lockfile
Yarn yarn create storybook yarn add --dev chromatic yarn install --immutable for modern Yarn

2. Install Storybook and choose Vite or Webpack

Run the Storybook initializer from the project root and answer the prompts:

npm create storybook@latest

The CLI inspects the project and proposes a configuration. Storybook currently recommends Vite for most Next.js projects because of its build and development startup characteristics, modern test support, and simpler setup. Select @storybook/nextjs-vite unless you need to preserve custom Webpack or Babel configuration, or rely on a specific Webpack feature. Those compatibility needs are reasons to use @storybook/nextjs instead. See the current Vite framework guidance and Webpack framework guidance.

After initialization, inspect the generated files and package scripts. A common setup includes .storybook/main.ts, .storybook/preview.ts, and scripts named storybook and build-storybook. Follow the scripts generated in your project rather than assuming they are identical across Storybook versions.

npm run storybook

Open the local address printed by the command. Add a story for a component and confirm it renders locally before connecting Chromatic. This separates component or Storybook configuration errors from publishing errors.

When to keep Webpack

  • Your Next.js project has custom Webpack or Babel configuration that you cannot migrate.
  • A build integration depends on Webpack-specific behavior.
  • You are upgrading an existing Storybook and need to migrate its existing framework and addons deliberately.

For an existing setup, follow the migration instructions for the installed Storybook release. Older projects may have legacy Next.js addons that are redundant with the current framework. Avoid copying configuration from an older major-version guide without checking compatibility.

3. Make stories match the app’s component context

A component can render in Next.js but fail in Storybook if it expects context that normally comes from a parent layout or provider. Add shared providers as Storybook decorators in .storybook/preview.ts (or the generated preview file). Common examples include a theme provider, localization context, and application-level design-system provider. Use the same configuration and styles the component needs in the application.

Next.js-specific framework support covers features such as images, routing and navigation, fonts, styling, and absolute imports. The precise behavior depends on the framework and installed release. For stories that import next/navigation, set the App Router parameter when appropriate. Configure it for an individual story:

import type { Meta, StoryObj } from '@storybook/nextjs-vite';
import { AccountMenu } from './AccountMenu';

const meta = {
  component: AccountMenu,
  parameters: {
    nextjs: {
      appDirectory: true,
    },
  },
} satisfies Meta<typeof AccountMenu>;

export default meta;
type Story = StoryObj<typeof meta>;

export const Default: Story = {};

Use your actual component and framework types. If all stories use the App Router, put the setting in the global preview parameters instead of repeating it per story. If a story needs router state, provide the relevant pathname or navigation context as documented for your installed framework version.

External fonts and assets

Stories may request fonts, images, or other resources from outside the repository. That can make a local or CI build depend on network access. If Google Font requests fail during the Storybook build, Storybook’s Next.js guidance describes mocking those requests through its documented environment-variable mechanism. Apply that workaround only when the requests are causing failures; it is not a universal requirement. For other assets, consider serving stable local files through Storybook’s static asset configuration so builds do not depend on a remote host.

4. Create a Chromatic project and publish the first build

  1. Create a Chromatic project or select an existing one, then obtain its project token.
  2. Install the Chromatic CLI package as a development dependency.
  3. Run the CLI with the project token. The CLI uses the Storybook build setup by default, builds the Storybook, and uploads it to Chromatic.
  4. Review the first build. Its snapshots establish the initial visual baselines for later comparisons.
npm install --save-dev chromatic
npx chromatic --project-token YOUR_CHROMATIC_PROJECT_TOKEN

Chromatic’s Quickstart and CLI documentation describe project setup and available CLI options. The token identifies the project and must be kept private. Do not commit a real token into a story, workflow file, or repository. For local use, an environment variable avoids placing the token directly in shell history or a tracked file:

export CHROMATIC_PROJECT_TOKEN=YOUR_CHROMATIC_PROJECT_TOKEN
npx chromatic

Use your shell’s appropriate environment-variable syntax on Windows. Chromatic also supports a chromatic.config.json file for CLI configuration; consult the current CLI reference for supported options and precedence. Keep secrets out of that file if it is committed.

What to do with the baseline

Review the first published snapshots and confirm they represent the intended UI. On subsequent builds, inspect visual changes in Chromatic. Accept or update a baseline when the UI change is intentional and reject or investigate it when it is unexpected. A snapshot difference is a signal for review, not proof by itself that a change is a defect.

5. Add Chromatic to GitHub Actions

Add CHROMATIC_PROJECT_TOKEN as a repository Actions secret in GitHub. Then add a workflow that checks out the full repository history, sets up the project’s Node version, installs dependencies from the lockfile, and runs the Chromatic action. Full history is part of Chromatic’s documented workflow pattern and helps it relate builds to repository history.

name: Chromatic
on: push
jobs:
  chromatic:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@<chosen-version>
        with:
          fetch-depth: 0
      - uses: actions/setup-node@<chosen-version>
        with:
          node-version: <project-supported-version>
      - run: npm ci
      - uses: chromaui/action@<chosen-version>
        with:
          projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}

Replace the placeholders with versions compatible with your repository. The tags shown in the live Chromatic GitHub Actions guide can change; choose whether to follow a moving tag, a major-version tag, or an exact version, and review that choice as part of dependency maintenance. For pnpm or Yarn, replace npm ci with the lockfile-enforcing install command for that package manager.

Run on the events that help your review workflow

The minimal example runs on pushes. A team may also want builds for pull requests, depending on its review process and Chromatic configuration. Keep the trigger policy clear so contributors know when visual review is expected. If forked pull requests are enabled, consider that repository secrets generally are not exposed to untrusted fork workflows; configure publishing accordingly rather than weakening secret handling.

6. Troubleshooting common setup failures

Symptom Likely cause What to check
Storybook initializer refuses or misconfigures the project Unsupported or mismatched Node.js, Next.js, or Storybook versions; running outside the app root Check the current framework requirements, run the initializer from the directory containing the intended package.json, and use a supported Node version.
Custom Webpack behavior disappears in Storybook The project selected the Vite framework but depends on Webpack configuration Use Webpack if that behavior cannot migrate, or port the relevant configuration to Vite using the framework’s migration guidance.
A component cannot render a hook from next/navigation The story lacks App Router context or framework parameters Set nextjs.appDirectory: true at story or preview level where appropriate, and provide the route state the component expects.
Story renders blank or throws a context error A required provider, decorator, or application setting is missing Check the browser console and wrap the story with the same theme, data, or application providers it needs.
Storybook build fails while fetching a Google Font The build environment cannot reach the external font endpoint Apply Storybook’s documented font-request mock for this failure, or make the build’s font dependency available through a stable local strategy.
Chromatic says the project token is missing or invalid The token was not supplied, is mistyped, or belongs to another project Check the local environment variable or GitHub secret name and value; confirm it matches the selected Chromatic project.
Chromatic builds locally but fails in CI Dependency installation differs, the token is unavailable, or the Storybook build depends on network resources Use the repository lockfile, verify secret availability for that event, inspect the Storybook build output, and remove or mock unreliable external requests.
Many visual changes appear after the first build The initial baseline differs from the expected environment or stories are unstable Review the snapshots, stabilize data and rendering inputs, and accept only intentional changes as new baselines.
GitHub Action cannot relate a build to prior commits Checkout history is shallow Set fetch-depth: 0 on the checkout step as shown in the documented workflow.

7. Performance, reliability, and cost considerations

  • Build time: Storybook’s Vite framework is recommended for most projects and is described as offering faster builds and development startup. A Vite migration can still require work if your project has custom Webpack or Babel behavior.
  • Reliable builds: Keep dependencies lockfile-based in CI. Avoid making stories depend on unpinned remote data, fonts, or assets where possible. A failed Storybook build should be diagnosed before treating it as a Chromatic publishing problem.
  • Visual stability: Make stories deterministic: control data, dates, and state that change the rendered output. Review changed snapshots before updating baselines.
  • Token security: Store the project token in the CI secret store and limit its exposure to trusted workflows. Never commit it.
  • Service cost: Chromatic is a hosted service. Check its current plan, usage, and billing details directly before choosing a workflow or estimating team cost; the setup references do not establish current prices.

Or skip the browser setup

If the task is capturing a rendered page rather than reviewing component changes, ScreenshotNeo is a website screenshot API and MCP server. One GET request returns a PNG, JPEG, WebP, or PDF, and its API documentation covers the available options. For example:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

Cookie banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, failed loads, and cache hits are not billed, and responses identify the page verdict and billing status. AI agents can use its MCP server, which includes take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo’s free plan.

FAQ

Does Chromatic replace Storybook?

No. Storybook provides the component development environment and build. Chromatic publishes that build and provides hosted visual review and snapshot comparison.

Will Chromatic automatically decide whether a visual change is wrong?

No. It highlights snapshot differences. A developer or reviewer decides whether to accept the change or investigate it.

Can I connect an existing Storybook instead of installing a new one?

Yes. Install Chromatic in the existing project, select or create its Chromatic project, and publish using the project token. Check the current framework migration guidance if the existing Storybook uses an older Next.js integration.

Do I need Chromatic to run Storybook locally?

No. Storybook can run locally on its own. Chromatic is needed for the hosted publishing and visual-review workflow described here.