You can use environment variables in Storybook to change its behavior in different “modes”.
If you supply an environment variable prefixed with STORYBOOK_
, it will be available in process.env
:
Then we can access these environment variables anywhere inside our preview JavaScript code like below:
You can also access these variables in your custom <head>
/<body>
using the substitution %STORYBOOK_X%
, for example: %STORYBOOK_THEME%
will become red
.
💡 If using the environment variables as attributes or values in JavaScript, you may need to add quotes, as the value will be inserted directly. e.g. <link rel="stylesheet" href="%STORYBOOK_STYLE_URL%" />
Using .env files
You can also use .env
files to change Storybook's behavior in different modes. For example, if you add a .env
file to your project with the following:
Then you can access this environment variable anywhere, even within your stories:
.env.development
or .env.production
to apply different values to your environment variables.You can also pass these environment variables when you are building your Storybook with build-storybook
.
Then they'll be hardcoded to the static version of your Storybook.
Using Storybook configuration
Additionally, you can extend your Storybook configuration file (i.e., .storybook/main.js
) and provide a configuration field that you can use to define specific variables (e.g., API URLs). For example:
When Storybook loads, it will enable you to access them in your stories similar as you would do if you were working with an env
file:
Using environment variables to choose the browser
Storybook allows you to choose the browser you want to preview your stories. Either through a .env
file entry or directly in your storybook
script.
The table below lists the available options:
Browser | Example |
---|---|
Safari | BROWSER="safari" |
Firefox | BROWSER="firefox" |
Chromium | BROWSER="chromium" |