Blog>
Snippets

Angular Universal Custom Express Middleware

Show how to create custom Express middleware to handle specific server-side logic before Angular handles the rendering.
const express = require('express');
const app = express();
Require the Express module and create an Express application instance.
app.use((req, res, next) => {
  // Custom logic can go here
  console.log(`Request made to: ${req.originalUrl}`);

  // If the middleware function does not end the request-response cycle,
  // it must call `next()` to pass control to the next middleware function.
  // Otherwise the request will be left hanging.
  next();
});
Define a custom middleware function that logs the original URL of each request and then uses 'next()' to pass control to the next middleware function.
app.get('/specific-route', (req, res, next) => {
  // Implement custom logic for a specific route
  res.send('This is the response from the specific route.');
});
Create a specific route with its own middleware logic to customize the server's response for that route.
const { ngExpressEngine } = require('@nguniversal/express-engine');
const { AppServerModuleNgFactory } = require('./dist/server/main');

// Set up Angular Universal for server-side rendering
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory
}));

app.set('view engine', 'html');
app.set('views', 'dist/browser');

// Handle requests for routes not handled by the specified middleware with Angular
app.get('*', (req, res) => {
  res.render('index', { req, res });
});
Configure Angular Universal by setting an express engine with ngExpressEngine and linking the server's main module. Finally, define a wildcard route to render the application using Angular Universal for any routes not caught by earlier middleware.
const PORT = process.env.PORT || 4000;

// Start the Express server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});
Set the port for the server to listen on and start the server.