commit | author | age
|
bae328
|
1 |
/* |
JR |
2 |
Code to serve the web app in PRODUCTION. |
|
3 |
Injects environment variables at runtime in build/index.html |
|
4 |
*/ |
|
5 |
require("dotenv").config(); |
|
6 |
const express = require("express"); |
|
7 |
const path = require("path"); |
|
8 |
const fs = require("fs").promises; |
|
9 |
const app = express(); |
|
10 |
|
|
11 |
const BUILD_PATH = path.join(__dirname, "build"); |
|
12 |
const INDEX_FILEPATH = path.join(__dirname, "build", "index.html"); |
|
13 |
|
|
14 |
|
|
15 |
// Setup server (Middlewares are evaluated in order) |
|
16 |
|
|
17 |
app.use(log); |
|
18 |
|
|
19 |
// First, if route is /frontend, we serve index.html with env variables |
|
20 |
app.use(async(req, res, next) => { |
|
21 |
if (req.url === "/frontend" || req.url === "/frontend/") { |
|
22 |
sendIndexWithEnv(req, res); |
|
23 |
} else { |
|
24 |
next(); |
|
25 |
} |
|
26 |
}); |
|
27 |
|
|
28 |
// Serve the file if the route is a static file (css, js...) |
|
29 |
app.use("/frontend", express.static(BUILD_PATH)); |
|
30 |
|
|
31 |
// For the rest of paths we also serve index.html with env variables |
|
32 |
app.get("/*", sendIndexWithEnv); |
|
33 |
|
|
34 |
|
|
35 |
const PORT = process.env.PORT || 8080; |
|
36 |
app.listen(PORT, () => { |
|
37 |
console.log(`Server listening at ${PORT}`); |
|
38 |
}); |
|
39 |
|
|
40 |
|
|
41 |
function log(req, res, next) { |
|
42 |
console.log(`${(new Date()).toISOString()} - GET ${req.url}`); |
|
43 |
next(); |
|
44 |
} |
|
45 |
|
|
46 |
|
|
47 |
async function sendIndexWithEnv(request, response) { |
|
48 |
// Only consider variables starting with REACT_APP |
|
49 |
const environment = {}; |
|
50 |
Object.keys(process.env) |
|
51 |
.filter(key => key.startsWith("REACT_APP_")) |
|
52 |
.forEach(key => { |
|
53 |
environment[key] = process.env[key]; |
|
54 |
}); |
|
55 |
|
|
56 |
const content = (await fs.readFile(INDEX_FILEPATH)) |
|
57 |
.toString() |
|
58 |
.replace( |
|
59 |
"__PRODUCTION_ENV__", |
|
60 |
JSON.stringify(environment) |
|
61 |
); |
|
62 |
|
|
63 |
response.send(content); |
|
64 |
} |