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
32 changes: 32 additions & 0 deletions packages/gatsby/src/commands/serve.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import report from "gatsby-cli/lib/reporter"
import multer from "multer"
import pathToRegexp from "path-to-regexp"
import cookie from "cookie"
import minimatch from "minimatch"

import telemetry from "gatsby-telemetry"

Expand Down Expand Up @@ -85,6 +86,36 @@ const matchPathRouter = (
return next()
}

const setCacheHeaders = (
req: express.Request,
res: express.Response,
next: express.NextFunction
): void => {
function match(pattern: string, options: minimatch.IOptions = {}): boolean {
return minimatch(req.path, pattern, options)
}

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

if ((match(`/static/**`) || match(`/**.+(js|css)`)) && !match(`/sw.js`)) {
res.header(
`Cache-control`,
`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 All @@ -110,6 +141,7 @@ module.exports = async (program: IServeProgram): Promise<void> => {
app.use(telemetry.expressMiddleware(`SERVE`))

router.use(compression())
app.use(setCacheHeaders)
router.use(express.static(`public`, { dotfiles: `allow` }))
const matchPaths = await readMatchPaths(program)
router.use(matchPathRouter(matchPaths, { root }))
Expand Down