]> Untitled Git - lemmy-ui.git/blob - src/server/middleware.ts
v0.18.1-rc.8
[lemmy-ui.git] / src / server / middleware.ts
1 import type { NextFunction, Request, Response } from "express";
2 import { hasJwtCookie } from "./utils/has-jwt-cookie";
3
4 export function setDefaultCsp({
5   res,
6   next,
7 }: {
8   res: Response;
9   next: NextFunction;
10 }) {
11   res.setHeader(
12     "Content-Security-Policy",
13     `default-src 'self'; manifest-src *; connect-src *; img-src * data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; form-action 'self'; base-uri 'self'; frame-src *; media-src * data:`
14   );
15
16   next();
17 }
18
19 // Set cache-control headers. If user is logged in, set `private` to prevent storing data in
20 // shared caches (eg nginx) and leaking of private data. If user is not logged in, allow caching
21 // all responses for 5 seconds to reduce load on backend and database. The specific cache
22 // interval is rather arbitrary and could be set higher (less server load) or lower (fresher data).
23 //
24 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
25 export function setCacheControl(
26   req: Request,
27   res: Response,
28   next: NextFunction
29 ) {
30   if (process.env.NODE_ENV !== "production") {
31     return next();
32   }
33
34   let caching: string;
35
36   if (
37     req.path.match(/\.(js|css|txt|manifest\.webmanifest)\/?$/) ||
38     req.path.includes("/css/themelist")
39   ) {
40     // Static content gets cached publicly for a day
41     caching = "public, max-age=86400";
42   } else {
43     if (hasJwtCookie(req)) {
44       caching = "private";
45     } else {
46       caching = "public, max-age=5";
47     }
48   }
49
50   res.setHeader("Cache-Control", caching);
51
52   next();
53 }