Skip to content

feat(gatsby): add cache control headers to serve command #31591

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ Object {

exports[`production response formats returns json correctly 2`] = `
Object {
"cache-control": "public, max-age=0, must-revalidate",
"connection": "close",
"content-length": "16",
"content-type": "application/json; charset=utf-8",
Expand All @@ -92,6 +93,7 @@ exports[`production response formats returns text correctly 1`] = `"I am typescr

exports[`production response formats returns text correctly 2`] = `
Object {
"cache-control": "public, max-age=0, must-revalidate",
"connection": "close",
"content-length": "15",
"content-type": "text/html; charset=utf-8",
Expand Down
32 changes: 32 additions & 0 deletions packages/gatsby/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { match as reachMatch } from "@gatsbyjs/reach-router"
import onExit from "signal-exit"
import report from "gatsby-cli/lib/reporter"
import telemetry from "gatsby-telemetry"
import { isMatch, Options as MicroMatchOptions } from "micromatch"

import { detectPortInUseAndPrompt } from "../utils/detect-port-in-use-and-prompt"
import { getConfigFile } from "../bootstrap/get-config-file"
Expand Down Expand Up @@ -98,6 +99,36 @@ const matchPathRouter =
return next()
}

const setCacheHeaders = (
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
function match(
pattern: string | ReadonlyArray<string>,
options?: MicroMatchOptions
): boolean {
return isMatch(req.path, pattern, options)
}

if (req.method !== `GET`) {
next()
return
}

if ((match(`/static/**`) || match(`/**.+(js|css)`)) && !match(`/sw.js`)) {
res.header(`Cache-control`, `public, max-age=31536000, immutable`)

next()
return
}

res.header(`Cache-control`, `public, max-age=0, must-revalidate`)

next()
return
}

module.exports = async (program: IServeProgram): Promise<void> => {
telemetry.trackCli(`SERVE_START`)
telemetry.startBackgroundUpdate()
Expand Down Expand Up @@ -132,6 +163,7 @@ module.exports = async (program: IServeProgram): Promise<void> => {
app.use(telemetry.expressMiddleware(`SERVE`))

router.use(compression())
app.use(setCacheHeaders)

router.use(
configureTrailingSlash(
Expand Down