loading...

publicRuntimeConfig undefined when using Storybook with Next.js

justincy profile image Justin ・1 min read

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 });

Posted on by:

Discussion

markdown guide