Cache API responses
You can persist API responses to make tests run faster and avoid repeating an expensive request in every worker and test run. For example, cache an upstream response for 1 hour inside a Playwright route handler:
test.use({
page: async ({ page }, use) => {
await page.route('https://api.example.com/users', async (route) => {
const users = await globalCache.get('users-api-response', { ttl: '1 hour' }, async () => {
const response = await route.fetch();
return response.json();
});
await route.fulfill({ json: users });
});
await use(page);
},
});
The upstream request is sent once. For the next hour, route handlers in the current run and subsequent runs receive the persisted response without contacting the upstream service again. After the TTL expires, the first request refreshes the value.
Dynamic params
Include every request parameter that affects the response in the cache key. This ensures each request variant gets the correct cached value:
import { test, expect } from '@playwright/test';
import { globalCache } from '@global-cache/playwright';
test.beforeEach(async ({ page }) => {
await page.route('https://api.example.com/users/*', async (route) => {
const requestUrl = new URL(route.request().url());
const userId = requestUrl.pathname.split('/').at(-1)!;
const user = await globalCache.get(`user-api-response:${userId}`, { ttl: '1 hour' }, async () => {
const response = await route.fetch();
return response.json();
});
await route.fulfill({ json: user });
});
});
test('opens user profile', async ({ page }) => {
await page.goto('/users/42');
await expect(page.getByTestId('user-id')).toHaveText('42');
});
Requests for /users/42 reuse one persistent cache entry, while /users/43 uses a separate entry
and fetches its own response. Each response can be reused by subsequent test runs for up to one hour.