In Vue and React, this isn’t usually a problem. They don’t break SEO with non-existent tags. I’m new to Angular SSR, and when I tried it, I was horrified. It feels like Angular considers leaving trash behind as normal. Maybe I missed a setting, but I haven’t found anyone else acknowledging this issue. Even tutorials on YouTube do SSR without addressing this.
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import bootstrap from './src/main.server';
/* HACK for remove angular trash code
TODO need to understand how to do it with default functional of */
function modifyHtml(html: string): string {
html = html.replace(/<app-root([^>]*)>([sS]*?)</app-root>/g, '<div id="root"$1>$2</div>');
html = html.replace(/<(/?app-w+|router-w+)[^>]*>/g, '');
return html;
}
/* The Express app is exported so that it can be used by serverless Functions. */
export function app(): express.Express {
const server = express();
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', browserDistFolder);
// All regular routes use the Angular engine
server.get('**', async (req, res, next) => {
const { protocol, headers, originalUrl, baseUrl } = req;
try {
const renderedHtml = await commonEngine.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
});
// modify before send client
const modifiedHtml = modifyHtml(renderedHtml);
res.send(modifiedHtml);
} catch (err) {
next(err);
}
});
return server;
}
function run(): void {
const port = process.env['PORT'] || 8082;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
run();
Thank you in advance for your advice. GPT and official documentation haven’t helped much either. If I missed something, I apologize.