Skip to content

Commit

Permalink
Only allow client to force unconditional request if options permit it
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dfabulich committed Dec 4, 2024
1 parent b5ad027 commit 06dc928
Showing 1 changed file with 14 additions and 3 deletions.
17 changes: 14 additions & 3 deletions app/src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export default class UnboxApp {
try {
await next()
} finally {
console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}"`)
console.log(`${ctx.method} ${ctx.url} ${ctx.status} "${ctx.headers['if-modified-since']}" "${ctx.headers['cache-control']}"`)
}
})

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

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

const ctxFresh = () => {
if (this.options.nginx?.cache?.support_bypass) {
// 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
return ctx.fresh
} else {
const modifiedSince = ctx.request.headers['if-modified-since']
return !!modifiedSince && modifiedSince === ctx.response.headers['last-modified']
}
}

// Front page
if (request_path === '/') {
// Allow the IF Archive admins to direct us to update the index as soon as it changes
Expand Down Expand Up @@ -214,7 +225,7 @@ export default class UnboxApp {
// Send and check the Last-Modified/If-Modified-Since headers
ctx.status = 200
ctx.lastModified = new Date(details.date)
if (ctx.fresh) {
if (ctxFresh()) {
ctx.status = 304
return
}
Expand Down Expand Up @@ -375,7 +386,7 @@ export default class UnboxApp {
// Send and check the Last-Modified/If-Modified-Since headers
ctx.status = 200
ctx.lastModified = new Date(details.date)
if (ctx.fresh) {
if (ctxFresh()) {
ctx.status = 304
return
}
Expand Down

0 comments on commit 06dc928

Please sign in to comment.