Home > Blockchain >  Prerender dynamic routes on Lambda and save on s3
Prerender dynamic routes on Lambda and save on s3

Time:11-21

I have enabled angular universal in my application and am able to do prerendering for some static routes (like home page, about, etc).

Now I also need to prerender some extra routes, but I need to be able to do this whenever it is needed, after the website has already been deployed. A live use-case would be if Airbnb wanted to prerender the new ads when people posted them.

I was thinking to have a Lambda function that I could trigger (when the ad is added for this example) that would run prerendering, then save the index.html file on the s3 bucket (I have CloudFront already on top of that).

But how to actually generate the files on Lambda? I am currently doing it at build time using:

ng run my-app:prerender

Note: I do not want to serve the files from the lambda, I want to generate them (prerender) and save on s3

CodePudding user response:

I managed to make it work by reading the source code of the universal prerendering package, and here is what works:

const { resolve, join } = require('path');
const { setup, render } = require('@nguniversal/builders/src/prerender/worker.js');

const [ route ] = process.argv.slice(2);

const ROOT = resolve(__dirname);
const outputPath = join(ROOT, 'dist', 'browser');
const serverBundlePath = join(ROOT, 'dist', 'server', 'main.js');

setup({
  indexFile: 'index.html',
  deployUrl: '',
  inlineCriticalCss: true,
  minifyCss: true
});

render(outputPath, serverBundlePath, route).then(() => {
  console.log('Build', route, 'done');
  process.exit(0);
}).catch(err => {
  console.error(err);
  process.exit(1);
});

After running once npm run prerender (like explained in the Angular tutorials), I can now prerender any route by just doing node prerender.js /my-route

  • Related