Skip to content

Commit 06dc928

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 b5ad027 commit 06dc928

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
@@ -93,7 +93,7 @@ export default class UnboxApp {
9393
try {
9494
await next()
9595
} finally {
96-
console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}"`)
96+
console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}" "${ctx.headers['cache-control']}"`)
9797
}
9898
})
9999

@@ -115,6 +115,17 @@ export default class UnboxApp {
115115

116116
ctx.set('Cache-Control', `max-age=1`)
117117

118+
const ctxFresh = () => {
119+
if (this.options.nginx?.cache?.support_bypass) {
120+
// ctx fresh uses https://github.com/jshttp/fresh/blob/v0.5.2/index.js#L43-L49
121+
// which always honors `Cache-Control: no-cache` in the request header
122+
return ctx.fresh
123+
} else {
124+
const modifiedSince = ctx.request.headers['if-modified-since']
125+
return !!modifiedSince && modifiedSince === ctx.response.headers['last-modified']
126+
}
127+
}
128+
118129
// Front page
119130
if (request_path === '/') {
120131
// Allow the IF Archive admins to direct us to update the index as soon as it changes
@@ -214,7 +225,7 @@ export default class UnboxApp {
214225
// Send and check the Last-Modified/If-Modified-Since headers
215226
ctx.status = 200
216227
ctx.lastModified = new Date(details.date)
217-
if (ctx.fresh) {
228+
if (ctxFresh()) {
218229
ctx.status = 304
219230
return
220231
}
@@ -375,7 +386,7 @@ export default class UnboxApp {
375386
// Send and check the Last-Modified/If-Modified-Since headers
376387
ctx.status = 200
377388
ctx.lastModified = new Date(details.date)
378-
if (ctx.fresh) {
389+
if (ctxFresh()) {
379390
ctx.status = 304
380391
return
381392
}

0 commit comments

Comments
 (0)