| | |
| | | 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"); |
| | | const fs = require("fs").promises; |
| | | const app = express(); |
| | | |
| | | app.use(express.static(path.join(__dirname, "build"))); |
| | | const BUILD_PATH = path.join(__dirname, "build"); |
| | | |
| | | app.get("/*", function (req, res) { |
| | | const indexFilePath = path.join(__dirname, "build", "index.html"); |
| | | fs.readFile(indexFilePath, (_, content) => { |
| | | const html = content.toString() |
| | | .replace( |
| | | "{{REACT_APP_ADOPTION_SERVICE_URL}}", |
| | | process.env.REACT_APP_ADOPTION_SERVICE_URL || "" |
| | | ) |
| | | .replace( |
| | | "{{REACT_APP_ANIMAL_SERVICE_URL}}", |
| | | process.env.REACT_APP_ANIMAL_SERVICE_URL || "" |
| | | ) |
| | | .replace( |
| | | "{{REACT_APP_SHELTER_SERVICE_URL}}", |
| | | process.env.REACT_APP_SHELTER_SERVICE_URL || "" |
| | | ) |
| | | .replace( |
| | | "{{REACT_APP_NEWS_SERVICE_URL}}", |
| | | process.env.REACT_APP_NEWS_SERVICE_URL || "" |
| | | ) |
| | | .replace( |
| | | "{{REACT_APP_NEWS_ENABLED}}", |
| | | process.env.REACT_APP_NEWS_ENABLED || "" |
| | | ); |
| | | app.use(express.static(BUILD_PATH)); |
| | | |
| | | res.send(html); |
| | | }); |
| | | // 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); |
| | | }); |
| | | |
| | | app.listen(process.env.PORT || 3000); |
| | | |
| | | 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) |
| | | ); |
| | | } |