-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserve.js
61 lines (50 loc) · 2.16 KB
/
serve.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
const Express = require("express");
const compression = require("compression");
const app = Express();
// Enforce the App to be visited under app.lern-fair.de (or whatever is in DOMAIN)
if (process.env.DOMAIN) {
app.use((req, res, next) => {
if (req.hostname !== process.env.DOMAIN) {
const target = "https://" + process.env.DOMAIN + req.url;
console.log("Redirecting " + req.url + " from " + req.hostname + " to " + target);
res.redirect(target);
return;
}
next();
});
}
if (!process.env.INSECURE) {
// Enforce HTTPS - The backend will reject requests from HTTP frontends anyways
app.use((req, res, next) => {
if (!req.secure && req.get('x-forwarded-proto') !== 'https') {
return res.redirect('https://' + req.get('host') + req.url);
}
next();
});
} else console.warn("Skipping HTTPS redirect!");
// Provide environment variables from the process,
// so that they can easily be switched in the deployment without rebuilding the app
// Unlike env variables starting with REACT_APP_ which are built into the minified files,
// variables prefixed with RUNTIME_ are loaded on demand
app.get('/config.js', (req, res) => {
const runtimeEnvironment = Object.fromEntries(
Object.entries(process.env)
.filter(([key]) => key.startsWith("RUNTIME_"))
);
res.end(`window.liveConfig = ${ JSON.stringify(runtimeEnvironment) };`);
});
// Compress assets with gzip for smaller responses:
app.use(compression());
// Aggressively cache assets as js and css files are different for each build anyways
// and logos, manifest et. al. also won't change often
app.use(Express.static(__dirname + '/build', {
immutable: true,
maxAge: '365 days',
fallthrough: true,
index: false
}));
// Entrypoint of the PWA - Do not cache to be able to invalidate logic changes fast
app.use((req, res) => res.sendFile(__dirname + '/build/index.html', { headers: { 'Cache-Control': 'no-cache' } }));
// Serve on the PORT Heroku wishes
const port = process.env.PORT ?? 5000;
app.listen(port, () => console.info(`Express started and listening on Port ${port}`));