Skip to content

Instantly share code, notes, and snippets.

@iamssen
Created June 5, 2024 04:55
Show Gist options
  • Save iamssen/779fe836baa33ae85aab2c442a80059c to your computer and use it in GitHub Desktop.
Save iamssen/779fe836baa33ae85aab2c442a80059c to your computer and use it in GitHub Desktop.
Using HTTP ETag to Control Cache in a Koa Server Example
import cors from '@koa/cors';
import Router from '@koa/router';
import fs from 'fs';
import https from 'https';
import Koa from 'koa';
import { DateTime } from 'luxon';
const app = new Koa();
const router = new Router();
let etag = (Math.random() * 1000000).toString();
let lastModifiedDate = DateTime.now().toHTTP();
router.get('/etag', async (ctx) => {
const ifNoneMatch = ctx.request.headers['if-none-match'];
if (Math.random() > 0.8) {
etag = (Math.random() * 1000000).toString();
lastModifiedDate = DateTime.now().toHTTP();
}
const notModifed =
!!ifNoneMatch &&
ifNoneMatch.substring(
ifNoneMatch.indexOf('W/') === 0 ? 3 : 1,
ifNoneMatch.length - 1,
) === etag;
if (notModifed) {
ctx.response.status = 304;
ctx.response.set('Last-Modified', lastModifiedDate);
ctx.response.set('Etag', `W/"${etag}"`);
} else {
ctx.response.set('Last-Modified', lastModifiedDate);
ctx.response.set('Etag', `W/"${etag}"`);
ctx.body = { v: etag };
}
});
app.use(cors()).use(router.routes()).use(router.allowedMethods());
https
.createServer(
{
key: fs.readFileSync(process.env.LOCALHOST_HTTPS_KEY!),
cert: fs.readFileSync(process.env.LOCALHOST_HTTPS_CERT!),
},
app.callback(),
)
.listen(9899);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment