Merge pull request #1708 from LemmyNet/cache-control

Cache static data for a day
This commit is contained in:
SleeplessOne1917 2023-06-29 14:19:07 -04:00 committed by GitHub
commit df39e0fe5d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 14 deletions

View file

@ -20,7 +20,13 @@ const [hostname, port] = process.env["LEMMY_UI_HOST"]
server.use(express.json());
server.use(express.urlencoded({ extended: false }));
server.use(getStaticDir(), express.static(path.resolve("./dist")));
server.use(
getStaticDir(),
express.static(path.resolve("./dist"), {
maxAge: 24 * 60 * 60 * 1000, // 1 day
immutable: true,
})
);
server.use(setCacheControl);
if (!process.env["LEMMY_UI_DISABLE_CSP"] && !process.env["LEMMY_UI_DEBUG"]) {

View file

@ -1,4 +1,4 @@
import type { NextFunction, Response } from "express";
import type { NextFunction, Request, Response } from "express";
import { UserService } from "../shared/services";
export function setDefaultCsp({
@ -18,24 +18,32 @@ export function setDefaultCsp({
// Set cache-control headers. If user is logged in, set `private` to prevent storing data in
// shared caches (eg nginx) and leaking of private data. If user is not logged in, allow caching
// all responses for 60 seconds to reduce load on backend and database. The specific cache
// all responses for 5 seconds to reduce load on backend and database. The specific cache
// interval is rather arbitrary and could be set higher (less server load) or lower (fresher data).
//
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
export function setCacheControl({
res,
next,
}: {
res: Response;
next: NextFunction;
}) {
export function setCacheControl(
req: Request,
res: Response,
next: NextFunction
) {
const user = UserService.Instance;
let caching: string;
if (
req.path.match(/\.(js|css|txt|manifest\.webmanifest)\/?$/) ||
req.path.includes("/css/themelist")
) {
// Static content gets cached publicly for a day
caching = "public, max-age=86400";
} else {
if (user.auth()) {
caching = "private";
} else {
caching = "public, max-age=60";
caching = "public, max-age=5";
}
}
res.setHeader("Cache-Control", caching);
next();

View file

@ -24,7 +24,7 @@ export async function createSsrHtml(
if (!appleTouchIcon) {
appleTouchIcon = site?.site_view.site.icon
? `data:image/png;base64,${sharp(
? `data:image/png;base64,${await sharp(
await fetchIconPng(site.site_view.site.icon)
)
.resize(180, 180)