rsnext/packages/next/server/send-payload/revalidate-headers.ts
Shu Ding c9863c8794
Reduce the size of web server (#34767)
By moving `setRevalidateHeaders` to a separate file we can shake off the dependency of `etag` and a polyfill for `Buffer` from the web server (which brings hundreds of kilobytes).

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
2022-02-24 19:53:17 +00:00

30 lines
943 B
TypeScript

import type { ServerResponse } from 'http'
import type { BaseNextResponse } from '../base-http'
import type { PayloadOptions } from './index'
export function setRevalidateHeaders(
res: ServerResponse | BaseNextResponse,
options: PayloadOptions
) {
if (options.private || options.stateful) {
if (options.private || !res.hasHeader('Cache-Control')) {
res.setHeader(
'Cache-Control',
`private, no-cache, no-store, max-age=0, must-revalidate`
)
}
} else if (typeof options.revalidate === 'number') {
if (options.revalidate < 1) {
throw new Error(
`invariant: invalid Cache-Control duration provided: ${options.revalidate} < 1`
)
}
res.setHeader(
'Cache-Control',
`s-maxage=${options.revalidate}, stale-while-revalidate`
)
} else if (options.revalidate === false) {
res.setHeader('Cache-Control', `s-maxage=31536000, stale-while-revalidate`)
}
}