Skip to content

Commit e9a2648

Browse files
committed
use microMatch
1 parent 31cc65a commit e9a2648

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

packages/gatsby/src/commands/serve.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { match as reachMatch } from "@gatsbyjs/reach-router"
88
import onExit from "signal-exit"
99
import report from "gatsby-cli/lib/reporter"
1010
import telemetry from "gatsby-telemetry"
11+
import { isMatch, Options as MicroMatchOptions } from "micromatch"
1112

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

102+
const setCacheHeaders = (
103+
req: express.Request,
104+
res: express.Response,
105+
next: express.NextFunction
106+
): void => {
107+
function match(
108+
pattern: string | ReadonlyArray<string>,
109+
options?: MicroMatchOptions
110+
): boolean {
111+
return isMatch(req.path, pattern, options)
112+
}
113+
114+
if (req.method !== `GET`) {
115+
next()
116+
return
117+
}
118+
119+
if ((match(`/static/**`) || match(`/**.+(js|css)`)) && !match(`/sw.js`)) {
120+
res.header(`Cache-control`, `public, max-age=31536000, immutable`)
121+
122+
next()
123+
return
124+
}
125+
126+
res.header(`Cache-control`, `public, max-age=0, must-revalidate`)
127+
128+
next()
129+
return
130+
}
131+
101132
module.exports = async (program: IServeProgram): Promise<void> => {
102133
telemetry.trackCli(`SERVE_START`)
103134
telemetry.startBackgroundUpdate()
@@ -132,6 +163,7 @@ module.exports = async (program: IServeProgram): Promise<void> => {
132163
app.use(telemetry.expressMiddleware(`SERVE`))
133164

134165
router.use(compression())
166+
app.use(setCacheHeaders)
135167

136168
router.use(
137169
configureTrailingSlash(

0 commit comments

Comments
 (0)