add cache-control header to font and image requests

This commit is contained in:
Sean Yesmunt 2019-12-10 17:05:30 -05:00
parent f3c5f03fa9
commit 920f480a57
2 changed files with 17 additions and 0 deletions

View file

@ -5,6 +5,7 @@ const serve = require('koa-static');
const logger = require('koa-logger'); const logger = require('koa-logger');
const router = require('./src/routes'); const router = require('./src/routes');
const redirectMiddleware = require('./middleware/redirect'); const redirectMiddleware = require('./middleware/redirect');
const cacheControlMiddleware = require('./middleware/cache-control');
const app = new Koa(); const app = new Koa();
const DIST_ROOT = path.resolve(__dirname, 'dist'); const DIST_ROOT = path.resolve(__dirname, 'dist');
@ -20,6 +21,7 @@ app.use(async (ctx, next) => {
}); });
app.use(logger()); app.use(logger());
app.use(cacheControlMiddleware);
app.use(redirectMiddleware); app.use(redirectMiddleware);
app.use(serve(DIST_ROOT)); // Check if the request url matches any assets inside of /dist app.use(serve(DIST_ROOT)); // Check if the request url matches any assets inside of /dist

View file

@ -0,0 +1,15 @@
const THREE_MONTHS_IN_SECONDS = 7776000;
async function redirectMiddleware(ctx, next) {
const {
request: { url },
} = ctx;
if (url.includes('.png') || url.includes('font.css') || url.includes('.woff')) {
ctx.set('Cache-Control', `public, max-age=${THREE_MONTHS_IN_SECONDS}`);
}
return next();
}
module.exports = redirectMiddleware;