{products.map(product => (
{product.name}
${(product.price / 100).toFixed(2)}
))}
);
}
```
### Testing API Routes tests/checkout.spec.ts
```typescript
test('processes payment via API route', async ({ page, switchScenario }) => {
const testId = await switchScenario(page, 'default');
// Your API route validation runs (page.request needs the test ID explicitly)
const response = await page.request.post('/api/checkout', {
headers: { 'x-scenarist-test-id': testId },
data: { amount: 5000, token: 'tok_test' },
});
expect(response.status()).toBe(200);
const data = await response.json();
expect(data.status).toBe('succeeded');
});
```
**Example API Route:** pages/api/checkout.ts
```typescript
import type { NextApiRequest, NextApiResponse } from 'next';
import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// Validation runs normally
if (!req.body.amount || !req.body.token) {
return res.status(400).json({ error: 'Missing required fields' });
}
// External API call is mocked by Scenarist
const response = await fetch('https://api.stripe.com/v1/charges', {
method: 'POST',
headers: {
...getScenaristHeaders(req),
'Authorization': `Bearer ${process.env.STRIPE_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(req.body),
});
const data = await response.json();
res.status(200).json(data);
}
```
## Forwarding Headers to External APIs **Why header forwarding matters:** When your API routes or getServerSideProps call external APIs (that you’re mocking with Scenarist), you must forward the test ID header so MSW knows which scenario to use. ### API Routes Use the `getScenaristHeaders` helper to safely extract Scenarist headers: pages/api/products.ts
```typescript
import type { NextApiRequest, NextApiResponse } from 'next';
import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// Forward Scenarist headers to external API
const response = await fetch('https://api.stripe.com/v1/products', {
headers: {
...getScenaristHeaders(req),
'Authorization': `Bearer ${process.env.STRIPE_KEY}`,
},
});
const data = await response.json();
res.status(200).json(data);
}
```
### getServerSideProps The same helper works in getServerSideProps: pages/products.tsx
```typescript
import type { GetServerSideProps } from 'next';
import { getScenaristHeaders } from '@scenarist/nextjs-adapter/pages';
export const getServerSideProps: GetServerSideProps = async ({ req }) => {
const response = await fetch('https://api.stripe.com/v1/products', {
headers: {
...getScenaristHeaders(req),
'Authorization': `Bearer ${process.env.STRIPE_KEY}`,
},
});
const { data: products } = await response.json();
return { props: { products } };
};
export default function ProductsPage({ products }) {
return (