Skip to content

Commit 2d78902

Browse files
committed
Only allow client to force unconditional request if options permit it
Koa's `ctx.fresh` uses https://github.com/jshttp/fresh/blob/v0.5.2/index.js#L43-L49 which always honors `Cache-Control: no-cache` in the request header. That's unfortunate, because Chrome passes a `Cache-Control: no-cache` request header if you check "Disable cache" in Chrome Dev Tools, making it difficult/confusing to verify that nginx conditional requests are working. In this commit, we use `ctx.fresh` only if our `options` object allows nginx itself to support bypassing the cache. If we don't support clients bypassing the cache, then we'll return `304 Not Modified` if `if-modified-since` matches `last-modified`, regardless of what other headers the client sends.
1 parent 498782d commit 2d78902

File tree

1 file changed

+14
-3
lines changed

1 file changed

+14
-3
lines changed

app/src/app.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ export default class UnboxApp {
9191

9292
this.app.use(async (ctx, next) => {
9393
await next();
94-
console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}"`)
94+
console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}" "${ctx.headers['cache-control']}"`)
9595
})
9696

9797
// And the main handler
@@ -112,6 +112,17 @@ export default class UnboxApp {
112112

113113
ctx.set('Cache-Control', `max-age=1`)
114114

115+
const ctxFresh = () => {
116+
if (this.options.nginx?.cache?.support_bypass) {
117+
// ctx fresh uses https://github.com/jshttp/fresh/blob/v0.5.2/index.js#L43-L49
118+
// which always honors `Cache-Control: no-cache` in the request header
119+
return ctx.fresh
120+
} else {
121+
const modifiedSince = ctx.request.headers['if-modified-since']
122+
return !!modifiedSince && modifiedSince === ctx.response.headers['last-modified']
123+
}
124+
}
125+
115126
// Front page
116127
if (request_path === '/') {
117128
// Allow the IF Archive admins to direct us to update the index as soon as it changes
@@ -211,7 +222,7 @@ export default class UnboxApp {
211222
// Send and check the Last-Modified/If-Modified-Since headers
212223
ctx.status = 200
213224
ctx.lastModified = new Date(details.date)
214-
if (ctx.fresh) {
225+
if (ctxFresh()) {
215226
ctx.status = 304
216227
return
217228
}
@@ -372,7 +383,7 @@ export default class UnboxApp {
372383
// Send and check the Last-Modified/If-Modified-Since headers
373384
ctx.status = 200
374385
ctx.lastModified = new Date(details.date)
375-
if (ctx.fresh) {
386+
if (ctxFresh()) {
376387
ctx.status = 304
377388
return
378389
}

0 commit comments

Comments
 (0)