@scenarist/nextjs-adapter 0.0.1 → 0.1.1

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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1450 -27
  3. package/dist/app/context.d.ts +19 -0
  4. package/dist/app/context.d.ts.map +1 -0
  5. package/dist/app/context.js +43 -0
  6. package/dist/app/endpoints.d.ts +20 -0
  7. package/dist/app/endpoints.d.ts.map +1 -0
  8. package/dist/app/endpoints.js +84 -0
  9. package/dist/app/helpers.d.ts +152 -0
  10. package/dist/app/helpers.d.ts.map +1 -0
  11. package/dist/app/helpers.js +173 -0
  12. package/dist/app/impl.d.ts +155 -0
  13. package/dist/app/impl.d.ts.map +1 -0
  14. package/dist/app/impl.js +97 -0
  15. package/dist/app/index.d.ts +40 -0
  16. package/dist/app/index.d.ts.map +1 -0
  17. package/dist/app/index.js +38 -0
  18. package/dist/app/production.d.ts +34 -0
  19. package/dist/app/production.d.ts.map +1 -0
  20. package/dist/app/production.js +38 -0
  21. package/dist/app/production.test.d.ts +100 -0
  22. package/dist/app/production.test.d.ts.map +1 -0
  23. package/dist/app/production.test.js +282 -0
  24. package/dist/app/setup.d.ts +29 -0
  25. package/dist/app/setup.d.ts.map +1 -0
  26. package/dist/app/setup.js +27 -0
  27. package/dist/common/create-scenarist-base.d.ts +32 -0
  28. package/dist/common/create-scenarist-base.d.ts.map +1 -0
  29. package/dist/common/create-scenarist-base.js +63 -0
  30. package/dist/common/endpoint-handlers.d.ts +99 -0
  31. package/dist/common/endpoint-handlers.d.ts.map +1 -0
  32. package/dist/common/endpoint-handlers.js +122 -0
  33. package/dist/pages/context.d.ts +17 -0
  34. package/dist/pages/context.d.ts.map +1 -0
  35. package/dist/pages/context.js +41 -0
  36. package/dist/pages/endpoints.d.ts +20 -0
  37. package/dist/pages/endpoints.d.ts.map +1 -0
  38. package/dist/pages/endpoints.js +84 -0
  39. package/dist/pages/helpers.d.ts +56 -0
  40. package/dist/pages/helpers.d.ts.map +1 -0
  41. package/dist/pages/helpers.js +49 -0
  42. package/dist/pages/impl.d.ts +124 -0
  43. package/dist/pages/impl.d.ts.map +1 -0
  44. package/dist/pages/impl.js +91 -0
  45. package/dist/pages/index.d.ts +37 -0
  46. package/dist/pages/index.d.ts.map +1 -0
  47. package/dist/pages/index.js +35 -0
  48. package/dist/pages/production.d.ts +18 -0
  49. package/dist/pages/production.d.ts.map +1 -0
  50. package/dist/pages/production.js +20 -0
  51. package/dist/pages/production.test.d.ts +119 -0
  52. package/dist/pages/production.test.d.ts.map +1 -0
  53. package/dist/pages/production.test.js +326 -0
  54. package/dist/pages/setup.d.ts +29 -0
  55. package/dist/pages/setup.d.ts.map +1 -0
  56. package/dist/pages/setup.js +27 -0
  57. package/package.json +86 -7
package/README.md CHANGED
@@ -1,45 +1,1468 @@
1
1
  # @scenarist/nextjs-adapter
2
2
 
3
- ## ⚠️ IMPORTANT NOTICE ⚠️
3
+ [![npm version](https://img.shields.io/npm/v/@scenarist/nextjs-adapter.svg)](https://www.npmjs.com/package/@scenarist/nextjs-adapter)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
5
 
5
- **This package is created solely for the purpose of setting up OIDC (OpenID Connect) trusted publishing with npm.**
6
+ Next.js adapter for [Scenarist](https://scenarist.io) - test different backend states in your Next.js applications without restarting your dev server or maintaining multiple test environments.
6
7
 
7
- This is **NOT** a functional package and contains **NO** code or functionality beyond the OIDC setup configuration.
8
+ **Problem it solves:** Testing error scenarios, loading states, and edge cases in Next.js is painful. You either restart your app repeatedly, maintain complex mock setups per test, or run tests serially to avoid conflicts. Scenarist lets you switch between complete API scenarios instantly via HTTP calls, enabling parallel testing with isolated backend states.
8
9
 
9
- ## Purpose
10
+ ## What is this?
10
11
 
11
- This package exists to:
12
- 1. Configure OIDC trusted publishing for the package name `@scenarist/nextjs-adapter`
13
- 2. Enable secure, token-less publishing from CI/CD workflows
14
- 3. Establish provenance for packages published under this name
12
+ **Before Scenarist:**
13
+ ```typescript
14
+ // Every test has fragile per-test mocking
15
+ beforeEach(() => {
16
+ server.use(
17
+ http.get('/api/user', () => HttpResponse.json({ role: 'admin' }))
18
+ );
19
+ });
20
+ // Repeat 100 times across test files, hope they don't conflict
21
+ ```
15
22
 
16
- ## What is OIDC Trusted Publishing?
23
+ **With Scenarist:**
24
+ ```typescript
25
+ // Define scenario once
26
+ const adminScenario = { id: 'admin', mocks: [/* complete backend state */] };
17
27
 
18
- OIDC trusted publishing allows package maintainers to publish packages directly from their CI/CD workflows without needing to manage npm access tokens. Instead, it uses OpenID Connect to establish trust between the CI/CD provider (like GitHub Actions) and npm.
28
+ // Use in any test with one line
29
+ await setScenario('test-1', 'admin');
30
+ // Test runs with complete "admin" backend state, isolated from other tests
31
+ ```
19
32
 
20
- ## Setup Instructions
33
+ This package provides complete Next.js integration for Scenarist's scenario management system, supporting both Pages Router and App Router:
21
34
 
22
- To properly configure OIDC trusted publishing for this package:
35
+ - **Runtime scenario switching** via HTTP endpoints - no restarts needed
36
+ - **Test isolation** using unique test IDs - run tests in parallel
37
+ - **Automatic MSW integration** for request interception - no MSW setup required
38
+ - **Zero boilerplate** - everything wired automatically with one function call
39
+ - **Both routers supported** - Pages Router and App Router with identical functionality
23
40
 
24
- 1. Go to [npmjs.com](https://www.npmjs.com/) and navigate to your package settings
25
- 2. Configure the trusted publisher (e.g., GitHub Actions)
26
- 3. Specify the repository and workflow that should be allowed to publish
27
- 4. Use the configured workflow to publish your actual package
41
+ ## Quick Navigation
28
42
 
29
- ## DO NOT USE THIS PACKAGE
43
+ | I want to... | Go to |
44
+ |-------------|--------|
45
+ | See what problems this solves | [What is this?](#what-is-this) |
46
+ | Get started in 5 minutes | [Quick Start (5 Minutes)](#quick-start-5-minutes) |
47
+ | Choose between routers | [Pages Router vs App Router](#pages-router-vs-app-router) |
48
+ | Set up Pages Router | [Pages Router Setup](#pages-router-setup) |
49
+ | Set up App Router | [App Router Setup](#app-router-setup) |
50
+ | Switch scenarios in tests | [Use in Tests](#4-use-in-tests) |
51
+ | Forward headers to external APIs | [Making External API Calls](#making-external-api-calls) |
52
+ | Understand test isolation | [Test ID Isolation](#test-id-isolation) |
53
+ | Reduce test boilerplate | [Common Patterns](#common-patterns) |
54
+ | Debug issues | [Troubleshooting](#troubleshooting) |
55
+ | See full API reference | [API Reference](#api-reference) |
56
+ | Learn about advanced features | [Core Functionality Docs](../../docs/core-functionality.md) |
30
57
 
31
- This package is a placeholder for OIDC configuration only. It:
32
- - Contains no executable code
33
- - Provides no functionality
34
- - Should not be installed as a dependency
35
- - Exists only for administrative purposes
58
+ ## Core Capabilities
36
59
 
37
- ## More Information
60
+ Scenarist provides 20+ powerful features for E2E testing. All capabilities work with Next.js (both Pages Router and App Router).
38
61
 
39
- For more details about npm's trusted publishing feature, see:
40
- - [npm Trusted Publishing Documentation](https://docs.npmjs.com/generating-provenance-statements)
41
- - [GitHub Actions OIDC Documentation](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connect)
62
+ ### Request Matching (6 capabilities)
63
+
64
+ **Body matching (partial match)** - Match requests based on request body fields
65
+ ```typescript
66
+ {
67
+ method: 'POST',
68
+ url: '/api/items',
69
+ match: { body: { itemId: 'premium-item' } },
70
+ response: { status: 200, body: { price: 100 } }
71
+ }
72
+ ```
73
+
74
+ **Header matching (exact match)** - Perfect for user tier testing
75
+ ```typescript
76
+ {
77
+ method: 'GET',
78
+ url: '/api/data',
79
+ match: { headers: { 'x-user-tier': 'premium' } },
80
+ response: { status: 200, body: { limit: 1000 } }
81
+ }
82
+ ```
83
+
84
+ **Query parameter matching** - Different responses for filtered requests
85
+ **Combined matching** - Combine body + headers + query (all must pass)
86
+ **Specificity-based selection** - Most specific mock wins (no need to order carefully)
87
+ **Fallback mocks** - Mocks without match criteria act as catch-all
88
+
89
+ ### Response Sequences (4 capabilities)
90
+
91
+ **Single responses** - Return same response every time
92
+ **Response sequences (ordered)** - Perfect for polling APIs
93
+ ```typescript
94
+ {
95
+ method: 'GET',
96
+ url: '/api/job/:id',
97
+ sequence: {
98
+ responses: [
99
+ { status: 200, body: { status: 'pending' } },
100
+ { status: 200, body: { status: 'processing' } },
101
+ { status: 200, body: { status: 'complete' } }
102
+ ],
103
+ repeat: 'last' // Stay at final response
104
+ }
105
+ }
106
+ ```
107
+
108
+ **Repeat modes** - `last` (stay at final), `cycle` (loop), `none` (exhaust)
109
+ **Sequence exhaustion with fallback** - Exhausted sequences skip to next mock
110
+
111
+ ### Stateful Mocks (6 capabilities)
112
+
113
+ **State capture from requests** - Extract values from body/headers/query
114
+ **State injection via templates** - Inject captured state using `{{state.X}}`
115
+ ```typescript
116
+ // Capture from POST
117
+ {
118
+ method: 'POST',
119
+ url: '/api/cart/items',
120
+ captureState: { 'cartItems[]': 'body.item' }, // Append to array
121
+ response: { status: 200 }
122
+ }
123
+
124
+ // Inject into GET response
125
+ {
126
+ method: 'GET',
127
+ url: '/api/cart',
128
+ response: {
129
+ status: 200,
130
+ body: {
131
+ items: '{{state.cartItems}}',
132
+ count: '{{state.cartItems.length}}'
133
+ }
134
+ }
135
+ }
136
+ ```
137
+
138
+ **Array append support** - Syntax: `stateKey[]` appends to array
139
+ **Nested state paths** - Support dot notation: `user.profile.name`
140
+ **State isolation per test ID** - Each test ID has isolated state
141
+ **State reset on scenario switch** - Fresh state for each scenario
142
+
143
+ ### Core Features (4 capabilities)
144
+
145
+ **Multiple API mocking** - Mock any number of external APIs in one scenario
146
+ **Automatic default fallback** - Active scenarios inherit mocks from default, override via specificity
147
+ **Test ID isolation** - Run 100+ tests concurrently without conflicts
148
+ **Runtime scenario switching** - Change backend state with one API call
149
+
150
+ ### Additional Features
151
+
152
+ **Path parameters** (`/users/:id`), **Wildcard URLs** (`*/api/*`), **Response delays**, **Custom headers**, **Strict mode** (fail on unmocked requests)
153
+
154
+ **Want to learn more?** See [Core Functionality Documentation](../../docs/core-functionality.md) for detailed explanations and examples.
155
+
156
+ ## Common Use Cases
157
+
158
+ ### Testing Error Scenarios
159
+
160
+ Test how your UI handles API errors without maintaining separate error mocks per test:
161
+
162
+ ```typescript
163
+ // Define once
164
+ const errorScenario = {
165
+ id: 'api-error',
166
+ name: 'API Error',
167
+ mocks: [{ method: 'GET', url: '*/api/*', response: { status: 500 } }]
168
+ };
169
+
170
+ // Use in many tests
171
+ await setScenario('test-1', 'api-error');
172
+ // All API calls return 500 for this test
173
+ ```
174
+
175
+ ### Testing Loading States
176
+
177
+ Test slow API responses without actual network delays:
178
+
179
+ ```typescript
180
+ const slowScenario = {
181
+ id: 'slow-api',
182
+ name: 'Slow API',
183
+ mocks: [{
184
+ method: 'GET',
185
+ url: '*/api/data',
186
+ response: { status: 200, body: { data: [] }, delay: 3000 } // 3s delay
187
+ }]
188
+ };
189
+
190
+ // Perfect for testing loading spinners and skeleton screens
191
+ ```
192
+
193
+ ### Testing User Tiers
194
+
195
+ Test different user permission levels by switching scenarios:
196
+
197
+ ```typescript
198
+ const freeUserScenario = { id: 'free', mocks: [/* limited features */] };
199
+ const premiumUserScenario = { id: 'premium', mocks: [/* all features */] };
200
+
201
+ // Test switches scenarios mid-suite - no app restart needed
202
+ test('free user sees upgrade prompt', async () => {
203
+ await setScenario('test-1', 'free');
204
+ // ... test free tier behavior
205
+ });
206
+
207
+ test('premium user sees all features', async () => {
208
+ await setScenario('test-2', 'premium');
209
+ // ... test premium tier behavior
210
+ });
211
+ ```
212
+
213
+ ### Parallel Test Execution
214
+
215
+ Run tests concurrently with different backend states - no conflicts:
216
+
217
+ ```typescript
218
+ // Test 1: Uses 'success' scenario with test-id-1
219
+ // Test 2: Uses 'error' scenario with test-id-2
220
+ // Test 3: Uses 'slow' scenario with test-id-3
221
+ // All running in parallel, completely isolated via test IDs
222
+ ```
223
+
224
+ **Want to see these in action?** Jump to [Quick Start (5 Minutes)](#quick-start-5-minutes).
225
+
226
+ ## Installation
227
+
228
+ ```bash
229
+ # npm
230
+ npm install --save-dev @scenarist/nextjs-adapter msw
231
+
232
+ # pnpm
233
+ pnpm add -D @scenarist/nextjs-adapter msw
234
+
235
+ # yarn
236
+ yarn add -D @scenarist/nextjs-adapter msw
237
+ ```
238
+
239
+ **Note:** All Scenarist types (`ScenaristScenario`, `ScenaristMock`, etc.) are re-exported from `@scenarist/nextjs-adapter` for convenience. You don't need to install `@scenarist/core` or `@scenarist/msw-adapter` separately - they're already included as dependencies.
240
+
241
+ **Peer Dependencies:**
242
+ - `next` ^14.0.0 || ^15.0.0
243
+ - `msw` ^2.0.0
244
+
245
+ ## Quick Start (5 Minutes)
246
+
247
+ **Goal:** Switch between success and error scenarios in your tests.
248
+
249
+ ### 1. Define Scenarios
250
+
251
+ ```typescript
252
+ // lib/scenarios.ts
253
+ import type { ScenaristScenario, ScenaristScenarios } from '@scenarist/nextjs-adapter';
254
+
255
+ export const defaultScenario: ScenaristScenario = {
256
+ id: 'default',
257
+ name: 'Default',
258
+ mocks: [{
259
+ method: 'GET',
260
+ url: 'https://api.example.com/user',
261
+ response: { status: 200, body: { name: 'Default User', role: 'user' } }
262
+ }]
263
+ };
264
+
265
+ export const successScenario: ScenaristScenario = {
266
+ id: 'success',
267
+ name: 'API Success',
268
+ mocks: [{
269
+ method: 'GET',
270
+ url: 'https://api.example.com/user',
271
+ response: { status: 200, body: { name: 'Alice', role: 'user' } }
272
+ }]
273
+ };
274
+
275
+ export const scenarios = {
276
+ default: defaultScenario,
277
+ success: successScenario,
278
+ } as const satisfies ScenaristScenarios;
279
+ ```
280
+
281
+ ### 2. Create Scenarist Instance
282
+
283
+ ```typescript
284
+ // lib/scenarist.ts
285
+ import { createScenarist } from '@scenarist/nextjs-adapter/pages'; // or /app
286
+ import { scenarios } from './scenarios';
287
+
288
+ export const scenarist = createScenarist({
289
+ enabled: process.env.NODE_ENV === 'test',
290
+ scenarios, // All scenarios registered upfront
291
+ });
292
+
293
+ // Start MSW in Node.js environment
294
+ if (typeof window === 'undefined' && scenarist) {
295
+ scenarist.start();
296
+ }
297
+ ```
298
+
299
+ > **CRITICAL: Singleton Pattern Required**
300
+ >
301
+ > **You MUST use `export const scenarist = createScenarist(...)` as shown above.** Do NOT wrap `createScenarist()` in a function:
302
+ >
303
+ > ```typescript
304
+ > // ❌ WRONG - Creates new instance each time
305
+ > export function getScenarist() {
306
+ > return createScenarist({ enabled: true, scenarios });
307
+ > }
308
+ >
309
+ > // ✅ CORRECT - Single exported constant
310
+ > export const scenarist = createScenarist({ enabled: true, scenarios });
311
+ > ```
312
+ >
313
+ > **Why:** Next.js dev server (and Turbopack) can load the same module multiple times. If you call `createScenarist()` repeatedly, you'll get multiple MSW servers conflicting with each other, causing `[MSW] Multiple handlers with the same URL` warnings and intermittent 500 errors.
314
+ >
315
+ > The singleton pattern inside `createScenarist()` prevents this - but ONLY if you export a constant. Wrapping in a function breaks the singleton protection.
316
+
317
+ ### 3. Create Scenario Endpoint
318
+
319
+ **Pages Router:** Create `pages/api/__scenario__.ts`:
320
+ ```typescript
321
+ import { scenarist } from '@/lib/scenarist';
322
+
323
+ // In production, scenarist is undefined due to conditional exports
324
+ // When the default export is undefined, Next.js treats the route as non-existent
325
+ export default scenarist?.createScenarioEndpoint();
326
+ ```
327
+
328
+ **App Router:** Create `app/api/%5F%5Fscenario%5F%5F/route.ts`:
329
+
330
+ > **Why the URL encoding?** Next.js App Router treats folders starting with `_` (underscore) as private folders that are excluded from routing. To create a URL route `/api/__scenario__`, we use `%5F` (URL-encoded underscore). This creates the actual endpoint at `http://localhost:3000/api/__scenario__`.
331
+
332
+ ```typescript
333
+ import { scenarist } from '@/lib/scenarist';
334
+
335
+ // In production, scenarist is undefined due to conditional exports
336
+ // When exports are undefined, Next.js treats the route as non-existent
337
+ const handler = scenarist?.createScenarioEndpoint();
338
+
339
+ export const POST = handler;
340
+ export const GET = handler;
341
+ ```
342
+
343
+ ### 4. Use in Tests
344
+
345
+ ```typescript
346
+ import { scenarist } from '@/lib/scenarist';
347
+
348
+ beforeAll(() => scenarist.start()); // Start MSW server
349
+ afterAll(() => scenarist.stop()); // Stop MSW server
350
+
351
+ it('fetches user successfully', async () => {
352
+ // Set scenario for this test
353
+ await fetch('http://localhost:3000/__scenario__', {
354
+ method: 'POST',
355
+ headers: { 'x-scenarist-test-id': 'test-1', 'content-type': 'application/json' },
356
+ body: JSON.stringify({ scenario: 'success' })
357
+ });
358
+
359
+ // Make request - MSW intercepts automatically
360
+ const response = await fetch('http://localhost:3000/api/user', {
361
+ headers: { 'x-scenarist-test-id': 'test-1' }
362
+ });
363
+
364
+ expect(response.status).toBe(200);
365
+ const user = await response.json();
366
+ expect(user.name).toBe('Alice');
367
+ });
368
+ ```
369
+
370
+ **That's it!** You've got runtime scenario switching.
371
+
372
+ **Next steps:**
373
+ - [Add more scenarios](#pages-router-setup) for different backend states
374
+ - [Use test helpers](#pattern-1-test-helpers) to reduce boilerplate
375
+ - [Learn about test isolation](#test-id-isolation) for parallel tests
376
+ - [See advanced features](../../docs/core-functionality.md#dynamic-response-system) like request matching and sequences
377
+
378
+ ---
379
+
380
+ ## Pages Router vs App Router
381
+
382
+ | Aspect | Pages Router | App Router |
383
+ |--------|-------------|------------|
384
+ | **Import Path** | `@scenarist/nextjs-adapter/pages` | `@scenarist/nextjs-adapter/app` |
385
+ | **Setup File** | `pages/api/__scenario__.ts` | `app/api/%5F%5Fscenario%5F%5F/route.ts` * |
386
+ | **Scenario Endpoint** | `export default scenarist.createScenarioEndpoint()` | `const handler = scenarist.createScenarioEndpoint();`<br>`export const POST = handler;`<br>`export const GET = handler;` |
387
+ | **Core Functionality** | ✅ Same scenarios, same behavior | ✅ Same scenarios, same behavior |
388
+
389
+ \* App Router uses `%5F%5Fscenario%5F%5F` (URL-encoded) because folders starting with `_` are treated as private folders in Next.js App Router. See [App Router Setup](#app-router-setup) for details.
390
+
391
+ **Key Insight:** Choose based on your Next.js version - all Scenarist features work identically in both routers.
392
+
393
+ **Detailed setup guides:**
394
+ - **[Pages Router Setup](#pages-router-setup)** - Full walkthrough for Pages Router
395
+ - **[App Router Setup](#app-router-setup)** - Full walkthrough for App Router
42
396
 
43
397
  ---
44
398
 
45
- **Maintained for OIDC setup purposes only**
399
+ ## Pages Router Setup
400
+
401
+ ### 1. Define Scenarios
402
+
403
+ ```typescript
404
+ // lib/scenarios/default.ts
405
+ import type { ScenaristScenario } from '@scenarist/nextjs-adapter/pages';
406
+
407
+ export const defaultScenario: ScenaristScenario = {
408
+ id: 'default',
409
+ name: 'Default Scenario',
410
+ description: 'Baseline responses for all APIs',
411
+ mocks: [
412
+ {
413
+ method: 'GET',
414
+ url: 'https://api.example.com/user',
415
+ response: {
416
+ status: 200,
417
+ body: {
418
+ id: '000',
419
+ name: 'Default User',
420
+ role: 'user',
421
+ },
422
+ },
423
+ },
424
+ ],
425
+ };
426
+
427
+ // lib/scenarios/admin-user.ts
428
+ export const adminUserScenario: ScenaristScenario = {
429
+ id: 'admin-user',
430
+ name: 'Admin User',
431
+ description: 'User with admin privileges',
432
+ mocks: [
433
+ {
434
+ method: 'GET',
435
+ url: 'https://api.example.com/user',
436
+ response: {
437
+ status: 200,
438
+ body: {
439
+ id: '123',
440
+ name: 'Admin User',
441
+ role: 'admin',
442
+ },
443
+ },
444
+ },
445
+ ],
446
+ };
447
+ ```
448
+
449
+ ### 2. Create Scenarist Instance
450
+
451
+ ```typescript
452
+ // lib/scenarist.ts
453
+ import { createScenarist } from '@scenarist/nextjs-adapter/pages';
454
+ import { scenarios } from './scenarios';
455
+
456
+ export const scenarist = createScenarist({
457
+ enabled: process.env.NODE_ENV === 'test',
458
+ scenarios, // All scenarios registered upfront
459
+ strictMode: false, // Allow unmocked requests to pass through to real APIs
460
+ });
461
+
462
+ // Start MSW in Node.js environment
463
+ if (typeof window === 'undefined' && scenarist) {
464
+ scenarist.start();
465
+ }
466
+ ```
467
+
468
+ ### 3. Create Scenario Endpoint
469
+
470
+ ```typescript
471
+ // pages/api/__scenario__.ts
472
+ import { scenarist } from '../../lib/scenarist';
473
+
474
+ // In production, scenarist is undefined due to conditional exports
475
+ // When the default export is undefined, Next.js treats the route as non-existent
476
+ export default scenarist?.createScenarioEndpoint();
477
+ ```
478
+
479
+ This single line creates a Next.js API route that handles both GET and POST requests for scenario management.
480
+
481
+ ### 4. Use in Tests
482
+
483
+ ```typescript
484
+ // tests/api.test.ts
485
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
486
+ import { scenarist } from '../lib/scenarist';
487
+
488
+ describe('User API', () => {
489
+ beforeAll(() => scenarist.start());
490
+ afterAll(() => scenarist.stop());
491
+
492
+ it('should return admin user', async () => {
493
+ // Set scenario for this test
494
+ await fetch('http://localhost:3000/__scenario__', {
495
+ method: 'POST',
496
+ headers: {
497
+ 'x-scenarist-test-id': 'admin-test',
498
+ 'content-type': 'application/json',
499
+ },
500
+ body: JSON.stringify({ scenario: 'admin-user' }),
501
+ });
502
+
503
+ // Make request - MSW intercepts automatically
504
+ const response = await fetch('http://localhost:3000/api/user', {
505
+ headers: { 'x-scenarist-test-id': 'admin-test' },
506
+ });
507
+
508
+ const user = await response.json();
509
+ expect(user.role).toBe('admin');
510
+ });
511
+ });
512
+ ```
513
+
514
+ ---
515
+
516
+ ## App Router Setup
517
+
518
+ ### 1. Define Scenarios
519
+
520
+ Same as Pages Router - see [Define Scenarios](#1-define-scenarios) above.
521
+
522
+ ### 2. Create Scenarist Instance
523
+
524
+ ```typescript
525
+ // lib/scenarist.ts
526
+ import { createScenarist } from '@scenarist/nextjs-adapter/app';
527
+ import { scenarios } from './scenarios';
528
+
529
+ export const scenarist = createScenarist({
530
+ enabled: process.env.NODE_ENV === 'test',
531
+ scenarios, // All scenarios registered upfront
532
+ strictMode: false, // Allow unmocked requests to pass through to real APIs
533
+ });
534
+
535
+ // Start MSW in Node.js environment
536
+ if (typeof window === 'undefined' && scenarist) {
537
+ scenarist.start();
538
+ }
539
+ ```
540
+
541
+ ### 3. Create Scenario Route Handlers
542
+
543
+ ```typescript
544
+ // app/api/%5F%5Fscenario%5F%5F/route.ts
545
+ import { scenarist } from '@/lib/scenarist';
546
+
547
+ // In production, scenarist is undefined due to conditional exports
548
+ // When exports are undefined, Next.js treats the route as non-existent
549
+ const handler = scenarist?.createScenarioEndpoint();
550
+
551
+ export const POST = handler;
552
+ export const GET = handler;
553
+ ```
554
+
555
+ The App Router uses Web standard Request/Response API and requires explicit exports for each HTTP method.
556
+
557
+ ### 4. Use in Tests
558
+
559
+ Same as Pages Router - see [Use in Tests](#4-use-in-tests) above. The scenario endpoint works identically.
560
+
561
+ ---
562
+
563
+ ## API Reference
564
+
565
+ ### `createScenarist(options)`
566
+
567
+ Creates a Scenarist instance with everything wired automatically.
568
+
569
+ **Import:**
570
+ ```typescript
571
+ // Pages Router
572
+ import { createScenarist } from '@scenarist/nextjs-adapter/pages';
573
+
574
+ // App Router
575
+ import { createScenarist } from '@scenarist/nextjs-adapter/app';
576
+ ```
577
+
578
+ **Parameters:**
579
+ ```typescript
580
+ type AdapterOptions<T extends ScenaristScenarios> = {
581
+ enabled: boolean; // Whether mocking is enabled
582
+ scenarios: T; // REQUIRED - scenarios object (all scenarios registered upfront)
583
+ strictMode?: boolean; // Return 501 for unmocked requests (default: false)
584
+ headers?: {
585
+ testId?: string; // Header for test ID (default: 'x-scenarist-test-id')
586
+ };
587
+ defaultTestId?: string; // Default test ID (default: 'default-test')
588
+ registry?: ScenarioRegistry; // Custom registry (default: InMemoryScenarioRegistry)
589
+ store?: ScenarioStore; // Custom store (default: InMemoryScenarioStore)
590
+ stateManager?: StateManager; // Custom state manager (default: InMemoryStateManager)
591
+ sequenceTracker?: SequenceTracker; // Custom sequence tracker (default: InMemorySequenceTracker)
592
+ };
593
+ ```
594
+
595
+ **Returns:**
596
+ ```typescript
597
+ type Scenarist<T extends ScenaristScenarios> = {
598
+ config: ScenaristConfig; // Resolved configuration (headers, etc.)
599
+ createScenarioEndpoint: () => Handler; // Creates scenario endpoint handler
600
+ switchScenario: (testId: string, scenarioId: ScenarioIds<T>, variant?: string) => ScenaristResult<void, Error>;
601
+ getActiveScenario: (testId: string) => ActiveScenario | undefined;
602
+ getScenarioById: (scenarioId: ScenarioIds<T>) => ScenaristScenario | undefined;
603
+ listScenarios: () => ReadonlyArray<ScenaristScenario>;
604
+ clearScenario: (testId: string) => void;
605
+ start: () => void; // Start MSW server
606
+ stop: () => Promise<void>; // Stop MSW server
607
+ };
608
+ ```
609
+
610
+ **Key Difference from Express Adapter:**
611
+
612
+ Unlike Express, Next.js doesn't have global middleware. Instead, you manually create the scenario endpoint using `createScenarioEndpoint()`:
613
+
614
+ ```typescript
615
+ // Pages Router - single default export
616
+ export default scenarist.createScenarioEndpoint();
617
+
618
+ // App Router - explicit method exports
619
+ const handler = scenarist.createScenarioEndpoint();
620
+ export const POST = handler;
621
+ export const GET = handler;
622
+ ```
623
+
624
+ ### Scenario Endpoints
625
+
626
+ The endpoint handler exposes these operations:
627
+
628
+ #### `POST /__scenario__` - Set Active Scenario
629
+
630
+ **Request:**
631
+ ```typescript
632
+ {
633
+ scenario: string; // Scenario ID (required)
634
+ variant?: string; // Variant name (optional)
635
+ }
636
+ ```
637
+
638
+ **Response (200):**
639
+ ```typescript
640
+ {
641
+ success: true;
642
+ testId: string;
643
+ scenarioId: string;
644
+ variant?: string;
645
+ }
646
+ ```
647
+
648
+ **Example:**
649
+ ```typescript
650
+ await fetch('http://localhost:3000/__scenario__', {
651
+ method: 'POST',
652
+ headers: {
653
+ 'x-scenarist-test-id': 'test-123',
654
+ 'content-type': 'application/json',
655
+ },
656
+ body: JSON.stringify({ scenario: 'user-logged-in' }),
657
+ });
658
+ ```
659
+
660
+ #### `GET /__scenario__` - Get Active Scenario
661
+
662
+ **Response (200):**
663
+ ```typescript
664
+ {
665
+ testId: string;
666
+ scenarioId: string;
667
+ scenarioName?: string;
668
+ }
669
+ ```
670
+
671
+ **Response (404) - No Active Scenario:**
672
+ ```typescript
673
+ {
674
+ error: "No active scenario for this test ID";
675
+ testId: string;
676
+ }
677
+ ```
678
+
679
+ **Example:**
680
+ ```typescript
681
+ const response = await fetch('http://localhost:3000/__scenario__', {
682
+ headers: { 'x-scenarist-test-id': 'test-123' },
683
+ });
684
+
685
+ const data = await response.json();
686
+ console.log(data.scenarioId); // 'user-logged-in'
687
+ ```
688
+
689
+ ## Core Concepts
690
+
691
+ Scenarist's core functionality is framework-agnostic. For deep understanding of these concepts (request matching, sequences, stateful mocks), see **[Core Functionality Documentation](../../docs/core-functionality.md)**.
692
+
693
+ **Quick reference for Next.js:**
694
+
695
+ ### Test ID Isolation
696
+
697
+ Each request includes an `x-scenarist-test-id` header for parallel test isolation:
698
+
699
+ ```typescript
700
+ // Test 1
701
+ headers: { 'x-scenarist-test-id': 'test-1' } // Uses scenario A
702
+
703
+ // Test 2 (parallel!)
704
+ headers: { 'x-scenarist-test-id': 'test-2' } // Uses scenario B
705
+ ```
706
+
707
+ Each test ID has completely isolated:
708
+ - Active scenario selection
709
+ - Sequence positions (for polling scenarios)
710
+ - Captured state (for stateful mocks)
711
+
712
+ **Learn more:** [Test Isolation in Core Docs](../../docs/core-functionality.md#test-isolation)
713
+
714
+ ### Making External API Calls
715
+
716
+ **IMPORTANT:** When your API routes call external APIs (or services mocked by Scenarist), you must forward Scenarist headers so MSW can intercept with the correct scenario.
717
+
718
+ **Why Next.js needs this:** Unlike Express (which uses AsyncLocalStorage middleware), Next.js API routes have no middleware layer to automatically propagate test IDs. You must manually forward the headers.
719
+
720
+ Use the safe helper functions provided by the adapter:
721
+
722
+ **Pages Router:**
723
+ ```typescript
724
+ // pages/api/products.ts
725
+ import type { NextApiRequest, NextApiResponse } from 'next';
726
+ import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
727
+
728
+ export default async function handler(
729
+ req: NextApiRequest,
730
+ res: NextApiResponse
731
+ ) {
732
+ // Fetch from external API with Scenarist headers forwarded
733
+ const response = await fetch('http://external-api.com/products', {
734
+ headers: {
735
+ ...getScenaristHeaders(req), // ✅ Scenarist infrastructure headers
736
+ 'content-type': 'application/json', // ✅ Your application headers
737
+ 'x-user-tier': req.headers['x-user-tier'], // ✅ Other app-specific headers
738
+ },
739
+ });
740
+
741
+ const data = await response.json();
742
+ res.json(data);
743
+ }
744
+ ```
745
+
746
+ **App Router Route Handlers:**
747
+ ```typescript
748
+ // app/api/products/route.ts
749
+ import { getScenaristHeaders } from '@scenarist/nextjs-adapter/app';
750
+
751
+ export async function GET(request: Request) {
752
+ const response = await fetch('http://external-api.com/products', {
753
+ headers: {
754
+ ...getScenaristHeaders(request),
755
+ 'content-type': 'application/json',
756
+ },
757
+ });
758
+
759
+ const data = await response.json();
760
+ return Response.json(data);
761
+ }
762
+ ```
763
+
764
+ **App Router Server Components:**
765
+ ```typescript
766
+ // app/products/page.tsx
767
+ import { headers } from 'next/headers';
768
+ import { getScenaristHeadersFromReadonlyHeaders } from '@scenarist/nextjs-adapter/app';
769
+
770
+ export default async function ProductsPage() {
771
+ // Server Components use headers() which returns ReadonlyHeaders, not Request
772
+ const headersList = await headers();
773
+
774
+ const response = await fetch('http://external-api.com/products', {
775
+ headers: {
776
+ ...getScenaristHeadersFromReadonlyHeaders(headersList), // ✅ For ReadonlyHeaders
777
+ 'content-type': 'application/json',
778
+ },
779
+ });
780
+
781
+ const data = await response.json();
782
+ return <ProductList products={data.products} />;
783
+ }
784
+ ```
785
+
786
+ **What these helpers do:**
787
+ - Extract test ID from request headers (`x-scenarist-test-id` by default)
788
+ - Respect your configured `testIdHeaderName` and `defaultTestId`
789
+ - Return object with Scenarist headers ready to spread
790
+ - Safe to use in production (return empty object when scenarist is undefined)
791
+
792
+ **When to use which helper:**
793
+ - **`getScenaristHeaders(request | req)`** - Route Handlers (Request object) or Pages Router API routes (NextApiRequest)
794
+ - **`getScenaristHeadersFromReadonlyHeaders(headersList)`** - App Router Server Components (ReadonlyHeaders from `headers()`)
795
+
796
+ **Key Distinction:**
797
+ - **Scenarist headers** (`x-scenarist-test-id`) - Infrastructure for test isolation
798
+ - **Application headers** (`x-user-tier`, `content-type`) - Your app's business logic
799
+
800
+ Only Scenarist headers need forwarding via helper functions. Your application headers are independent.
801
+
802
+ **For architectural rationale, see:** [ADR-0007: Framework-Specific Header Forwarding](../../docs/adrs/0007-framework-specific-header-helpers.md)
803
+
804
+ ### Automatic MSW Integration
805
+
806
+ `createScenarist()` automatically wires MSW for request interception. You never see MSW code directly.
807
+
808
+ **What it does:**
809
+ 1. Creates MSW server with dynamic handler
810
+ 2. Extracts test ID from request headers
811
+ 3. Looks up active scenario for that test ID
812
+ 4. Returns mocked responses based on scenario
813
+
814
+ **Next.js-specific details:**
815
+ - Pages Router: Uses Next.js API routes
816
+ - App Router: Uses Web standard Request/Response
817
+ - Both: Full test ID isolation via headers
818
+
819
+ ### Default Scenario Fallback
820
+
821
+ Active scenario mocks take precedence; unmocked endpoints fall back to default scenario:
822
+
823
+ ```typescript
824
+ // Default covers all endpoints
825
+ const defaultScenario = {
826
+ id: 'default',
827
+ mocks: [
828
+ { method: 'GET', url: '*/api/users', response: { status: 200, body: [] } },
829
+ { method: 'GET', url: '*/api/orders', response: { status: 200, body: [] } },
830
+ ]
831
+ };
832
+
833
+ // Test scenario overrides only specific endpoints
834
+ const errorScenario = {
835
+ id: 'error',
836
+ mocks: [
837
+ { method: 'GET', url: '*/api/users', response: { status: 500 } }
838
+ // Orders uses default scenario
839
+ ]
840
+ };
841
+ ```
842
+
843
+ **Learn more:** [Fallback Behavior in Core Docs](../../docs/core-functionality.md#fallback-behavior)
844
+
845
+ ## Type-Safe Scenario IDs
846
+
847
+ TypeScript automatically infers scenario names from your scenarios object, providing autocomplete and compile-time safety.
848
+
849
+ ### How It Works
850
+
851
+ ```typescript
852
+ // lib/scenarios.ts
853
+ import type { ScenaristScenario, ScenaristScenarios } from '@scenarist/nextjs-adapter/pages';
854
+
855
+ export const scenarios = {
856
+ default: { id: 'default', name: 'Default', mocks: [] },
857
+ success: { id: 'success', name: 'Success', mocks: [] },
858
+ error: { id: 'error', name: 'Error', mocks: [] },
859
+ timeout: { id: 'timeout', name: 'Timeout', mocks: [] },
860
+ } as const satisfies ScenaristScenarios;
861
+
862
+ // lib/scenarist.ts
863
+ import { createScenarist } from '@scenarist/nextjs-adapter/pages';
864
+ import { scenarios } from './scenarios';
865
+
866
+ export const scenarist = createScenarist({
867
+ enabled: true,
868
+ scenarios, // ✅ Autocomplete + type-checked!
869
+ });
870
+ ```
871
+
872
+ ### Type Safety Benefits
873
+
874
+ ```typescript
875
+ // ✅ Valid - TypeScript knows about these scenario IDs
876
+ scenarist.switchScenario('test-123', 'success');
877
+ scenarist.switchScenario('test-123', 'error');
878
+ scenarist.switchScenario('test-123', 'timeout');
879
+
880
+ // ❌ TypeScript error - 'invalid-name' is not a valid scenario ID
881
+ scenarist.switchScenario('test-123', 'invalid-name');
882
+ // ^^^^^^^^^^^^^^
883
+ // Argument of type '"invalid-name"' is not assignable to parameter of type
884
+ // '"default" | "success" | "error" | "timeout"'
885
+ ```
886
+
887
+ ### In Tests
888
+
889
+ ```typescript
890
+ // tests.ts
891
+ import { scenarios } from './scenarios';
892
+
893
+ // ✅ Type-safe scenario switching
894
+ await fetch('http://localhost:3000/__scenario__', {
895
+ method: 'POST',
896
+ headers: { 'x-scenarist-test-id': 'test-1', 'content-type': 'application/json' },
897
+ body: JSON.stringify({ scenario: 'success' }), // ✅ Autocomplete works!
898
+ });
899
+
900
+ // Or reference by object key for refactor-safety
901
+ await fetch('http://localhost:3000/__scenario__', {
902
+ method: 'POST',
903
+ headers: { 'x-scenarist-test-id': 'test-1', 'content-type': 'application/json' },
904
+ body: JSON.stringify({ scenario: scenarios.success.id }), // ✅ Even safer!
905
+ });
906
+ ```
907
+
908
+ **What you get:**
909
+ - ✅ IDE autocomplete for all scenario names
910
+ - ✅ Compile-time errors for typos (catch bugs before runtime)
911
+ - ✅ Refactor-safe (rename scenarios and all usages update)
912
+ - ✅ Self-documenting code (see all available scenarios in one place)
913
+ - ✅ Single source of truth (scenarios object defines everything)
914
+
915
+ ## Common Patterns
916
+
917
+ ### Pattern 1: Test Helpers
918
+
919
+ Create helper functions to reduce boilerplate:
920
+
921
+ ```typescript
922
+ // tests/helpers.ts
923
+ const API_BASE = 'http://localhost:3000';
924
+
925
+ export const setScenario = async (testId: string, scenario: string, variant?: string) => {
926
+ await fetch(`${API_BASE}/__scenario__`, {
927
+ method: 'POST',
928
+ headers: {
929
+ 'x-scenarist-test-id': testId,
930
+ 'content-type': 'application/json',
931
+ },
932
+ body: JSON.stringify({ scenario, variant }),
933
+ });
934
+ };
935
+
936
+ export const makeRequest = (testId: string, path: string, options?: RequestInit) => {
937
+ return fetch(`${API_BASE}${path}`, {
938
+ ...options,
939
+ headers: {
940
+ ...options?.headers,
941
+ 'x-scenarist-test-id': testId,
942
+ },
943
+ });
944
+ };
945
+ ```
946
+
947
+ **Usage:**
948
+ ```typescript
949
+ import { setScenario, makeRequest } from './helpers';
950
+
951
+ test('payment flow', async () => {
952
+ const testId = 'payment-test';
953
+ await setScenario(testId, 'payment-success');
954
+
955
+ const response = await makeRequest(testId, '/api/charge', { method: 'POST' });
956
+ expect(response.status).toBe(200);
957
+ });
958
+ ```
959
+
960
+ ### Pattern 2: Unique Test IDs
961
+
962
+ Generate unique test IDs automatically using a factory function:
963
+
964
+ ```typescript
965
+ import { randomUUID } from 'crypto';
966
+
967
+ describe('API Tests', () => {
968
+ // Factory function - no shared mutable state
969
+ const createTestId = () => randomUUID();
970
+
971
+ it('should process payment', async () => {
972
+ const testId = createTestId(); // Fresh ID per test
973
+
974
+ await setScenario(testId, 'payment-success');
975
+ const response = await makeRequest(testId, '/api/charge', { method: 'POST' });
976
+ expect(response.status).toBe(200);
977
+ });
978
+
979
+ it('should handle payment decline', async () => {
980
+ const testId = createTestId(); // Independent state
981
+
982
+ await setScenario(testId, 'payment-declined');
983
+ const response = await makeRequest(testId, '/api/charge', { method: 'POST' });
984
+ expect(response.status).toBe(402);
985
+ });
986
+ });
987
+ ```
988
+
989
+ ### Pattern 3: Development Workflows
990
+
991
+ **⚠️ Security Warning:** Only enable scenario endpoints in development/test environments, **NEVER in production**.
992
+
993
+ **Why?** The `/__scenario__` endpoint allows arbitrary mock switching, which could be exploited in production to bypass security, fake data, or cause unexpected behavior.
994
+
995
+ **Safe configuration:**
996
+
997
+ ```typescript
998
+ // lib/scenarist.ts
999
+ // ✅ CORRECT - Only enabled in safe environments
1000
+ const scenarist = createScenarist({
1001
+ enabled: process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test',
1002
+ scenarios,
1003
+ strictMode: false,
1004
+ });
1005
+
1006
+ // ❌ WRONG - Dangerous in production
1007
+ const scenarist = createScenarist({
1008
+ enabled: true, // Always on, including production!
1009
+ scenarios,
1010
+ });
1011
+ ```
1012
+
1013
+ **Production checklist:**
1014
+ - ✅ `enabled` is conditional (never hardcoded `true`)
1015
+ - ✅ Environment checks use `process.env.NODE_ENV`
1016
+ - ✅ `/__scenario__` endpoints not exposed in production builds
1017
+
1018
+ **During development**, manually switch scenarios with curl:
1019
+
1020
+ ```bash
1021
+ # Switch to error scenario
1022
+ curl -X POST http://localhost:3000/__scenario__ \
1023
+ -H "Content-Type: application/json" \
1024
+ -d '{"scenario": "payment-declined"}'
1025
+
1026
+ # Check active scenario
1027
+ curl http://localhost:3000/__scenario__
1028
+ ```
1029
+
1030
+ ## Configuration
1031
+
1032
+ ### Environment-Specific
1033
+
1034
+ ```typescript
1035
+ // Test-only
1036
+ const scenarist = createScenarist({
1037
+ enabled: process.env.NODE_ENV === 'test',
1038
+ scenarios,
1039
+ strictMode: true, // Fail if any unmocked request
1040
+ });
1041
+
1042
+ // Development and test
1043
+ const scenarist = createScenarist({
1044
+ enabled: process.env.NODE_ENV === 'test' || process.env.NODE_ENV === 'development',
1045
+ scenarios,
1046
+ strictMode: false, // Allow passthrough to real APIs
1047
+ });
1048
+
1049
+ // Opt-in with environment variable
1050
+ const scenarist = createScenarist({
1051
+ enabled: process.env.ENABLE_MOCKING === 'true',
1052
+ scenarios,
1053
+ strictMode: false,
1054
+ });
1055
+ ```
1056
+
1057
+ ### strictMode Option
1058
+
1059
+ Controls behavior when no mock matches a request.
1060
+
1061
+ **`strictMode: false` (recommended for development):**
1062
+ - Unmocked requests pass through to real APIs
1063
+ - Useful when only mocking specific endpoints
1064
+ - Default scenario provides fallback for common endpoints
1065
+ - Best for development where you want partial mocking
1066
+
1067
+ **`strictMode: true` (recommended for tests):**
1068
+ - Unmocked requests return 501 Not Implemented
1069
+ - Ensures tests don't accidentally hit real APIs
1070
+ - Catches missing mocks early in test development
1071
+ - Best for test isolation and reproducibility
1072
+
1073
+ **Example:**
1074
+
1075
+ ```typescript
1076
+ // Development: Only mock failing endpoints, let others pass through
1077
+ const minimalScenarios = {
1078
+ default: minimalScenario, // Only critical mocks
1079
+ } as const satisfies ScenaristScenarios;
1080
+
1081
+ const scenarist = createScenarist({
1082
+ enabled: process.env.NODE_ENV === 'development',
1083
+ scenarios: minimalScenarios,
1084
+ strictMode: false, // Let unmocked APIs pass through to real services
1085
+ });
1086
+
1087
+ // Testing: Ensure complete isolation
1088
+ const testScenarios = {
1089
+ default: completeScenario, // Mock all endpoints
1090
+ } as const satisfies ScenaristScenarios;
1091
+
1092
+ const scenarist = createScenarist({
1093
+ enabled: process.env.NODE_ENV === 'test',
1094
+ scenarios: testScenarios,
1095
+ strictMode: true, // Fail loudly if any endpoint isn't mocked
1096
+ });
1097
+ ```
1098
+
1099
+ **When strictMode is true:**
1100
+ - Request for mocked endpoint → Returns defined mock response ✅
1101
+ - Request for unmocked endpoint → Returns 501 Not Implemented ❌
1102
+ - Easy to spot missing mocks during test development
1103
+
1104
+ **When strictMode is false:**
1105
+ - Request for mocked endpoint → Returns defined mock response ✅
1106
+ - Request for unmocked endpoint → Passes through to real API 🌐
1107
+ - Useful for incremental mocking in development
1108
+
1109
+ ### Custom Headers
1110
+
1111
+ ```typescript
1112
+ const scenarist = createScenarist({
1113
+ enabled: true,
1114
+ scenarios,
1115
+ headers: {
1116
+ testId: 'x-my-test-id',
1117
+ },
1118
+ });
1119
+ ```
1120
+
1121
+ ## Troubleshooting
1122
+
1123
+ ### Scenarios switch but requests aren't mocked
1124
+
1125
+ **Problem:** Scenario endpoints work but external API calls go to real endpoints.
1126
+
1127
+ **Solution:** Ensure you've called `scenarist.start()` before tests and `scenarist.stop()` after:
1128
+
1129
+ ```typescript
1130
+ beforeAll(() => scenarist.start()); // Starts MSW server
1131
+ afterAll(() => scenarist.stop()); // Stops MSW server
1132
+ ```
1133
+
1134
+ ### Tests see each other's scenarios
1135
+
1136
+ **Problem:** Different tests are seeing each other's active scenarios.
1137
+
1138
+ **Solution:** Ensure you're sending the `x-scenarist-test-id` header with **every** request:
1139
+
1140
+ ```typescript
1141
+ // ❌ Wrong - missing header on second request
1142
+ await setScenario('test-1', 'my-scenario');
1143
+ const response = await fetch('http://localhost:3000/api/data'); // No test ID!
1144
+
1145
+ // ✅ Correct - header on all requests
1146
+ await setScenario('test-1', 'my-scenario');
1147
+ const response = await fetch('http://localhost:3000/api/data', {
1148
+ headers: { 'x-scenarist-test-id': 'test-1' },
1149
+ });
1150
+ ```
1151
+
1152
+ ### Scenario not found error
1153
+
1154
+ **Problem:** `Scenario not found` when setting scenario.
1155
+
1156
+ **Solution:** Ensure the scenario is included in your scenarios object:
1157
+
1158
+ ```typescript
1159
+ // lib/scenarios.ts
1160
+ export const scenarios = {
1161
+ default: defaultScenario,
1162
+ 'my-scenario': myScenario, // ✅ Include in scenarios object
1163
+ } as const satisfies ScenaristScenarios;
1164
+
1165
+ // lib/scenarist.ts
1166
+ const scenarist = createScenarist({
1167
+ enabled: true,
1168
+ scenarios, // All scenarios registered automatically
1169
+ });
1170
+
1171
+ // tests
1172
+ await setScenario('test-1', 'my-scenario'); // ✅ Now works
1173
+ ```
1174
+
1175
+ ### TypeScript errors with Next.js types
1176
+
1177
+ **Problem:** Type errors with Next.js request/response types.
1178
+
1179
+ **Solution:** Ensure your `next` peer dependency version matches the adapter's supported versions (^14.0.0 || ^15.0.0).
1180
+
1181
+ ## TypeScript
1182
+
1183
+ This package is written in TypeScript and includes full type definitions.
1184
+
1185
+ **Exported Types:**
1186
+ ```typescript
1187
+ // Pages Router - adapter-specific types
1188
+ import type {
1189
+ PagesAdapterOptions,
1190
+ PagesScenarist,
1191
+ PagesRequestContext,
1192
+ } from '@scenarist/nextjs-adapter/pages';
1193
+
1194
+ // Pages Router - core types (re-exported for convenience)
1195
+ import type {
1196
+ ScenaristScenario,
1197
+ ScenaristMock,
1198
+ ScenaristResponse,
1199
+ ScenaristSequence,
1200
+ ScenaristMatch,
1201
+ ScenaristCaptureConfig,
1202
+ ScenaristScenarios,
1203
+ ScenaristConfig,
1204
+ ScenaristResult,
1205
+ } from '@scenarist/nextjs-adapter/pages';
1206
+
1207
+ // App Router - adapter-specific types
1208
+ import type {
1209
+ AppAdapterOptions,
1210
+ AppScenarist,
1211
+ AppRequestContext,
1212
+ } from '@scenarist/nextjs-adapter/app';
1213
+
1214
+ // App Router - core types (re-exported for convenience)
1215
+ import type {
1216
+ ScenaristScenario,
1217
+ ScenaristMock,
1218
+ ScenaristResponse,
1219
+ ScenaristSequence,
1220
+ ScenaristMatch,
1221
+ ScenaristCaptureConfig,
1222
+ ScenaristScenarios,
1223
+ ScenaristConfig,
1224
+ ScenaristResult,
1225
+ } from '@scenarist/nextjs-adapter/app';
1226
+ ```
1227
+
1228
+ **Note:** All core types are re-exported from both `/pages` and `/app` subpaths for convenience. You only need one import path for all Scenarist types - just import from the subpath that matches your Next.js router.
1229
+
1230
+ ## Advanced Usage
1231
+
1232
+ **Note:** Most users should use `createScenarist()`, which handles everything automatically.
1233
+
1234
+ <details>
1235
+ <summary><strong>For framework authors or custom integrations only - click to expand</strong></summary>
1236
+
1237
+ If you need custom wiring for specialized use cases, you can access low-level components:
1238
+
1239
+ ```typescript
1240
+ // Pages Router low-level components
1241
+ import {
1242
+ PagesRequestContext,
1243
+ createScenarioEndpoint,
1244
+ } from '@scenarist/nextjs-adapter/pages';
1245
+
1246
+ // App Router low-level components
1247
+ import {
1248
+ AppRequestContext,
1249
+ createScenarioEndpoint,
1250
+ } from '@scenarist/nextjs-adapter/app';
1251
+ ```
1252
+
1253
+ **Use cases for low-level APIs:**
1254
+ - Building a custom adapter for a Next.js-like framework
1255
+ - Integrating with non-standard request handling
1256
+ - Creating custom middleware chains
1257
+ - Implementing custom test ID extraction logic
1258
+
1259
+ **For typical Next.js applications, use `createScenarist()` instead.** It provides the same functionality with zero configuration.
1260
+
1261
+ </details>
1262
+
1263
+ ## Production Tree-Shaking
1264
+
1265
+ **Problem:** MSW and Scenarist are test-only dependencies that should never appear in production bundles.
1266
+
1267
+ **Solution:** The Next.js adapter uses **conditional exports** to eliminate all testing code from production builds automatically.
1268
+
1269
+ ### How It Works
1270
+
1271
+ When `NODE_ENV=production`, bundlers (Next.js webpack/Turbopack, esbuild, Vite, etc.) automatically resolve to production entry points that return `undefined` with **zero imports**:
1272
+
1273
+ ```typescript
1274
+ // Production build imports this instead:
1275
+ // packages/nextjs-adapter/src/app/production.ts (or pages/production.ts)
1276
+ export const createScenarist = () => undefined;
1277
+ // No imports = 100% tree-shaking
1278
+ ```
1279
+
1280
+ ### Bundle Size Impact
1281
+
1282
+ **Before (development):**
1283
+ - Scenarist adapter + Core + MSW: ~320kb
1284
+
1285
+ **After (production with tree-shaking):**
1286
+ - **0kb** - Complete elimination
1287
+
1288
+ ### Verifying Tree-Shaking
1289
+
1290
+ Both Next.js example apps include verification scripts:
1291
+
1292
+ ```bash
1293
+ # App Router example
1294
+ cd apps/nextjs-app-router-example
1295
+ pnpm verify:treeshaking
1296
+
1297
+ # Pages Router example
1298
+ cd apps/nextjs-pages-router-example
1299
+ pnpm verify:treeshaking
1300
+ ```
1301
+
1302
+ This builds your app with `NODE_ENV=production` and verifies zero MSW code exists in the `.next/` bundle.
1303
+
1304
+ ### Bundler Configuration
1305
+
1306
+ **Next.js (Automatic):**
1307
+ - Next.js webpack/Turbopack automatically respects `NODE_ENV=production`
1308
+ - No configuration needed - tree-shaking works out of the box
1309
+
1310
+ **Custom Bundlers:**
1311
+
1312
+ If using a custom bundler, ensure it resolves the `"production"` condition:
1313
+
1314
+ ```javascript
1315
+ // esbuild
1316
+ esbuild.build({
1317
+ conditions: ['production'], // Resolves production entry points
1318
+ define: { 'process.env.NODE_ENV': '"production"' },
1319
+ });
1320
+
1321
+ // Webpack
1322
+ module.exports = {
1323
+ resolve: {
1324
+ conditionNames: ['production', 'import'],
1325
+ },
1326
+ };
1327
+
1328
+ // Vite
1329
+ export default {
1330
+ resolve: {
1331
+ conditions: ['production'],
1332
+ },
1333
+ };
1334
+ ```
1335
+
1336
+ ### What Gets Eliminated
1337
+
1338
+ When tree-shaking succeeds, your production bundle has:
1339
+ - ❌ No MSW runtime code (`setupWorker`, `http.get`, `HttpResponse.json`)
1340
+ - ❌ No Scenarist core code (scenario manager, state manager, etc.)
1341
+ - ❌ No Zod validation schemas
1342
+ - ❌ No adapter code (request context, endpoints, etc.)
1343
+ - ✅ Only your application code
1344
+
1345
+ ### Troubleshooting Tree-Shaking
1346
+
1347
+ **If `verify:treeshaking` fails:**
1348
+
1349
+ 1. **Check `NODE_ENV`:** Ensure `NODE_ENV=production` during build
1350
+ ```bash
1351
+ NODE_ENV=production next build
1352
+ ```
1353
+
1354
+ 2. **Check bundler configuration:** Verify `"production"` condition is resolved
1355
+ - Next.js: Should work automatically
1356
+ - Custom bundlers: Add `conditions: ['production']`
1357
+
1358
+ 3. **Check dynamic imports:** Avoid dynamic imports that bypass tree-shaking
1359
+ ```typescript
1360
+ // ❌ BAD - Bypasses tree-shaking
1361
+ const scenarist = await import('@scenarist/nextjs-adapter/app');
1362
+
1363
+ // ✅ GOOD - Enables tree-shaking
1364
+ import { createScenarist } from '@scenarist/nextjs-adapter/app';
1365
+ const scenarist = createScenarist({ ... });
1366
+ ```
1367
+
1368
+ 4. **Inspect bundle:** Check `.next/` directory for MSW strings
1369
+ ```bash
1370
+ grep -r "setupWorker\|HttpResponse\.json" .next/
1371
+ ```
1372
+
1373
+ ### Architecture Details
1374
+
1375
+ The adapter uses **package.json conditional exports** to provide different entry points per environment:
1376
+
1377
+ ```json
1378
+ {
1379
+ "exports": {
1380
+ "./app": {
1381
+ "types": "./dist/app/index.d.ts",
1382
+ "production": "./dist/app/production.js", // Returns undefined
1383
+ "import": "./dist/app/index.js" // Full implementation
1384
+ },
1385
+ "./pages": {
1386
+ "types": "./dist/pages/index.d.ts",
1387
+ "production": "./dist/pages/production.js", // Returns undefined
1388
+ "import": "./dist/pages/index.js" // Full implementation
1389
+ }
1390
+ }
1391
+ }
1392
+ ```
1393
+
1394
+ **Key Insight:** Since the production entry point has **zero imports**, bundlers eliminate the entire dependency chain (adapter → core → MSW → Zod). This is more effective than dynamic imports or `NODE_ENV` checks, which can't guarantee complete elimination.
1395
+
1396
+ **For architectural rationale, see:** [Tree-Shaking Investigation](../../docs/investigations/tree-shaking-dynamic-imports-vs-conditional-exports.md)
1397
+
1398
+ ---
1399
+
1400
+ ## Development & Testing
1401
+
1402
+ ### Test Coverage Exception
1403
+
1404
+ **For users:** This package is production-ready and fully tested. The function coverage gap described below does not affect functionality or safety - it's an architectural pattern that will be resolved with integration tests in Phase 0.
1405
+
1406
+ **For developers:** This package has an explicit exception to the project's 100% coverage requirement.
1407
+
1408
+ **Current Coverage:**
1409
+ - Lines: 100% ✅
1410
+ - Statements: 100% ✅
1411
+ - Branches: 100% ✅
1412
+ - Functions: **93.2%** (explicit exception - improved from 86% after refactoring)
1413
+
1414
+ **Reason for Exception:**
1415
+
1416
+ Arrow functions passed to `createDynamicHandler()` in `src/common/create-scenarist-base.ts` are only executed when MSW handles actual HTTP requests:
1417
+
1418
+ ```typescript
1419
+ const handler = createDynamicHandler({
1420
+ getTestId: () => currentTestId, // Only called during HTTP request
1421
+ getActiveScenario: (testId) => ..., // Only called during HTTP request
1422
+ getScenarioDefinition: (scenarioId) => ..., // Only called during HTTP request
1423
+ });
1424
+ ```
1425
+
1426
+ Adapter unit tests focus on Layer 2 (translation layer):
1427
+ - Request context extraction
1428
+ - Endpoint request/response handling
1429
+ - Framework-specific edge cases
1430
+
1431
+ These tests do NOT make real HTTP requests, so the handler arrow functions are never executed.
1432
+
1433
+ **Resolution:**
1434
+
1435
+ Phase 0 (Next.js example app) will add integration tests that:
1436
+ - Make real HTTP requests (like Express example app does with supertest)
1437
+ - Trigger MSW handlers
1438
+ - Execute the remaining arrow functions
1439
+ - Achieve 100% combined coverage across adapter + example app
1440
+
1441
+ **Precedent:**
1442
+
1443
+ The Express adapter follows the same pattern:
1444
+ - Adapter unit tests: `packages/express-adapter/tests/`
1445
+ - Integration tests: `apps/express-example/tests/` (with supertest)
1446
+ - Combined result: 100% coverage
1447
+
1448
+ **This is the ONLY explicit exception to the 100% coverage rule in the project.**
1449
+
1450
+ ## Documentation
1451
+
1452
+ 📖 **[Full Documentation](https://scenarist.io)** - Complete guides, API reference, and examples.
1453
+
1454
+ ## Contributing
1455
+
1456
+ See [CONTRIBUTING.md](../../CONTRIBUTING.md) for development setup and guidelines.
1457
+
1458
+ ## License
1459
+
1460
+ MIT
1461
+
1462
+ ## Related Packages
1463
+
1464
+ - **[@scenarist/core](../core)** - Core scenario management
1465
+ - **[@scenarist/express-adapter](../express-adapter)** - Express.js adapter
1466
+ - **[@scenarist/msw-adapter](../msw-adapter)** - MSW integration (used internally)
1467
+
1468
+ **Note:** The MSW adapter is used internally by this package. Users of `@scenarist/nextjs-adapter` don't need to interact with it directly.