Jaime Ramírez
2020-06-03 8b401ce6cb754d4cde758d5d96cffc28d3456331
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
/*
Code to serve the web app in PRODUCTION.
Injects environment variables at runtime in build/index.html
*/
require("dotenv").config();
const express = require("express");
const path = require("path");
const fs = require("fs").promises;
const app = express();
 
const BUILD_PATH = path.join(__dirname, "build");
 
app.use(express.static(BUILD_PATH));
 
// Return index.html, with injected env variables
const indexFilePath = path.join(__dirname, "build", "index.html");
app.get("/*", async(request, response) => {
    log(request);
    const content = await injectEnvironmentInHTml(indexFilePath);
    response.send(content);
});
 
 
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
    console.log(`Server listening at ${PORT}`);
});
 
 
function log(req) {
    console.log(`${(new Date()).toISOString()} - GET ${req.url}`);
}
 
 
async function injectEnvironmentInHTml(filePath) {
    // Only consider variables starting with REACT_APP
    const environment = {};
    Object.keys(process.env)
        .filter(key => key.startsWith("REACT_APP_"))
        .forEach(key => {
            environment[key] = process.env[key];
        });
 
    const content = await fs.readFile(filePath);
    return content
        .toString()
        .replace(
            "__PRODUCTION_ENV__",
            JSON.stringify(environment)
        );
}