DEV Community

Justin
Justin

Posted on

5 2 1

publicRuntimeConfig undefined when using Storybook with Next.js

publicRuntimeConfig is setup for us automatically in a Next app, but that doesn't happen when our code gets bundled into Storybook so we need to do it ourselves.

Developers have previously seen this issue in jest tests, so we'll borrow our solution from them by manually setting the config ourselves. We'll add the following code to .storybook/preview.js (create the file if it doesn't already exist):

// Allow us to use `publicRuntimeConfig` in stories
import { setConfig } from 'next/config';
import { publicRuntimeConfig } from './next.config';
setConfig({ publicRuntimeConfig });

That works fine if your next.config file is simple, but if you do any imports (such as for setting up Next Bundle Analyzer) then you might run into new errors in Storybook caused by it trying to bundle this imports. In that case, you can the runtime config to a separate file and importing just the runtime config into the storybook setup:

// runtimeConfig.js
module.exports {
  // Add your config here
};

// next.config.js
const runtimeConfig = require('./runtimeConfig');
module.exports = {
  publicRuntimeConfig: runtimeConfig
};

// storybook/preview.js
import { setConfig } from 'next/config';
import publicRuntimeConfig from '../src/config';
setConfig({ publicRuntimeConfig });

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay