angular setting up server side rendering setup

To setup ssr on a new project, simply run the following command 

ng new --ssr

and to setup existing project 

ng add @angular/ssr

Let's check src/app/app.config.ts file where we have provideClientHydration added. 


export const appConfig: ApplicationConfig = {
  providers: [provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(withEventReplay())]
};

To start running your server, run the following command and you will get the outputs shown here

ng build 




Noticed that server..mjs is generated and if you look at your package.json, it uses node + express to run your server app. Go ahead and run the following command:- 

npm run serve:ssr:myssr

Then go to your chrome browser and then locate localhost, you will see the response. Notice that the html,css and images is return by the web server. 




Looking at server.ts file, we noticed that if route request for static file goes to browser dist folder 

/**
 * Serve static files from /browser
 */
app.use(
  express.static(browserDistFolder, {
    maxAge: '1y',
    index: false,
    redirect: false,
  }),
);

All other requested are routed server side. So this means, if you request for http://localhost:4000/index.html - it does not goes here. 

/**
 * Handle all other requests by rendering the Angular application.
 */
app.use('/**', (req, res, next) => {
  console.log('server side rendering')
  angularApp
    .handle(req)
    .then((response) =>
      response ? writeResponseToNodeResponse(response, res) : next(),
    )
    .catch(next);
});






Comments

Popular posts from this blog

The specified initialization vector (IV) does not match the block size for this algorithm

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20