简体   繁体   中英

CDN caching for React.JS SSR

I have the below code to do my server-side rending:

// Load in our HTML file from our build
fs.readFile(
  path.resolve(__dirname, '../build/index.html'),
  'utf8',
  (err, htmlData) => {
    // If there's an error... serve up something nasty
    ...
    // Pass all this nonsense into our HTML formatting function above
    const html = injectHTML(htmlData, {
      html: helmet.htmlAttributes.toString(),
      title: helmet.title.toString(),
      meta: helmet.meta.toString(),
      headScript: helmet.script.toString(),
      link: helmet.link.toString(),
      body: routeMarkup,
      scripts: extraChunks,
      state: JSON.stringify(store.getState()).replace(/</g, '\\u003c')
    });
    // We have all the final HTML, let's send it to the user already!
    res.send(html);

It is working fine. However, all my static assets are loaded from ../build . I want to connect a CDN, such as S3 to cache assets.

To do this, I need to prepend the CDN url to links to static assets so <script src="/static/js/main.7e3b844f.chunk.js"></script> becomes <script src="https://cdn.mydomain.com/static/js/main.7e3b844f.chunk.js"></script>

The urls of interest are inside htmlData . I could use regular expressions to replace /static/css with ${prefix}/static/css and the same for /static/js .

Are there better alternatives than running a regex? Suggestoins?

I ended-up doing the below before injecting HTML with body, meta etc:

const prefix =
  process.env.REACT_APP_STAGE === 'production'
    ? 'https://prod-cdn.mydomain.com'
    : '';
const processedHtmlData = htmlData.replace(
  /(\/static)/g,
  `${prefix}$1`
);
const html = injectHTML(processedHtmlData, {
  html: helmet.htmlAttributes.toString(),
  title: helmet.title.toString(),
  meta: helmet.meta.toString(),
  headScript: helmet.script.toString(),
  link: helmet.link.toString(),
  body: routeMarkup,
  scripts: extraChunks,
  state: JSON.stringify(store.getState()).replace(/</g, '\\u003c')
});

It works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM