Blog>
Snippets

Angular Universal Route Rendering

Demonstrate how to use Angular Router with server-side rendering to handle incoming requests and return the corresponding pre-rendered pages.
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

// Import the components that you want to route to
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { NotFoundComponent } from './not-found/not-found.component';

// Define routes
const routes: Routes = [
  { path: '', component: HomeComponent },
  { path: 'about', component: AboutComponent },
  { path: '**', component: NotFoundComponent }
];

// RouterModule with server-side configurations
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
})
export class AppRoutingModule { }
This is the AppRoutingModule where you define your routes and export them to be used with server-side rendering. An array of routes associates path patterns to components. The '**' wildcard path is for handling not-found errors (404s), and will render a NotFoundComponent.
import { NgModule } from '@angular/core';
import { ServerModule } from '@angular/platform-server';
import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    AppRoutingModule
  ],
  bootstrap: [AppComponent]
})
export class AppServerModule { }
This is the AppServerModule where you include your AppModule, the ServerModule from Angular Universal, and your AppRoutingModule. This sets up the server-side version of your app, enabling the server to handle incoming requests and return the pre-rendered pages.
import 'zone.js/dist/zone-node';
import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';
import { AppServerModule } from './src/main.server';

const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist/browser');

// Angular Express Engine
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModule,
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

// Server static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
  maxAge: '1y'
}));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});
This Express server setup uses the Angular Universal express engine to handle incoming requests. It serves static files and uses server-side rendering for regular routes. When a request is received, it renders the application using Angular Server-side Rendering and sends the pre-rendered page back to the client.