CDN Support with Asset Prefix

Attention: Deploying to Vercel automatically configures a global CDN for your Next.js project. You do not need to manually setup an Asset Prefix.

Note: Next.js 9.5+ added support for a customizable Base Path, which is better suited for hosting your application on a sub-path like /docs. We do not suggest you use a custom Asset Prefix for this use case.

To set up a CDN, you can set up an asset prefix and configure your CDN’s origin to resolve to the domain that Next.js is hosted on.

Open next.config.js and add the assetPrefix config:

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

Next.js will automatically use your asset prefix for the JavaScript and CSS files it loads from the /_next/ path (.next/static/ folder).

Asset prefix support does not influence the following paths:

  • Files in the public folder; if you want to serve those assets over a CDN, you’ll have to introduce the prefix yourself
  • /_next/data/ requests for getServerSideProps pages. These requests will always be made against the main domain since they’re not static.
  • /_next/data/ requests for getStaticProps pages. These requests will always be made against the main domain to support Incremental Static Generation, even if you’re not using it (for consistency).

Related

[

Introduction to next.config.js

Learn more about the configuration file used by Next.js.]($0b4bd5a3a6817758.md)

[

Static File Serving

Serve static files, like images, in the public directory.]($c25a43623c617a9a.md)