@storybook/nextjs 0.0.0-pr-23609-sha-f47ef339

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +981 -0
  2. package/dist/chunk-2SSJK7AW.mjs +5 -0
  3. package/dist/chunk-FFRTCGB4.mjs +3 -0
  4. package/dist/chunk-HAVEVISW.mjs +3 -0
  5. package/dist/font/webpack/loader/storybook-nextjs-font-loader.d.ts +3 -0
  6. package/dist/font/webpack/loader/storybook-nextjs-font-loader.js +48 -0
  7. package/dist/font/webpack/loader/storybook-nextjs-font-loader.mjs +55 -0
  8. package/dist/images/context.d.ts +13 -0
  9. package/dist/images/context.js +1 -0
  10. package/dist/images/context.mjs +2 -0
  11. package/dist/images/next-future-image.d.ts +6 -0
  12. package/dist/images/next-future-image.js +1 -0
  13. package/dist/images/next-future-image.mjs +9 -0
  14. package/dist/images/next-image.d.ts +6 -0
  15. package/dist/images/next-image.js +1 -0
  16. package/dist/images/next-image.mjs +9 -0
  17. package/dist/images/next-legacy-image.d.ts +6 -0
  18. package/dist/images/next-legacy-image.js +1 -0
  19. package/dist/images/next-legacy-image.mjs +9 -0
  20. package/dist/index.d-d29054be.d.ts +1203 -0
  21. package/dist/index.d.ts +28 -0
  22. package/dist/index.js +1 -0
  23. package/dist/index.mjs +1 -0
  24. package/dist/next-image-loader-stub.d.ts +10 -0
  25. package/dist/next-image-loader-stub.js +1 -0
  26. package/dist/next-image-loader-stub.mjs +7 -0
  27. package/dist/preset.d.ts +16 -0
  28. package/dist/preset.js +1 -0
  29. package/dist/preview.d.ts +15 -0
  30. package/dist/preview.js +1 -0
  31. package/dist/preview.mjs +12 -0
  32. package/jest.config.js +7 -0
  33. package/package.json +160 -0
  34. package/preset.js +1 -0
  35. package/src/globals.d.ts +3 -0
  36. package/template/cli/.eslintrc.json +7 -0
  37. package/template/cli/js/Button.jsx +54 -0
  38. package/template/cli/js/Button.stories.js +45 -0
  39. package/template/cli/js/Configure.mdx +446 -0
  40. package/template/cli/js/Header.jsx +59 -0
  41. package/template/cli/js/Header.stories.js +23 -0
  42. package/template/cli/js/Page.jsx +68 -0
  43. package/template/cli/js/Page.stories.js +24 -0
  44. package/template/cli/ts-3-8/Button.stories.ts +50 -0
  45. package/template/cli/ts-3-8/Button.tsx +52 -0
  46. package/template/cli/ts-3-8/Configure.mdx +446 -0
  47. package/template/cli/ts-3-8/Header.stories.ts +26 -0
  48. package/template/cli/ts-3-8/Header.tsx +56 -0
  49. package/template/cli/ts-3-8/Page.stories.ts +29 -0
  50. package/template/cli/ts-3-8/Page.tsx +73 -0
  51. package/template/cli/ts-4-9/Button.stories.ts +50 -0
  52. package/template/cli/ts-4-9/Button.tsx +52 -0
  53. package/template/cli/ts-4-9/Configure.mdx +446 -0
  54. package/template/cli/ts-4-9/Header.stories.ts +26 -0
  55. package/template/cli/ts-4-9/Header.tsx +56 -0
  56. package/template/cli/ts-4-9/Page.stories.ts +29 -0
  57. package/template/cli/ts-4-9/Page.tsx +73 -0
  58. package/template/next-env.d.ts +7 -0
  59. package/template/stories/DynamicImport.stories.jsx +20 -0
  60. package/template/stories/Image.stories.jsx +89 -0
  61. package/template/stories/StyledJsx.stories.jsx +20 -0
  62. package/template/stories/dynamic-component.js +5 -0
  63. package/template/stories_nextjs-12-js/ImageFuture.stories.jsx +55 -0
  64. package/template/stories_nextjs-12-js/Link.stories.jsx +28 -0
  65. package/template/stories_nextjs-default-js/Font.jsx +64 -0
  66. package/template/stories_nextjs-default-js/Font.stories.jsx +23 -0
  67. package/template/stories_nextjs-default-js/Head.stories.jsx +34 -0
  68. package/template/stories_nextjs-default-js/ImageLegacy.stories.jsx +36 -0
  69. package/template/stories_nextjs-default-js/Link.stories.jsx +82 -0
  70. package/template/stories_nextjs-default-js/Link.stories.module.css +3 -0
  71. package/template/stories_nextjs-default-js/Navigation.stories.jsx +124 -0
  72. package/template/stories_nextjs-default-js/Router.stories.jsx +69 -0
  73. package/template/stories_nextjs-default-js/fonts/OFL.txt +93 -0
  74. package/template/stories_nextjs-default-js/fonts/RubikStorm-Regular.ttf +0 -0
  75. package/template/stories_nextjs-default-ts/Link.stories.module.css +3 -0
  76. package/template/stories_nextjs-default-ts/Link.stories.tsx +85 -0
  77. package/template/stories_nextjs-default-ts/Navigation.stories.tsx +81 -0
package/README.md ADDED
@@ -0,0 +1,981 @@
1
+ # Storybook for Next.js <!-- omit in toc -->
2
+
3
+ ## Table of Contents <!-- omit in toc -->
4
+
5
+ - [Supported Features](#supported-features)
6
+ - [Requirements](#requirements)
7
+ - [Getting Started](#getting-started)
8
+ - [In a project without Storybook](#in-a-project-without-storybook)
9
+ - [In a project with Storybook](#in-a-project-with-storybook)
10
+ - [Automatic migration](#automatic-migration)
11
+ - [Manual migration](#manual-migration)
12
+ - [Documentation](#documentation)
13
+ - [Options](#options)
14
+ - [Next.js's Image Component](#nextjss-image-component)
15
+ - [Local Images](#local-images)
16
+ - [Remote Images](#remote-images)
17
+ - [AVIF](#avif)
18
+ - [Next.js Font Optimization](#nextjs-font-optimization)
19
+ - [next/font/google](#nextfontgoogle)
20
+ - [next/font/local](#nextfontlocal)
21
+ - [Not supported features of next/font](#not-supported-features-of-nextfont)
22
+ - [Next.js Routing](#nextjs-routing)
23
+ - [Overriding defaults](#overriding-defaults)
24
+ - [Global Defaults](#global-defaults)
25
+ - [Default Router](#default-router)
26
+ - [Actions Integration Caveats](#actions-integration-caveats)
27
+ - [Next.js Navigation](#nextjs-navigation)
28
+ - [Set `nextjs.appDirectory` to `true`](#set-nextjsappdirectory-to-true)
29
+ - [Overriding defaults](#overriding-defaults-1)
30
+ - [Global Defaults](#global-defaults-1)
31
+ - [`useSelectedLayoutSegment` `useSelectedLayoutSegments` and `useParams` hook](#useselectedlayoutsegment-useselectedlayoutsegments-and-useparams-hook)
32
+ - [Default Navigation Context](#default-navigation-context)
33
+ - [Actions Integration Caveats](#actions-integration-caveats-1)
34
+ - [Next.js Head](#nextjs-head)
35
+ - [Sass/Scss](#sassscss)
36
+ - [Css/Sass/Scss Modules](#csssassscss-modules)
37
+ - [Styled JSX](#styled-jsx)
38
+ - [Postcss](#postcss)
39
+ - [Absolute Imports](#absolute-imports)
40
+ - [Runtime Config](#runtime-config)
41
+ - [Custom Webpack Config](#custom-webpack-config)
42
+ - [Typescript](#typescript)
43
+ - [Notes for Yarn v2 and v3 users](#notes-for-yarn-v2-and-v3-users)
44
+ - [FAQ](#faq)
45
+ - [Stories for pages/components which fetch data](#stories-for-pagescomponents-which-fetch-data)
46
+ - [Statically imported images won't load](#statically-imported-images-wont-load)
47
+ - [Module not found: Error: Can't resolve `package name`](#module-not-found-error-cant-resolve-package-name)
48
+ - [What if I'm using the Vite builder?](#what-if-im-using-the-vite-builder)
49
+ - [Acknowledgements](#acknowledgements)
50
+
51
+ ## Supported Features
52
+
53
+ 👉 [Next.js's Image Component](#nextjss-image-component)
54
+
55
+ 👉 [Next.js Font Optimization](#nextjs-font-optimization)
56
+
57
+ 👉 [Next.js Routing (next/router)](#nextjs-routing)
58
+
59
+ 👉 [Next.js Head (next/head)](#nextjs-head)
60
+
61
+ 👉 [Next.js Navigation (next/navigation)](#nextjs-navigation)
62
+
63
+ 👉 [Sass/Scss](#sassscss)
64
+
65
+ 👉 [Css/Sass/Scss Modules](#csssassscss-modules)
66
+
67
+ 👉 [Styled JSX](#styled-jsx)
68
+
69
+ 👉 [Postcss](#postcss)
70
+
71
+ 👉 [Absolute Imports](#absolute-imports)
72
+
73
+ 👉 [Runtime Config](#runtime-config)
74
+
75
+ 👉 [Custom Webpack Config](#custom-webpack-config)
76
+
77
+ 👉 [Typescript](#typescript) (already supported out of the box by Storybook)
78
+
79
+ ## Requirements
80
+
81
+ - [Next.js](https://nextjs.org/) >= 12.x
82
+ - [Storybook](https://storybook.js.org/) >= 7.x
83
+
84
+ ## Getting Started
85
+
86
+ ### In a project without Storybook
87
+
88
+ Follow the prompts after running this command in your Next.js project's root directory:
89
+
90
+ ```bash
91
+ npx storybook@latest init
92
+ ```
93
+
94
+ [More on getting started with Storybook](https://storybook.js.org/docs/react/get-started/install)
95
+
96
+ ### In a project with Storybook
97
+
98
+ This framework is designed to work with Storybook 7. If you’re not already using v7, upgrade with this command:
99
+
100
+ ```bash
101
+ npx storybook@latest upgrade --prerelease
102
+ ```
103
+
104
+ #### Automatic migration
105
+
106
+ When running the `upgrade` command above, you should get a prompt asking you to migrate to `@storybook/nextjs`, which should handle everything for you. In case that auto-migration does not work for your project, refer to the manual migration below.
107
+
108
+ #### Manual migration
109
+
110
+ Install the framework:
111
+
112
+ ```bash
113
+ yarn add --dev @storybook/nextjs
114
+ ```
115
+
116
+ Update your `main.js` to change the framework property:
117
+
118
+ ```js
119
+ // .storybook/main.js
120
+ export default {
121
+ // ...
122
+ framework: {
123
+ // name: '@storybook/react-webpack5', // Remove this
124
+ name: '@storybook/nextjs', // Add this
125
+ options: {},
126
+ },
127
+ };
128
+ ```
129
+
130
+ If you were using Storybook plugins to integrate with Next.js, those are no longer necessary when using this framework and can be removed:
131
+
132
+ ```js
133
+ // .storybook/main.js
134
+ export default {
135
+ // ...
136
+ addons: [
137
+ // ...
138
+ // These can both be removed
139
+ // 'storybook-addon-next',
140
+ // 'storybook-addon-next-router',
141
+ ],
142
+ };
143
+ ```
144
+
145
+ ## Documentation
146
+
147
+ ### Options
148
+
149
+ You can be pass an options object for addional configuration if needed.
150
+
151
+ For example:
152
+
153
+ ```js
154
+ // .storybook/main.js
155
+ import * as path from 'path';
156
+
157
+ export default {
158
+ // ...
159
+ framework: {
160
+ name: '@storybook/nextjs',
161
+ options: {
162
+ image: {
163
+ loading: 'eager',
164
+ },
165
+ nextConfigPath: path.resolve(__dirname, '../next.config.js'),
166
+ },
167
+ },
168
+ };
169
+ ```
170
+
171
+ - `image`: Props to pass to every instance of `next/image`
172
+ - `nextConfigPath`: The absolute path to the `next.config.js`
173
+
174
+ ### Next.js's Image Component
175
+
176
+ [next/image](https://nextjs.org/docs/api-reference/next/image) is [notoriously difficult](https://github.com/vercel/next.js/issues/18393) to get working with Storybook. This framework allows you to use Next.js's `Image` component with no configuration!
177
+
178
+ #### Local Images
179
+
180
+ [Local images](https://nextjs.org/docs/basic-features/image-optimization#local-images) work just fine! Keep in mind that this feature was [only added in Next.js v11](https://nextjs.org/blog/next-11#automatic-size-detection-local-images).
181
+
182
+ ```js
183
+ import Image from 'next/image';
184
+ import profilePic from '../public/me.png';
185
+
186
+ function Home() {
187
+ return (
188
+ <>
189
+ <h1>My Homepage</h1>
190
+ <Image
191
+ src={profilePic}
192
+ alt="Picture of the author"
193
+ // width={500} automatically provided
194
+ // height={500} automatically provided
195
+ // blurDataURL="../public/me.png" set to equal the image itself (for this framework)
196
+ // placeholder="blur" // Optional blur-up while loading
197
+ />
198
+ <p>Welcome to my homepage!</p>
199
+ </>
200
+ );
201
+ }
202
+ ```
203
+
204
+ #### Remote Images
205
+
206
+ [Remote images](https://nextjs.org/docs/basic-features/image-optimization#remote-images) also work just fine!
207
+
208
+ ```js
209
+ import Image from 'next/image';
210
+
211
+ export default function Home() {
212
+ return (
213
+ <>
214
+ <h1>My Homepage</h1>
215
+ <Image src="/me.png" alt="Picture of the author" width={500} height={500} />
216
+ <p>Welcome to my homepage!</p>
217
+ </>
218
+ );
219
+ }
220
+ ```
221
+
222
+ #### AVIF
223
+
224
+ This format is not supported by this framework yet. Feel free to [open up an issue](https://github.com/storybookjs/storybook/issues) if this is something you want to see.
225
+
226
+ ### Next.js Font Optimization
227
+
228
+ [next/font](https://nextjs.org/docs/basic-features/font-optimization) is partially supported in Storybook. The packages `next/font/google` and `next/font/local` are supported.
229
+
230
+ #### next/font/google
231
+
232
+ You don't have to do anything. `next/font/google` is supported out of the box.
233
+
234
+ #### next/font/local
235
+
236
+ For local fonts you have to define the [src](https://nextjs.org/docs/api-reference/next/font#src) property.
237
+ The path is relative to the directory where the font loader function is called.
238
+
239
+ If the following component defines your localFont like this:
240
+
241
+ ```js
242
+ // src/components/MyComponent.js
243
+ import localFont from 'next/font/local';
244
+
245
+ const localRubikStorm = localFont({ src: './fonts/RubikStorm-Regular.ttf' });
246
+ ```
247
+
248
+ You have to tell Storybook where the `fonts` directory is located. The `from` value is relative to the `.storybook` directory. The `to` value is relative to the execution context of Storybook. Very likely it is the root of your project.
249
+
250
+ ```js
251
+ // .storybook/main.js
252
+ export default {
253
+ ...
254
+ "staticDirs": [
255
+ {
256
+ from: '../src/components/fonts',
257
+ to: 'src/components/fonts'
258
+ }
259
+ ],
260
+ }
261
+ ```
262
+
263
+ #### Not supported features of next/font
264
+
265
+ The following features are not supported (yet). Support for these features might be planned for the future:
266
+
267
+ - [Support font loaders configuration in next.config.js](https://nextjs.org/docs/basic-features/font-optimization#specifying-a-subset)
268
+ - [fallback](https://nextjs.org/docs/api-reference/next/font#fallback) option
269
+ - [adjustFontFallback](https://nextjs.org/docs/api-reference/next/font#adjustfontfallback) option
270
+ - [declarations](https://nextjs.org/docs/api-reference/next/font#declarations) option
271
+ - [preload](https://nextjs.org/docs/api-reference/next/font#preload) option gets ignored. Storybook handles Font loading its own way.
272
+ - [display](https://nextjs.org/docs/api-reference/next/font#display) option gets ignored. All fonts are loaded with display set to "block" to make Storybook load the font properly.
273
+
274
+ ### Next.js Routing
275
+
276
+ [Next.js's router](https://nextjs.org/docs/routing/introduction) is automatically stubbed for you so that when the router is interacted with, all of its interactions are automatically logged to the Actions ctions panel if you have the [Storybook actions addon](https://storybook.js.org/docs/react/essentials/actions).
277
+
278
+ > When using Next.js 13+, you should only use `next/router` in the `pages` directory. In the `app` directory, it is necessary to use `next/navigation`.
279
+
280
+ #### Overriding defaults
281
+
282
+ Per-story overrides can be done by adding a `nextjs.router` property onto the story [parameters](https://storybook.js.org/docs/react/writing-stories/parameters). The framework will shallowly merge whatever you put here into the router.
283
+
284
+ ```js
285
+ // SomeComponentThatUsesTheRouter.stories.js
286
+ import SomeComponentThatUsesTheRouter from './SomeComponentThatUsesTheRouter';
287
+
288
+ export default {
289
+ component: SomeComponentThatUsesTheRouter,
290
+ };
291
+
292
+ // If you have the actions addon,
293
+ // you can interact with the links and see the route change events there
294
+ export const Example = {
295
+ parameters: {
296
+ nextjs: {
297
+ router: {
298
+ path: '/profile/[id]',
299
+ asPath: '/profile/1',
300
+ query: {
301
+ id: '1',
302
+ },
303
+ },
304
+ },
305
+ },
306
+ };
307
+ ```
308
+
309
+ #### Global Defaults
310
+
311
+ Global defaults can be set in [preview.js](https://storybook.js.org/docs/react/configure/overview#configure-story-rendering) and will be shallowly merged with the default router.
312
+
313
+ ```js
314
+ // .storybook/preview.js
315
+
316
+ export const parameters = {
317
+ nextjs: {
318
+ router: {
319
+ path: '/some-default-path',
320
+ asPath: '/some-default-path',
321
+ query: {},
322
+ },
323
+ },
324
+ };
325
+ ```
326
+
327
+ #### Default Router
328
+
329
+ The default values on the stubbed router are as follows (see [globals](https://storybook.js.org/docs/react/essentials/toolbars-and-globals#globals) for more details on how globals work)
330
+
331
+ ```ts
332
+ const defaultRouter = {
333
+ push(...args) {
334
+ action('nextRouter.push')(...args);
335
+ return Promise.resolve(true);
336
+ },
337
+ replace(...args) {
338
+ action('nextRouter.replace')(...args);
339
+ return Promise.resolve(true);
340
+ },
341
+ reload(...args) {
342
+ action('nextRouter.reload')(...args);
343
+ },
344
+ back(...args) {
345
+ action('nextRouter.back')(...args);
346
+ },
347
+ forward() {
348
+ action('nextRouter.forward')();
349
+ },
350
+ prefetch(...args) {
351
+ action('nextRouter.prefetch')(...args);
352
+ return Promise.resolve();
353
+ },
354
+ beforePopState(...args) {
355
+ action('nextRouter.beforePopState')(...args);
356
+ },
357
+ events: {
358
+ on(...args) {
359
+ action('nextRouter.events.on')(...args);
360
+ },
361
+ off(...args) {
362
+ action('nextRouter.events.off')(...args);
363
+ },
364
+ emit(...args) {
365
+ action('nextRouter.events.emit')(...args);
366
+ },
367
+ },
368
+ // The locale should be configured [globally](https://storybook.js.org/docs/react/essentials/toolbars-and-globals#globals)
369
+ locale: globals?.locale,
370
+ asPath: '/',
371
+ basePath: '/',
372
+ isFallback: false,
373
+ isLocaleDomain: false,
374
+ isReady: true,
375
+ isPreview: false,
376
+ route: '/',
377
+ pathname: '/',
378
+ query: {},
379
+ };
380
+ ```
381
+
382
+ #### Actions Integration Caveats
383
+
384
+ If you override a function, you lose the automatic actions integration and have to build it out yourself.
385
+
386
+ ```js
387
+ // .storybook/preview.js
388
+
389
+ export const parameters = {
390
+ nextjs: {
391
+ router: {
392
+ push() {
393
+ // The default implementation that logs the action into the Actions panel is lost
394
+ },
395
+ },
396
+ },
397
+ };
398
+ ```
399
+
400
+ Doing this yourself looks something like this (make sure you install the `@storybook/addon-actions` package):
401
+
402
+ ```js
403
+ // .storybook/preview.js
404
+ import { action } from '@storybook/addon-actions';
405
+
406
+ export const parameters = {
407
+ nextjs: {
408
+ router: {
409
+ push(...args) {
410
+ // Custom logic can go here
411
+ // This logs to the Actions panel
412
+ action('nextRouter.push')(...args);
413
+ // Return whatever you want here
414
+ return Promise.resolve(true);
415
+ },
416
+ },
417
+ },
418
+ };
419
+ ```
420
+
421
+ ### Next.js Navigation
422
+
423
+ > Please note that [next/navigation](https://beta.nextjs.org/docs/upgrade-guide#step-5-migrating-routing-hooks) can only be used in components/pages in the `app` directory of Next.js 13+.
424
+
425
+ #### Set `nextjs.appDirectory` to `true`
426
+
427
+ If your story imports components that use `next/navigation`, you need to set the parameter `nextjs.appDirectory` to `true` in your Story:
428
+
429
+ ```js
430
+ // SomeComponentThatUsesTheRouter.stories.js
431
+ import SomeComponentThatUsesTheNavigation from './SomeComponentThatUsesTheNavigation';
432
+
433
+ export default {
434
+ component: SomeComponentThatUsesTheNavigation,
435
+ };
436
+
437
+ export const Example = {
438
+ parameters: {
439
+ nextjs: {
440
+ appDirectory: true,
441
+ },
442
+ },
443
+ },
444
+ ```
445
+
446
+ If your Next.js project uses the `app` directory for every page (in other words, it does not have a `pages` directory), you can set the parameter `nextjs.appDirectory` to `true` in the [preview.js](https://storybook.js.org/docs/react/configure/overview#configure-story-rendering) file to apply it to all stories.
447
+
448
+ ```js
449
+ // .storybook/preview.js
450
+
451
+ export const parameters = {
452
+ nextjs: {
453
+ appDirectory: true,
454
+ },
455
+ };
456
+ ```
457
+
458
+ The parameter `nextjs.appDirectory` defaults to `false` if not set.
459
+
460
+ #### Overriding defaults
461
+
462
+ Per-story overrides can be done by adding a `nextjs.navigation` property onto the story [parameters](https://storybook.js.org/docs/react/writing-stories/parameters). The framework will shallowly merge whatever you put here into the router.
463
+
464
+ ```js
465
+ // SomeComponentThatUsesTheNavigation.stories.js
466
+ import SomeComponentThatUsesTheNavigation from './SomeComponentThatUsesTheNavigation';
467
+
468
+ export default {
469
+ component: SomeComponentThatUsesTheNavigation,
470
+ };
471
+
472
+ // If you have the actions addon,
473
+ // you can interact with the links and see the route change events there
474
+ export const Example = {
475
+ parameters: {
476
+ nextjs: {
477
+ appDirectory: true,
478
+ navigation: {
479
+ pathname: '/profile',
480
+ query: {
481
+ user: '1',
482
+ },
483
+ },
484
+ },
485
+ },
486
+ };
487
+ ```
488
+
489
+ #### Global Defaults
490
+
491
+ Global defaults can be set in [preview.js](https://storybook.js.org/docs/react/configure/overview#configure-story-rendering) and will be shallowly merged with the default router.
492
+
493
+ ```js
494
+ // .storybook/preview.js
495
+
496
+ export const parameters = {
497
+ nextjs: {
498
+ appDirectory: true,
499
+ navigation: {
500
+ pathname: '/some-default-path',
501
+ },
502
+ },
503
+ };
504
+ ```
505
+
506
+ #### `useSelectedLayoutSegment` `useSelectedLayoutSegments` and `useParams` hook
507
+
508
+ The `useSelectedLayoutSegment` `useSelectedLayoutSegments` and `useParams` hooks are supported in Storybook. You have to set the `nextjs.navigation.segments` parameter to return the segments or the params you want to use.
509
+
510
+ ```js
511
+ // SomeComponentThatUsesTheNavigation.stories.js
512
+ import SomeComponentThatUsesTheNavigation from './SomeComponentThatUsesTheNavigation';
513
+
514
+ export default {
515
+ component: SomeComponentThatUsesTheNavigation,
516
+ parameters: {
517
+ nextjs: {
518
+ appDirectory: true,
519
+ navigation: {
520
+ segments: ['dashboard', 'analytics']
521
+ },
522
+ },
523
+ },
524
+ };
525
+
526
+ export const Example = {};
527
+
528
+ // SomeComponentThatUsesTheNavigation.js
529
+ import { useSelectedLayoutSegment, useSelectedLayoutSegments, useParams } from 'next/navigation';
530
+
531
+ export default function SomeComponentThatUsesTheNavigation() {
532
+ const segment = useSelectedLayoutSegment(); // dashboard
533
+ const segments = useSelectedLayoutSegments(); // ["dashboard", "analytics"]
534
+ const params = useParams(); // {}
535
+ ...
536
+ }
537
+ ```
538
+
539
+ To use `useParams`, you have to use a two string elements array for a segment, the first array element is the param key and the second array element is the param value.
540
+
541
+ ```js
542
+ // SomeComponentThatUsesParams.stories.js
543
+ import SomeComponentThatUsesParams from './SomeComponentThatUsesParams';
544
+
545
+ export default {
546
+ component: SomeComponentThatUsesParams,
547
+ parameters: {
548
+ nextjs: {
549
+ appDirectory: true,
550
+ navigation: {
551
+ segments: [
552
+ ['slug', 'hello'],
553
+ ['framework', 'nextjs'],
554
+ ]
555
+ },
556
+ },
557
+ },
558
+ };
559
+
560
+ export const Example = {};
561
+
562
+ // SomeComponentThatUsesParams.js
563
+ import { useSelectedLayoutSegment, useSelectedLayoutSegments, useParams } from 'next/navigation';
564
+
565
+ export default function SomeComponentThatUsesParams() {
566
+ const segment = useSelectedLayoutSegment(); // hello
567
+ const segments = useSelectedLayoutSegments(); // ["hello", "nextjs"]
568
+ const params = useParams(); // { slug: "hello", framework: "nextjs" }
569
+ ...
570
+ }
571
+ ```
572
+
573
+ The default value of `nextjs.navigation.segments` is `[]` if not set.
574
+
575
+ #### Default Navigation Context
576
+
577
+ The default values on the stubbed navigation context are as follows:
578
+
579
+ ```ts
580
+ const defaultNavigationContext = {
581
+ push(...args) {
582
+ action('nextNavigation.push')(...args);
583
+ },
584
+ replace(...args) {
585
+ action('nextNavigation.replace')(...args);
586
+ },
587
+ forward(...args) {
588
+ action('nextNavigation.forward')(...args);
589
+ },
590
+ back(...args) {
591
+ action('nextNavigation.back')(...args);
592
+ },
593
+ prefetch(...args) {
594
+ action('nextNavigation.prefetch')(...args);
595
+ },
596
+ refresh: () => {
597
+ action('nextNavigation.refresh')();
598
+ },
599
+ pathname: '/',
600
+ query: {},
601
+ };
602
+ ```
603
+
604
+ #### Actions Integration Caveats
605
+
606
+ If you override a function, you lose the automatic action tab integration and have to build it out yourself.
607
+
608
+ ```js
609
+ // .storybook/preview.js
610
+
611
+ export const parameters = {
612
+ nextjs: {
613
+ appDirectory: true,
614
+ navigation: {
615
+ push() {
616
+ // The default implementation that logs the action into the Actions panel is lost
617
+ },
618
+ },
619
+ },
620
+ };
621
+ ```
622
+
623
+ Doing this yourself looks something like this (make sure you install the `@storybook/addon-actions` package):
624
+
625
+ ```js
626
+ // .storybook/preview.js
627
+ import { action } from '@storybook/addon-actions';
628
+
629
+ export const parameters = {
630
+ nextjs: {
631
+ appDirectory: true,
632
+ navigation: {
633
+ push(...args) {
634
+ // Custom logic can go here
635
+ // This logs to the Actions panel
636
+ action('nextNavigation.push')(...args);
637
+ // Return whatever you want here
638
+ return Promise.resolve(true);
639
+ },
640
+ },
641
+ },
642
+ };
643
+ ```
644
+
645
+ ### Next.js Head
646
+
647
+ [next/head](https://nextjs.org/docs/api-reference/next/head) is supported out of the box. You can use it in your stories like you would in your Next.js application. Please keep in mind, that the Head children are placed into the head element of the iframe that Storybook uses to render your stories.
648
+
649
+ ### Sass/Scss
650
+
651
+ [Global sass/scss stylesheets](https://nextjs.org/docs/basic-features/built-in-css-support#sass-support) are supported without any additional configuration as well. Just import them into [preview.js](https://storybook.js.org/docs/react/configure/overview#configure-story-rendering)
652
+
653
+ ```js
654
+ import '../styles/globals.scss';
655
+ ```
656
+
657
+ This will automatically include any of your [custom sass configurations](https://nextjs.org/docs/basic-features/built-in-css-support#customizing-sass-options) in your `next.config.js` file.
658
+
659
+ ```js
660
+ // next.config.js
661
+ import * as path from 'path';
662
+
663
+ export default {
664
+ // Any options here are included in Sass compilation for your stories
665
+ sassOptions: {
666
+ includePaths: [path.join(__dirname, 'styles')],
667
+ },
668
+ };
669
+ ```
670
+
671
+ ### Css/Sass/Scss Modules
672
+
673
+ [css modules](https://nextjs.org/docs/basic-features/built-in-css-support#adding-component-level-css) work as expected.
674
+
675
+ ```js
676
+ // This import works just fine in Storybook now
677
+ import styles from './Button.module.css';
678
+ // sass/scss is also supported
679
+ // import styles from './Button.module.scss'
680
+ // import styles from './Button.module.sass'
681
+
682
+ export function Button() {
683
+ return (
684
+ <button type="button" className={styles.error}>
685
+ Destroy
686
+ </button>
687
+ );
688
+ }
689
+ ```
690
+
691
+ ### Styled JSX
692
+
693
+ The built in CSS-in-JS solution for Next.js is [styled-jsx](https://nextjs.org/docs/basic-features/built-in-css-support#css-in-js), and this framework supports that out of the box too, zero config.
694
+
695
+ ```js
696
+ // This works just fine in Storybook now
697
+ function HelloWorld() {
698
+ return (
699
+ <div>
700
+ Hello world
701
+ <p>scoped!</p>
702
+ <style jsx>{`
703
+ p {
704
+ color: blue;
705
+ }
706
+ div {
707
+ background: red;
708
+ }
709
+ @media (max-width: 600px) {
710
+ div {
711
+ background: blue;
712
+ }
713
+ }
714
+ `}</style>
715
+ <style global jsx>{`
716
+ body {
717
+ background: black;
718
+ }
719
+ `}</style>
720
+ </div>
721
+ );
722
+ }
723
+
724
+ export default HelloWorld;
725
+ ```
726
+
727
+ You can use your own babel config too. This is an example of how you can customize styled-jsx.
728
+
729
+ ```json
730
+ // .babelrc or whatever config file you use
731
+ {
732
+ "presets": [
733
+ [
734
+ "next/babel",
735
+ {
736
+ "styled-jsx": {
737
+ "plugins": ["@styled-jsx/plugin-sass"]
738
+ }
739
+ }
740
+ ]
741
+ ]
742
+ }
743
+ ```
744
+
745
+ ### Postcss
746
+
747
+ Next.js lets you [customize postcss config](https://nextjs.org/docs/advanced-features/customizing-postcss-config#default-behavior). Thus this framework will automatically handle your postcss config for you.
748
+
749
+ This allows for cool things like zero config tailwindcss! (See [Next.js' example](https://github.com/vercel/next.js/tree/canary/examples/with-tailwindcss))
750
+
751
+ ### Absolute Imports
752
+
753
+ Goodbye `../`! Absolute imports from the root directory work just fine.
754
+
755
+ ```js
756
+ // All good!
757
+ import Button from 'components/button';
758
+ // Also good!
759
+ import styles from 'styles/HomePage.module.css';
760
+
761
+ export default function HomePage() {
762
+ return (
763
+ <>
764
+ <h1 className={styles.title}>Hello World</h1>
765
+ <Button />
766
+ </>
767
+ );
768
+ }
769
+ ```
770
+
771
+ Also OK for global styles in `preview.js`!
772
+
773
+ ```js
774
+ // .storybook/preview.js
775
+
776
+ import 'styles/globals.scss';
777
+
778
+ // ...
779
+ ```
780
+
781
+ ### Runtime Config
782
+
783
+ Next.js allows for [Runtime Configuration](https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration) which lets you import a handy `getConfig` function to get certain configuration defined in your `next.config.js` file at runtime.
784
+
785
+ In the context of Storybook with this framework, you can expect Next.js's [Runtime Configuration](https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration) feature to work just fine.
786
+
787
+ Note, because Storybook doesn't server render your components, your components will only see what they normally see on the client side (i.e. they won't see `serverRuntimeConfig` but will see `publicRuntimeConfig`).
788
+
789
+ For example, consider the following Next.js config:
790
+
791
+ ```js
792
+ // next.config.js
793
+ module.exports = {
794
+ serverRuntimeConfig: {
795
+ mySecret: 'secret',
796
+ secondSecret: process.env.SECOND_SECRET, // Pass through env variables
797
+ },
798
+ publicRuntimeConfig: {
799
+ staticFolder: '/static',
800
+ },
801
+ };
802
+ ```
803
+
804
+ Calls to `getConfig` would return the following object when called within Storybook:
805
+
806
+ ```json
807
+ {
808
+ "serverRuntimeConfig": {},
809
+ "publicRuntimeConfig": {
810
+ "staticFolder": "/static"
811
+ }
812
+ }
813
+ ```
814
+
815
+ ### Custom Webpack Config
816
+
817
+ Next.js comes with a lot of things for free out of the box like sass support, but sometimes you add [custom webpack config modifications to Next.js](https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config). This framework takes care of most of the webpack modifications you would want to add. If Next.js supports a feature out of the box, then that feature will work out of the box in Storybook. If Next.js doesn't support something out of the box, but makes it easy to configure, then this framework will do the same for that thing for Storybook.
818
+
819
+ Any webpack modifications desired for Storybook should be made in [.storybook/main.js](https://storybook.js.org/docs/react/builders/webpack#extending-storybooks-webpack-config).
820
+
821
+ Note: Not all webpack modifications are copy/paste-able between `next.config.js` and `.storybook/main.js`. It is recommended to do your reasearch on how to properly make your modifcation to Storybook's webpack config and on how [webpack works](https://webpack.js.org/concepts/).
822
+
823
+ Below is an example of how to add svgr support to Storybook with this framework.
824
+
825
+ ```js
826
+ // .storybook/main.js
827
+ export default {
828
+ // ...
829
+ webpackFinal: async (config) => {
830
+ // This modifies the existing image rule to exclude .svg files
831
+ // since you want to handle those files with @svgr/webpack
832
+ const imageRule = config.module.rules.find((rule) => rule.test.test('.svg'));
833
+ imageRule.exclude = /\.svg$/;
834
+
835
+ // Configure .svg files to be loaded with @svgr/webpack
836
+ config.module.rules.push({
837
+ test: /\.svg$/,
838
+ use: ['@svgr/webpack'],
839
+ });
840
+
841
+ return config;
842
+ },
843
+ };
844
+ ```
845
+
846
+ ### Typescript
847
+
848
+ Storybook handles most [Typescript](https://www.typescriptlang.org/) configurations, but this framework adds additional support for Next.js's support for [Absolute Imports and Module path aliases](https://nextjs.org/docs/advanced-features/module-path-aliases). In short, it takes into account your `tsconfig.json`'s [baseUrl](https://www.typescriptlang.org/tsconfig#baseUrl) and [paths](https://www.typescriptlang.org/tsconfig#paths). Thus, a `tsconfig.json` like the one below would work out of the box.
849
+
850
+ ```json
851
+ {
852
+ "compilerOptions": {
853
+ "baseUrl": ".",
854
+ "paths": {
855
+ "@/components/*": ["components/*"]
856
+ }
857
+ }
858
+ }
859
+ ```
860
+
861
+ ### Notes for Yarn v2 and v3 users
862
+
863
+ If you're using [Yarn](https://yarnpkg.com/) v2 or v3, you may run into issues where Storybook can't resolve `style-loader` or `css-loader`. For example, you might get errors like:
864
+
865
+ `Module not found: Error: Can't resolve 'css-loader'`\
866
+ `Module not found: Error: Can't resolve 'style-loader'`
867
+
868
+ This is because those versions of Yarn have different package resolution rules than Yarn v1.x. If this is the case for you, just install the package directly.
869
+
870
+ ### FAQ
871
+
872
+ #### Stories for pages/components which fetch data
873
+
874
+ Next.js page files can contain imports to modules meant to run in a node environment (for use in data fetching functions). If you import from a Next.js page file containing those node module imports in your stories, your Storybook's Webpack will crash because those modules will not run in a browser. To get around this, you can extract the component in your page file into a separate file and import that pure component in your stories. Or, if that's not feasible for some reason, you can [polyfill those modules](https://webpack.js.org/configuration/node/) in your Storybook's [`webpackFinal` configuration](https://storybook.js.org/docs/react/builders/webpack#extending-storybooks-webpack-config).
875
+
876
+ **Before**
877
+
878
+ ```jsx
879
+ // ./pages/my-page.jsx
880
+ import fs from 'fs';
881
+
882
+ // Using this component in your stories will break the Storybook build
883
+ export default function Page(props) {
884
+ return; // ...
885
+ }
886
+
887
+ export const getStaticProps = async () => {
888
+ // Logic that uses `fs`
889
+ };
890
+ ```
891
+
892
+ **After**
893
+
894
+ ```jsx
895
+ // ./pages/my-page.jsx
896
+ import fs from 'fs';
897
+
898
+ // Use this pure component in your stories instead
899
+ import MyPage from 'components/MyPage';
900
+
901
+ export default function Page(props) {
902
+ return <MyPage {...props} />;
903
+ }
904
+
905
+ export const getStaticProps = async () => {
906
+ // Logic that uses `fs`
907
+ };
908
+ ```
909
+
910
+ Starting with Next.js 13, you can also fetch data directly within server components in the `app` directory. This does not (currently) work within Storybook for similar reasons as above. It can be worked around similarly as well, by extracting a pure component to a separate file and importing that component in your stories.
911
+
912
+ **Before**
913
+
914
+ ```jsx
915
+ // ./app/my-page/index.jsx
916
+ async function getData() {
917
+ const res = await fetch(...);
918
+ // ...
919
+ }
920
+
921
+ // Using this component in your stories will break the Storybook build
922
+ export default async function Page() {
923
+ const data = await getData();
924
+
925
+ return // ...
926
+ }
927
+ ```
928
+
929
+ **After**
930
+
931
+ ```jsx
932
+ // ./app/my-page/index.jsx
933
+
934
+ // Use this component in your stories
935
+ import MyPage from './components/MyPage';
936
+
937
+ async function getData() {
938
+ const res = await fetch(...);
939
+ // ...
940
+ }
941
+
942
+ export default async function Page() {
943
+ const data = await getData();
944
+
945
+ return <MyPage {...data} />;
946
+ }
947
+ ```
948
+
949
+ #### Statically imported images won't load
950
+
951
+ Make sure you are treating image imports the same way you treat them when using `next/image` in normal development.
952
+
953
+ Before using this framework, image imports just imported the raw path to the image (e.g. `'static/media/stories/assets/logo.svg'`). Now image imports work the "Next.js way", meaning that you now get an object when importing an image. For example:
954
+
955
+ ```json
956
+ {
957
+ "src": "static/media/stories/assets/logo.svg",
958
+ "height": 48,
959
+ "width": 48,
960
+ "blurDataURL": "static/media/stories/assets/logo.svg"
961
+ }
962
+ ```
963
+
964
+ Therefore, if something in storybook isn't showing the image properly, make sure you expect the object to be returned from an import instead of just the asset path.
965
+
966
+ See [local images](https://nextjs.org/docs/basic-features/image-optimization#local-images) for more detail on how Next.js treats static image imports.
967
+
968
+ #### Module not found: Error: Can't resolve `package name`
969
+
970
+ You might get this if you're using Yarn v2 or v3. See [Notes for Yarn v2 and v3 users](#notes-for-yarn-v2-and-v3-users) for more details.
971
+
972
+ #### What if I'm using the Vite builder?
973
+
974
+ The `@storybook/nextjs` package abstracts the Webpack 5 builder and provides all the necessary Webpack configuration needed (and used internally) by Next.js. Webpack is currently the official builder in Next.js, and Next.js does not support Vite, therefore it is not possible to use Vite with `@storybook/nextjs`. You can use `@storybook/react-vite` framework instead, but at the cost of having a degraded experience, and we won't be able to provide you official support.
975
+
976
+ ## Acknowledgements
977
+
978
+ This framework borrows heavily from these Storybook addons:
979
+
980
+ - [storybook-addon-next](https://github.com/RyanClementsHax/storybook-addon-next) by [RyanClementsHax](https://github.com/RyanClementsHax/)
981
+ - [storybook-addon-next-router](https://github.com/lifeiscontent/storybook-addon-next-router) by [lifeiscontent](https://github.com/lifeiscontent)