Blog>
Snippets

Optimizing Angular Universal Pre-rendering Performance

Show how to optimize the server response time for an Angular Universal app, which is critical for SEO, by caching pre-rendered content.
import * as cache from 'cache-manager';

// Initializing in-memory cache
const memoryCache = cache.caching({ store: 'memory', max: 100, ttl: 600 /*seconds*/ });

// Middleware to check cache before rendering
function cacheMiddleware(req, res, next) {
  const key = req.originalUrl;
  memoryCache.get(key, (err, result) => {
    if (!err && result) {
      // Cache hit, send the response
      return res.send(result);
    } else {
      // Cache miss, render the page
      res.sendResponse = res.send;
      res.send = (body) => {
        // Save the rendered page in the cache
        memoryCache.set(key, body, (error) => {
          if (error) throw error;
        });
        // Send the rendered page to the client
        res.sendResponse(body);
      };
      next();
    }
  });
}

// Use the cache middleware in your server setup
app.use(cacheMiddleware);
This code sets up an in-memory cache using the 'cache-manager' library and creates a middleware function that checks if a response for a given URL is already cached. If the response is cached, it sends the cached content to the client. If not, it proceeds with rendering the page and caches the response before sending it to the client. This middleware is then used in the server setup to cache and serve pre-rendered Angular Universal pages, improving server response time and SEO.