1- import { APP_BASE_HREF } from '@angular/common' ;
2- import { CommonEngine , isMainModule } from '@angular/ssr/node' ;
1+ import {
2+ AngularNodeAppEngine ,
3+ createNodeRequestHandler ,
4+ isMainModule ,
5+ writeResponseToNodeResponse ,
6+ } from '@angular/ssr/node' ;
37import express from 'express' ;
4- import { dirname , join , resolve } from 'node:path' ;
5- import { fileURLToPath } from 'node:url' ;
6- import bootstrap from './main.server' ;
8+ import { join } from 'node:path' ;
79
8- const serverDistFolder = dirname ( fileURLToPath ( import . meta. url ) ) ;
9- const browserDistFolder = resolve ( serverDistFolder , '../browser' ) ;
10- const indexHtml = join ( serverDistFolder , 'index.server.html' ) ;
10+ const browserDistFolder = join ( import . meta. dirname , '../browser' ) ;
1111
1212const app = express ( ) ;
13- const commonEngine = new CommonEngine ( ) ;
13+ const angularApp = new AngularNodeAppEngine ( ) ;
1414
1515/**
1616 * Example Express Rest API endpoints can be defined here.
@@ -27,30 +27,24 @@ const commonEngine = new CommonEngine();
2727/**
2828 * Serve static files from /browser
2929 */
30- app . get (
31- '**' ,
30+ app . use (
3231 express . static ( browserDistFolder , {
3332 maxAge : '1y' ,
34- index : 'index.html' ,
35- } )
33+ index : false ,
34+ redirect : false ,
35+ } ) ,
3636) ;
3737
3838/**
3939 * Handle all other requests by rendering the Angular application.
4040 */
41- app . get ( '**' , ( req , res , next ) => {
42- const { protocol, originalUrl, baseUrl, headers } = req ;
43-
44- commonEngine
45- . render ( {
46- bootstrap,
47- documentFilePath : indexHtml ,
48- url : `${ protocol } ://${ headers . host } ${ originalUrl } ` ,
49- publicPath : browserDistFolder ,
50- providers : [ { provide : APP_BASE_HREF , useValue : baseUrl } ] ,
51- } )
52- . then ( ( html ) => res . send ( html ) )
53- . catch ( ( err ) => next ( err ) ) ;
41+ app . use ( ( req , res , next ) => {
42+ angularApp
43+ . handle ( req )
44+ . then ( ( response ) =>
45+ response ? writeResponseToNodeResponse ( response , res ) : next ( ) ,
46+ )
47+ . catch ( next ) ;
5448} ) ;
5549
5650/**
@@ -59,9 +53,16 @@ app.get('**', (req, res, next) => {
5953 */
6054if ( isMainModule ( import . meta. url ) ) {
6155 const port = process . env [ 'PORT' ] || 4000 ;
62- app . listen ( port , ( ) => {
56+ app . listen ( port , ( error ) => {
57+ if ( error ) {
58+ throw error ;
59+ }
60+
6361 console . log ( `Node Express server listening on http://localhost:${ port } ` ) ;
6462 } ) ;
6563}
6664
67- export default app ;
65+ /**
66+ * Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions.
67+ */
68+ export const reqHandler = createNodeRequestHandler ( app ) ;
0 commit comments