`GenerateEtags` Config Is Ignored For `Next/Image` Responses
When `generateEtags: false` is set in next.config.js, static assets and pages respect the setting and omit ETag headers, but optimized image responses from `/_next/image` still include an ETag, causing inconsistent caching behavior.
The image optimization route (`next/image`) does not consult the `nextConfig.generateEtags` setting when constructing response headers, and unconditionally generates and sets the ETag header.
1. Create a Next.js project and set `generateEtags: false` in next.config.js.
2. Run `npm run build && npm start` to start the production server.
3. Request a static asset (e.g., `/_next/static/chunks/<hash>.js`) and observe that no ETag header is present.
4. Request an optimized image (e.g., `/_next/image?url=%2Ftest.jpg&w=256&q=75`) and observe that an ETag header is present.
Fixing Code Block
// In packages/next/src/server/image-optimizer.ts
// Locate the imageOptimizer function and modify the response header generation to respect generateEtags.
// Example patch:
import { NextConfig } from '../../server/config-shared'
import { getHash } from '../../lib/hash'
export async function imageOptimizer(
req: IncomingMessage,
res: ServerResponse,
params: ImageParams,
nextConfig: NextConfig
) {
try {
const { buffer, contentType, maxAge, etag, isStatic, isAnimated } = await optimizeImage(params)
if (contentType) {
res.setHeader('Content-Type', contentType)
}
if (maxAge) {
res.setHeader('Cache-Control', `public, max-age=${maxAge}, immutable`)
}
// Only set ETag if generateEtags is not explicitly disabled
if (etag && nextConfig.generateEtags !== false) {
res.setHeader('ETag', `"${etag}"`)
}
res.end(buffer)
} catch (err) {
res.statusCode = 500
res.end('Internal Server Error')
}
}
The fix adds a conditional check before setting the ETag header in the image optimization response. It uses `nextConfig.generateEtags` (which defaults to true) to decide whether to include the ETag. This mirrors the behavior already implemented for static assets and pages.
Edge Case Audit
This patch assumes that `nextConfig` is available in the image optimizer and that the ETag is generated elsewhere. If the actual code structure differs, the patch may need adjustment. Disabling ETags could affect caching intermediaries that rely on ETag for revalidation, potentially leading to stale cache entries or unnecessary re-fetches. Apply the patch in a staging environment, test with various image requests, and keep a rollback plan (revert the conditional) if issues arise.