commit | author | age
|
3038db
|
1 |
/* |
JR |
2 |
Code to serve the web app in PRODUCTION. |
|
3 |
Injects environment variables at runtime in build/index.html |
|
4 |
*/ |
1c7869
|
5 |
require("dotenv").config(); |
3038db
|
6 |
const express = require("express"); |
JR |
7 |
const path = require("path"); |
a2054f
|
8 |
const fs = require("fs").promises; |
3038db
|
9 |
const app = express(); |
a2054f
|
10 |
|
1c7869
|
11 |
const BUILD_PATH = path.join(__dirname, "build"); |
JR |
12 |
|
|
13 |
app.use(express.static(BUILD_PATH)); |
|
14 |
|
|
15 |
// Return index.html, with injected env variables |
a2054f
|
16 |
const indexFilePath = path.join(__dirname, "build", "index.html"); |
1c7869
|
17 |
app.get("/*", async(request, response) => { |
8b401c
|
18 |
log(request); |
1c7869
|
19 |
const content = await injectEnvironmentInHTml(indexFilePath); |
JR |
20 |
response.send(content); |
|
21 |
}); |
3038db
|
22 |
|
JR |
23 |
|
1c7869
|
24 |
const PORT = process.env.PORT || 8080; |
JR |
25 |
app.listen(PORT, () => { |
|
26 |
console.log(`Server listening at ${PORT}`); |
|
27 |
}); |
|
28 |
|
|
29 |
|
|
30 |
function log(req) { |
d10c64
|
31 |
console.log(`${(new Date()).toISOString()} - GET ${req.url}`); |
1c7869
|
32 |
} |
a2054f
|
33 |
|
JR |
34 |
|
1c7869
|
35 |
async function injectEnvironmentInHTml(filePath) { |
JR |
36 |
// Only consider variables starting with REACT_APP |
|
37 |
const environment = {}; |
|
38 |
Object.keys(process.env) |
|
39 |
.filter(key => key.startsWith("REACT_APP_")) |
|
40 |
.forEach(key => { |
|
41 |
environment[key] = process.env[key]; |
|
42 |
}); |
|
43 |
|
a2054f
|
44 |
const content = await fs.readFile(filePath); |
JR |
45 |
return content |
|
46 |
.toString() |
|
47 |
.replace( |
|
48 |
"__PRODUCTION_ENV__", |
1c7869
|
49 |
JSON.stringify(environment) |
a2054f
|
50 |
); |
JR |
51 |
} |