From d4be69b85c7904d828dc9c42c6b1df4cd663594c Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Wed, 9 Aug 2023 07:00:43 +0000 Subject: [PATCH] fix(@nguniversal/common): check for server context when doing hybrid rendering Prior to this change, we did not check for the server context which is some cases caused the app-shell to be served instead of the SSR version. (cherry picked from commit 98ea74f691ce6f7c79f3dba851ce0532e296d7f7) --- modules/common/engine/src/engine.ts | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/modules/common/engine/src/engine.ts b/modules/common/engine/src/engine.ts index cf232ed74..1181bb8e8 100644 --- a/modules/common/engine/src/engine.ts +++ b/modules/common/engine/src/engine.ts @@ -18,6 +18,8 @@ import * as fs from 'fs'; import { dirname, resolve } from 'path'; import { URL } from 'url'; +const SSG_MARKER_REGEXP = /ng-server-context=["']\w*\|?ssg\|?\w*["']/; + export interface RenderOptions { bootstrap?: Type<{}> | (() => Promise); providers?: StaticProvider[]; @@ -44,7 +46,7 @@ export interface RenderOptions { export class CommonEngine { private readonly templateCache = new Map(); private readonly inlineCriticalCssProcessor: InlineCriticalCssProcessor; - private readonly pageExists = new Map(); + private readonly pageIsSSG = new Map(); constructor( private bootstrap?: Type<{}> | (() => Promise), @@ -70,13 +72,20 @@ export class CommonEngine { if (pagePath !== resolve(opts.documentFilePath)) { // View path doesn't match with prerender path. - let pageExists = this.pageExists.get(pagePath); - if (pageExists === undefined) { - pageExists = await exists(pagePath); - this.pageExists.set(pagePath, pageExists); - } - - if (pageExists) { + const pageIsSSG = this.pageIsSSG.get(pagePath); + if (pageIsSSG === undefined) { + if (await exists(pagePath)) { + const content = await fs.promises.readFile(pagePath, 'utf-8'); + const isSSG = SSG_MARKER_REGEXP.test(content); + this.pageIsSSG.set(pagePath, isSSG); + + if (isSSG) { + return content; + } + } else { + this.pageIsSSG.set(pagePath, false); + } + } else if (pageIsSSG) { // Serve pre-rendered page. return fs.promises.readFile(pagePath, 'utf-8'); }