8. Bonus: How to Test Caching Behavior?
You shouldn't rely on manual refreshing to test caching. Here is how I automate it.
1. Check Response Headers
Next.js adds a custom header x-nextjs-cache.
HIT: Served from cache.
MISS: Fetched from origin.
STALE: Served from cache but revalidating in background.
You can write an E2E test (Playwright/Cypress) to check this header.
test('should serve cached content', async ({ request }) => {
const response = await request.get('/api/banners');
expect(response.headers()['x-nextjs-cache']).toBe('HIT');
});
2. Time-Based Testing
If you set revalidate: 60, your test should:
- Fetch data (MISS) -> Record timestamp A.
- Fetch again immediately (HIT) -> Body should be same as A.
- Wait 61 seconds.
- Fetch again (STALE/MISS) -> Body should be different (Timestamp B).
Writing these tests ensures you don't accidentally break caching logic when refactoring code. Next.js caching is "Implicit", so explicit tests are your only safety net.