How to Cleanly Swap Between React Native Storybook 10 and Your App

Authors
Daniel Williams
Senior Software Engineer
@
Callstack

Back in 2023, I wrote a post on the same topic, titled How to swap between React Native Storybook and your app.

A lot has changed since then. I was honestly surprised with how many people actually found that tutorial useful.

However,  the original post has now become quite outdated, which is why I wanted to revisit this topic. In this updated version, I'd like to show you how much easier the whole process  is today and how to make sure that nothing leaks into your production bundle.

What's changed?

A number of updates have been introduced that make the process simpler today. Let's go through them.

Built-in support for environment variables in Expo

At the time of the original post, there wasn't a built-in solution for environment variables in Expo, which is why we made use of Expo Constants. This worked as well, but required a few extra steps.

The withStorybook Metro helper function

In newer versions of React Native Storybook, we now include a Metro helper that applies some Metro configuration and handles generating your story imports.

This also made it possible for us to introduce improvements to how we enable/disable Storybook.

Metro improvements

We've also gained some newer configuration options in Metro such as resolver.resolveRequest that allow you to override some resolver functionality with your own logic. For example, for Storybook files, we make sure that enablePackageExports is enabled.

Let's get into it

I'll split this into Expo and community CLI guides, so scroll down if you aren't using Expo.

The Expo guide

I'm going to assume you already have a project set up to keep things simple. If you want to see how to get started  with Expo Router,  check out my article on the Expo blog.

I have also set up a blank TypeScript example app here that only has Storybook setup. In the pull requests for this repository, I also made the same changes outlined below.

Let's assume you have a project like this with the basic setup for Storybook already done.

.rnstorybook/
src/index.tsx
app.tsx
metro.config.js

Make sure you’ve already added the withStorybook function to your Metro config like this:‍

// metro.config.js
const { getDefaultConfig } = require("expo/metro-config");
const {
  withStorybook,
} = require("@storybook/react-native/metro/withStorybook");

/** @type {import('expo/metro-config').MetroConfig} */
const config = getDefaultConfig(__dirname);

module.exports = withStorybook(config);

‍

Now, let's take a look at a simple way, in which you can add storybook to your app and still be able to swap back to your application whenever you need to.

Use an environment variable

First, let's add a Storybook script to our package.json:

{
  "scripts": {
    "storybook": "EXPO_PUBLIC_STORYBOOK_ENABLED=true expo start",
  }
}

‍

This is just the start command, but with the EXPO_PUBLIC_STORYBOOK_ENABLED environment variable set to true.

Expo will inject environment variables into process.env like you might be used to from server or web frameworks.

Now let's go to our App.tsx and add some logic to show Storybook when our variable is set to true.

// App.tsx
import StorybookUI from './.rnstorybook';
import { AppRoot } from './src';

const isStorybook = process.env.EXPO_PUBLIC_STORYBOOK_ENABLED === 'true';

export default function App() {
  return isStorybook ? <StorybookUI/> : <AppRoot />;
}

Now, whenever you run npm run storybook you see Storybook, and whenever you run npm run start, you see your app.

But my production bundle!

You might notice that we're importing Storybook even when not using it. This will cause Metro to include all the dependencies in the bundle.

This is where we bring in the new Metro options.

Update your Metro config to pass some options to withStorybook.

// metro.config.js

module.exports = withStorybook(config, {
  enabled: process.env.EXPO_PUBLIC_STORYBOOK_ENABLED === "true", // <-
});

‍

The enabled option, when set to false in version 10, will actually strip Storybook out of your bundle. I will explain a bit more about how that works at the end, in case you are interested.

That's it!

Nothing else is needed, and from here on out, you can expand on this idea and come up with more developer-friendly ways to hide/show Storybook. One example is to create a dev menu option and use it to toggle Storybook in combination with the environment variable.

Expo Router

With Expo Router, I recommend putting Storybook in its own route and using a protected route to disable it when Storybook is not enabled.

// app/_layout.tsx

export default function RootLayout() {
  return (
    <Stack screenOptions={{ headerShown: false }}>
      <Stack.Screen name="index" />

      <Stack.Protected
        guard={process.env.EXPO_PUBLIC_STORYBOOK_ENABLED === "true"}
      >
        <Stack.Screen name="storybook" />
      </Stack.Protected>
    </Stack>
  );
}

Community CLI

If you are using the Community CLI or Rock, you can follow this guide.

I'm going to assume you already have a project setup to keep things simple. You can find an example project here.

Let's assume you have a project like this

.rnstorybook/
src/index.tsx
app.tsx
metro.config.js

Make sure you’ve already added the withStorybook function to your Metro config like this:

// metro.config.js
const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');

const {
  withStorybook,
} = require("@storybook/react-native/metro/withStorybook");

const config = {};

const finalConfig = mergeConfig(getDefaultConfig(__dirname), config);

module.exports = withStorybook(finalConfig);

‍

Now, let's look at a simple way, in which you can add Storybook to your app and still be able to swap back to your application when you need to.

Use an environment variable

By using the Babel plugin babel-plugin-transform-inline-environment-variables we can get environment variables on process.env and use that to make things easier.First, install the package:

npm install babel-plugin-transform-inline-environment-variables

Now, add the plugin to your babel.config.js:‍

//babel.config.js
module.exports = {
  presets: ['module:@react-native/babel-preset'],
  plugins: [
    'transform-inline-environment-variables', // <--
  ],
};

‍

Let's add a Storybook script to our package.json:

{
  "scripts": {
    "storybook": "STORYBOOK_ENABLED=true react-native start",
  }
}

‍

This is just the start command but with the STORYBOOK_ENABLED environment variable set to true.

Now, let's go to our app and add a simple bit of logic for toggling Storybook.

// App.tsx
import StorybookUI from './.rnstorybook';
import { AppRoot } from './src';

const isStorybook = process.env.STORYBOOK_ENABLED === 'true';

export default function App() {
  return isStorybook ? <StorybookUI/> : <AppRoot />;
}

‍

Now, whenever you use npm run storybook you see Storybook and whenever you use npm run start, you see your app.

‍

But my production bundle!

You might notice that we're importing Storybook even when not using it. This will cause Metro to include all the dependencies in the bundle.

However, this is where we bring in the new Metro options.

Update your Metro config to pass some enabled option to withStorybook helper:

// metro.config.js
module.exports = withStorybook(finalConfig, {
  enabled: process.env.EXPO_PUBLIC_STORYBOOK_ENABLED === "true", // <-
});

‍

The enabled option, when set to false in version 10 and higher, will actually strip Storybook out of your bundle.

That's it!

Nothing else is needed. From here on out you can expand on this idea and come up with more developer friendly ways to hide/show Storybook. For example, you can create a dev menu option and use it to toggle Storybook in combination with the environment variable.

How does this work under the hood?

The withStorybook wrapper makes use of custom resolvers like I've mentioned earlier in this post.

First, let me expand a bit on what I mean by that.

Mocking with Metro

If you look at the Expo docs about Metro, you'll find an example that nicely illustrates how you can use resolvers to mock out a module.

const { getDefaultConfig } = require('expo/metro-config');

/** @type {import('expo/metro-config').MetroConfig} */
const config = getDefaultConfig(__dirname);

config.resolver.resolveRequest = (context, moduleName, platform) => {
  if (platform === 'web' && moduleName === 'lodash') {
    return {
      type: 'empty',
    };
  }

  // Ensure you call the default resolver.
  return context.resolveRequest(context, moduleName, platform);
};

module.exports = config;

‍

By returning type: 'empty', Metro will essentially just ignore that entire codepath and you won't find it in your bundle anymore.

However, this isn't limited to just 'empty', you can also swap out the file that's used.

return {
   filePath: 'path-to-file-here',
   type: 'sourceFile',
};

‍

The implementation in Storybook

‍

In Storybook, we combine both the empty and sourceFile mocking to make sure we correctly remove Storybook fully when it’s disabled. We will return empty for anything in your .rnstorybook folder and replace .rnstorybook/index.tsx with a file that imports nothing and exports a component warning you that Storybook is disabled.

  if (!enabled) {
    return {
      ...config,
      resolver: {
        ...config.resolver,
        resolveRequest: (context: any, moduleName: string, platform: string | null) => {
          const resolveFunction: ResolveRequestFunction = config?.resolver?.resolveRequest
            ? config.resolver.resolveRequest
            : context.resolveRequest;

          const resolved = resolveFunction(context, moduleName, platform);

          if (resolved.filePath?.includes?.(`${configPath}/index.tsx`)) {
            return {
              filePath: path.resolve(__dirname, '../stub.js'),
              type: 'sourceFile',
            };
          }

          if (resolved.filePath?.includes?.(configPath)) {
            return { type: 'empty' };
          }

          return resolved;
        },
      },
    };
  }

‍

The reason why we specifically stub out the index file is that if you have this code and StorybookUI isn't a component, then it's going to crash.

import StorybookUI from './.rnstorybook';
export default function App() {
  return isStorybook ? <StorybookUI/> : <AppRoot />;
}

‍

Replacing  .rnstorybook/index.tsx with a placeholder component instead of treating it as an empty file makes sure that the app won’t crash. It also ensures that the Storybook code is still removed from the bundle since the placeholder component has no dependencies.

In conclusion

The process for swapping between Storybook and your app is much simpler than it used to be. With environment variables, Metro’s custom resolver options, and the new withStorybook helper, you can keep Storybook fully isolated from your production bundle while still making it easy to enable in development. Use this guide as a base and tailor the workflow to whatever suits your team best.

‍

Insights

Learn more about React Native

cover

Aug 4Podcast

VisionCamera V5 With Marc Rousavy

Marc Rousavy joins Mike Grabowski to unpack VisionCamera v5, Nitro Modules, the constraints API, migration work, and what changed for React Native camera apps.

cover

Jul 1Podcast

Redraw for Effects Beyond Skia

William Candillon talks about where Redraw fits next to Skia, from physics-based rendering to camera effects, AR, and new UI patterns.

cover

Jun 29Article

Less Boilerplate, More Type Safety: React Navigation 8's Typed Hooks

React Navigation 8 improves typed hooks with screen-aware types, less boilerplate, and fewer unsafe casts in shared UI and nested navigators.

cover

Apr 30Live Stream

Build a React Native App With the TanStack Stack

Join Callstack’s live stream on building a React Native app from the ground up using the TanStack toolbelt.

cover

Apr 28Article

React Native production lessons from React Universe Meetup x Zalando

Lessons from React Universe Meetup x Zalando on React Native in production, covering brownfield performance, feed video, native API access, and on-device AI.

cover

Apr 23Talk

Shipping iOS Live Activities with React: The Voltra Story

How Voltra enables Live Activities and Dynamic Island views using React without writing Swift. A deep dive into iOS constraints and architecture.

cover

Apr 16Live Stream

React Native 0.85: Animation Backend and Key Updates

A recap of React Native 0.85, covering the new animation backend, DevTools improvements, and ecosystem takeaways.

cover

Mar 5Article

Keeping Screens Visible With <Activity mode="hidden">

A cross‑platform workaround to keep screens visible while <Activity mode="hidden"> unmounts effects on inactive screens by setting mode="hidden".

cover

Feb 25Article

React Native Monorepo With pnpm Workspaces

Set up a React Native monorepo with pnpm workspaces for mobile and Next.js web, including Metro fixes, hoisted node-linker, and shared packages.

cover

Feb 18Article

A Practical Guide to React Native Monorepo With Yarn Workspaces

Learn how to set up a React Native monorepo with Yarn workspaces for mobile and web, including Metro, Gradle, and shared packages.

cover

Feb 17Podcast

From Teddy Bears to Voice Agents: Kraen Hansen on Voice AI, Local-First & App Security

What happens when you combine voice agents and teddy bears? A hands-on look at local-first systems, voice AI, and security lessons from poking real apps.

cover

Jan 28Article

Bringing CSS Clipping to React Native

A deep look at how a single CSS feature moves through React Native’s New Architecture, from JavaScript styles to native rendering on iOS and Android.

cover

Mar 19Tutorial

The Hard Way vs. The React Native AI SDK Way: Stop Writing Custom Modules for Every Model

Learn how React Native AI uses a unified provider model to switch between cloud and on-device LLMs without rewriting application logic, enabling reliable AI experiences online and offline.

cover

Mar 12Tutorial

Build Smarter Apps: Tool Calling & AI Orchestration Explained

Learn how on-device models in React Native can call tools, interact with external APIs, and return structured outputs you can use directly in application logic.

cover

Mar 5Tutorial

MLC LLM + React Native: On-Device AI Without the Pain

Learn how to run third-party on-device LLMs in React Native using MLC LLM. Choose your models, run them efficiently across platforms, and keep a unified JavaScript API with React Native AI.

cover

Feb 24Tutorial

Intelligent Fallbacks with Apple Intelligence in React Native

Learn how to use Apple’s built-in Foundation Models in React Native apps, reduce memory usage, and enable fast, fully on-device AI with React Native AI Apple.

cover

Feb 10Tutorial

What Is the React Native AI SDK? A Complete Intro & Quickstart

Learn why on-device AI matters for React Native apps, how local LLMs behave offline, and what problems React Native AI is designed to solve from day one.

cover

Jan 29Tutorial

Implementing an Android TurboModule with Kotlin

Learn how to implement a React Native TurboModule on Android, from the TypeScript spec and Codegen to the Kotlin implementation and package registration.

cover

Jan 19Tutorial

Working with Different Threads in Swift TurboModules

Learn how JavaScript, native module, background, and main threads interact in React Native TurboModules, and how to use GCD queues to run async work safely in Swift.

cover

Jan 9Tutorial

How to Add Type-Safe Constants to Swift TurboModules

Learn how to expose typed, immutable constants from a Swift TurboModule using Codegen, and get full end-to-end type safety between native and JavaScript.

cover

Dec 30Tutorial

Adding Event Emitters to Your TurboModule in Swift

Learn how to emit native events from a Swift TurboModule and subscribe to them in JavaScript, including proper memory management and Codegen integration.

cover

Dec 22Tutorial

Writing Your First TurboModule in Swift

Learn how to build a fully working TurboModule in Swift, integrate it with Codegen, and bridge it through Objective‑C inside an Expo app.