One way to accomplish this is to use Angular Universal to do your initial render server-side via Node.
As part of your Angular Universal setup, you'll have a server.ts file, which can read any environment variables you need. I chose Nunjucks for this example to render the index.html from the Angular application (I'm sure you can use EJS or another templating engine).
// server.ts
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import * as nunjucks from 'nunjucks';
import { renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';
import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
// Express server
const app = express();
const PORT = process.env.PORT || 4201;
const DIST_FOLDER = join(process.cwd(), 'dist');
// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'index.html')).toString();
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist-server/main.bundle');
const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');
nunjucks.configure(DIST_FOLDER, {
autoescape: true,
express: app,
});
app.engine('html', (_, options, callback) => {
renderModuleFactory(AppServerModuleNgFactory, {
// Our index.html
document: template,
url: options.req.url,
// DI so that we can get lazy-loading to work differently (since we need it to just instantly render it)
extraProviders: [
provideModuleMap(LAZY_MODULE_MAP)
]
}).then(html => {
callback(null, html);
});
});
app.set('view engine', 'html');
// Server static files from dist folder
app.get('*.*', express.static(DIST_FOLDER));
// All regular routes use the Universal engine
// You can pass in server-side values here to have Nunjucks render them
app.get('*', (req, res) => {
res.render('index', { req, someValue: process.env.someValue });
});
// Start up the Node server
app.listen(PORT);
In your index.html, you can output the server-side variables wherever you need. I chose to assign a value to the window
here called environment
.
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" />
...
</head>
<body>
<app-root></app-root>
<script>
window['environment'] = {
someValue: '{{ someValue }}',
};
</script>
</body>
</html>
Subsequently in Angular components, services, etc, you can access the value via window['environment'].someValue