Search code examples
next.jsstaticsingle-page-applicationassets

How to host Next JS built index.html separately from other static assets?


I have a Next JS SPA (no server-side code), which after next build produces index.html along with other static assets (JS chunks, images etc.) in the _next folder as usual. See image below for the folder structure.

build folder structure

I need to render this SPA during a particular flow of a commercial product. Due to constraints of that environment, I must host the index.html on that environment but must host the other static assets elsewhere (e.g. a public S3 bucket)

Will this kind of a setup work just by changing all relative paths inside index.html to absolute paths pointing to the static assets?

For e.g.

Original relative URL in index.html:

<script src="/_next/static/chunks/961-e6437325a155ddfa.js" async=""></script>

Manually rewritten absolute URL:

<script src="https://s3.amazonaws.com/my-public-bucket/_next/static/chunks/961-e6437325a155ddfa.js" async=""></script>

If not, how to make this kind of a distributed setup work?


Solution

  • Thanks to the Vercel engineer who pointed me to this config:

    const isProd = process.env.NODE_ENV === 'production'
     
    module.exports = {
      // Use the CDN in production and localhost for development.
      assetPrefix: isProd ? 'https://cdn.mydomain.com' : undefined,
    }
    

    Ref: https://nextjs.org/docs/app/api-reference/next-config-js/assetPrefix