Angular Universal doesn't serve static assets

Viewed 550

I run simple Angular Universal SSR (server-side rendering) application, everything works fine, server renders html but there is one problem. static assets, like fonts, images, icons doesn't get loaded by server, but browser. What I want to do, is to render html with static assets.

I tried express.static() function but couldn't make it work. So how can I make it work?

1 Answers

Got it working by suggestions here.

Implement HTTP interceptor according to this article. It will add absolute url to all requests with a relative path, so SSR with server running will work. But while static pre-rendering this.request will be empty, in this case you should redirect such requests to your own static server, e.g. http://localhost:3000

Create NodeJs script for pre-rendering. It will run static server on port 3000 (the same port as in interceptor), when it's running, you can execute npm run prerender in child process. Then listen to events error and close on the subprocess and close server when they happen:

const { spawn } = require('child_process');

// In static server 'listen' callback
const sp = spawn('npm', ['run', 'prerender'], { stdio: 'inherit', timeout: 5 * 60 * 1000 })
sp.on('error', (err) => {
    // Pre-rendering failed.
    // TODO kill subprocess, close server, end current process with error code
});
sp.on('exit', (code: number) => {
  // Pre-rendering is finished
  // TODO Close server
  
  if (code !== 0) {
    // Pre-rendering failed.
    // TODO End current process with error code
  }
})
Related