feat: Static File Caching (#3455)

* add static file cache

* disable compression env variable
This commit is contained in:
matt burnett 2024-08-04 21:17:59 -04:00 committed by GitHub
parent 020c4a1a0e
commit e4ac42f034
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 99 additions and 5 deletions

View file

@ -4,6 +4,7 @@ require('module-alias')({ base: path.resolve(__dirname, '..') });
const cors = require('cors');
const axios = require('axios');
const express = require('express');
const compression = require('compression');
const passport = require('passport');
const mongoSanitize = require('express-mongo-sanitize');
const { jwtLogin, passportLogin } = require('~/strategies');
@ -17,8 +18,9 @@ const configureSocialLogins = require('./socialLogins');
const AppService = require('./services/AppService');
const noIndex = require('./middleware/noIndex');
const routes = require('./routes');
const staticCache = require('./utils/staticCache');
const { PORT, HOST, ALLOW_SOCIAL_LOGIN } = process.env ?? {};
const { PORT, HOST, ALLOW_SOCIAL_LOGIN, DISABLE_COMPRESSION } = process.env ?? {};
const port = Number(PORT) || 3080;
const host = HOST || 'localhost';
@ -43,12 +45,16 @@ const startServer = async () => {
app.use(express.json({ limit: '3mb' }));
app.use(mongoSanitize());
app.use(express.urlencoded({ extended: true, limit: '3mb' }));
app.use(express.static(app.locals.paths.dist));
app.use(express.static(app.locals.paths.fonts));
app.use(express.static(app.locals.paths.assets));
app.use(staticCache(app.locals.paths.dist));
app.use(staticCache(app.locals.paths.fonts));
app.use(staticCache(app.locals.paths.assets));
app.set('trust proxy', 1); // trust first proxy
app.use(cors());
if (DISABLE_COMPRESSION !== 'true') {
app.use(compression());
}
if (!ALLOW_SOCIAL_LOGIN) {
console.warn(
'Social logins are disabled. Set Environment Variable "ALLOW_SOCIAL_LOGIN" to true to enable them.',

View file

@ -1,7 +1,8 @@
const express = require('express');
const staticCache = require('../utils/staticCache');
const paths = require('~/config/paths');
const router = express.Router();
router.use(express.static(paths.imageOutput));
router.use(staticCache(paths.imageOutput));
module.exports = router;

View file

@ -0,0 +1,19 @@
const express = require('express');
const oneWeekInSeconds = 24 * 60 * 60 * 7;
const sMaxAge = process.env.STATIC_CACHE_S_MAX_AGE || oneWeekInSeconds;
const maxAge = process.env.STATIC_CACHE_MAX_AGE || oneWeekInSeconds * 4;
const staticCache = (staticPath) =>
express.static(staticPath, {
setHeaders: (res) => {
if (process.env.NODE_ENV.toLowerCase() !== 'production') {
return;
}
res.setHeader('Cache-Control', `public, max-age=${maxAge}, s-maxage=${sMaxAge}`);
},
});
module.exports = staticCache;