Skip to the content.

Nuxt 4 public/ files and resized images on a CDN

Context

Research note, primary sources only. Versions installed in this worktree: nuxt 4.6.0, @nuxt/nitro-server 4.6.0, @nuxt/image 2.1.0, ipx 4.0.0-beta.1, nitropack 2.13.4, @vitejs/plugin-vue 6.0.9, @vue/compiler-sfc 3.5.43. Package paths below are relative to /path/to/project.

Repo setup at the time of writing: aws_lambda preset with serveStatic: false (core/web/nuxt.config.ts:361), app.cdnURL from NUXT_APP_CDN_URL (core/web/nuxt.config.ts:256), and server/middleware/cdn.ts 302-redirecting static paths to CloudFront. The worktree also contains an uncommitted-or-in-progress cdnIpx provider (core/web/app/providers/cdn-ipx.ts, wired at core/web/nuxt.config.ts:262-272). This note reviews that approach in the recommendations. In infra/sam/template.yaml the HTML is served by API Gateway (custom domain, :678-707), and the CloudFront distribution has a single S3 origin (:501-503). As a result, any relative URL in the HTML reaches the Lambda.

Summary

Outcome (2026-10-19)

The owner chose recommendation 4, pre-generated variants: site-media.md § Resized images on the CDN. The cdn-ipx.ts reviewed below was an earlier draft; the shipped provider has no prerender branch and snaps widths to the IPX_VARIANT_WIDTHS ladder that the build writes, so its URL is the same on server and client. Public files use recommendation 1 (usePublicAssetUrl on app.cdnURL); the 302 middleware stays as a safety net. The import.meta.prerender observation came from a build whose prerender hung partway, so it may not reflect a complete build; it no longer affects the design.

1. Does Nuxt apply app.cdnURL to public/ paths?

What cdnURL is. The docs describe it as “An absolute URL to serve the public folder from (production-only)” and say it can be overridden at runtime with NUXT_APP_CDN_URL (nuxt-config#cdnurl). The schema returns "" in dev and otherwise process.env.NUXT_APP_CDN_URL || val (@nuxt/schema/dist/index.mjs:103-106). It is copied into runtimeConfig.app.cdnURL (@nuxt/schema/dist/index.mjs:543-548). Because it is runtime config, it is readable on both server and client.

The helper. publicAssetsURL(...path) returns joinRelativeURL(app.cdnURL || app.baseURL, ...path). buildAssetsURL is the same plus buildAssetsDir (/_nuxt/).

Static literal src in a template. This one is rewritten.

  1. Nuxt’s default vue.transformAssetUrls covers img[src], video[src,poster], source[src], image[href] and use[href] (@nuxt/schema/dist/index.mjs:77-83).
  2. In a production build, @vitejs/plugin-vue sets includeAbsolute: true (@vitejs/plugin-vue/dist/index.mjs:219). The compiler then turns static attributes (attr.type === 6) with root-absolute URLs into imports (@vue/compiler-sfc/dist/compiler-sfc.cjs.js:2253-2275).
  3. Nuxt’s nuxt:vite-public-dir-resolution resolves any id that exists in public/ to a virtual module that exports publicAssetsURL("<path>") (@nuxt/vite-builder/dist/index.mjs:832-849).
  4. Vite renderBuiltUrl uses __publicAssetsURL / __buildAssetsURL at runtime for SSR (@nuxt/vite-builder/dist/index.mjs:3461-3472).

The result is that <img src="/i/x.png"> renders as https://<cdn>/i/x.png. The docs say the same: static public paths are rewritten by the build, so “a static public path works even when the base URL is only known at deploy time” (assets). Pug templates go through the same compiler after preprocessing (@vitejs/plugin-vue/dist/index.mjs:229-232), so they should be rewritten too (inferred, not tested).

Runtime-bound :src. This is not rewritten. Only static attributes are transformed (compiler check above). The docs say this directly: “A runtime-built public path like /img/${name}.png is therefore not prefixed” (assets). Paths from Nuxt Content JSON fall into this group.

<NuxtImg src>. This is not rewritten either.

CSS url(/…). Public paths in CSS are made relative to the CSS file (@nuxt/vite-builder/dist/index.mjs:864-875). Inline styles are wrapped in publicAssetsURL (:850-863). Both end up on the CDN because CSS is served from /_nuxt/ on the CDN.

2. Resized images when the server cannot read public/

Provider selection (@nuxt/image/dist/module.js:362-383):

The docs say the default is ipx, or “ipxStatic if used with a static nitro preset, such as if you are running nuxt generate” (configuration).

An external IPX disables generation. ipxSetup returns early when the IPX baseURL has a protocol, or when a user handler already owns the route. It then registers no handler (@nuxt/image/dist/module.js:17-21). Pointing image.ipx.baseURL at https://<cdn>/_ipx therefore produces absolute URLs, but nothing ever writes /_ipx/* to S3. That matches the current 403s.

How variants get written (ipx and ipxStatic both).

  1. When not in dev, the /_ipx/** handler is added to nitro.options._config.handlers with fs.dir = moduleOptions.dirs, which are the source public/ dirs (@nuxt/image/dist/module.js:49-52).
  2. The prerenderer is a second Nitro built from _config (nitropack/dist/core/index.mjs:1996-2004), so it can resize from source.
  3. During prerender, NuxtImg and NuxtPicture call prerenderStaticImages(src, srcset, event) (@nuxt/image/dist/runtime/components/NuxtImg.vue:105-106, NuxtPicture.vue:123-125). So does $img / getImage when an event is present (@nuxt/image/dist/runtime/image.js:12-14).
  4. prerenderStaticImages keeps only URLs that contain /_ipx/ and appends them to the x-nitro-prerender response header (@nuxt/image/dist/runtime/utils/prerender.js:6-13).
  5. Nitro reads that header only for HTML routes. It skips any link that has a protocol or host (nitropack/dist/core/index.mjs:1843-1849, :2154-2163), then fetches each remaining link and writes it to .output/public.

So the variants written are exactly the src plus every srcset candidate (each width × densities, @nuxt/image/dist/runtime/image.js:94-140) that were rendered into prerendered HTML.

Not covered:

The docs give the same caveat: for ipxStatic, “if images weren’t crawled during generation (unreachable modals, pages or dynamic runtime size)”, changing dir causes 404s (configuration). The static images page says images are optimised “when your site is generated”. With ssr: false it says to list image URLs in nitro.prerender.routes. That page does not discuss SSR builds that prerender only some routes. The source shows the mechanism is the same for any prerendered route, because the _config handler is pushed whenever !nitro.options.dev (module.js:49).

The runtime Lambda handler.

CDN image providers.

Absolute CDN URLs from NuxtImg. The supported way is a custom provider. Its getImage returns { url }, and per the docs the URL may be absolute (custom provider). Absolute URLs have two effects:

  1. Nitro will not prerender them (nitropack/dist/core/index.mjs:1847). Any provider that wants both generation and absolute runtime URLs has to emit relative URLs only while prerendering.
  2. Server and client must return the same URL for one render, or the attributes will not match during hydration. Vue’s exact production behaviour for attribute mismatches was not verified here.

About import.meta.prerender. Nitro defines import.meta.prerender per Nitro build: true only for the nitro-prerender preset (nitropack/dist/rollup/index.mjs:1864, 1873). Vite defines it only for the client, as false (@nuxt/vite-builder/dist/index.mjs:1850). So from source, the Lambda build should see false. The task context reports that it was observed folded to true in the server bundle. That conflicts with the source reading, and the cause is unverified.

Either way, two things hold:

3. Should rasters/SVGs move to app/assets/?

What app/assets/ gives. The build processes these files “mainly for performance or caching purposes”, and a bundled path “resolves to the hashed output file” (assets).

Names that come from content JSON. The docs list three patterns (assets):

  1. An explicit map of literal ?url imports.
  2. A dynamic import() where only the filename varies.
  3. import.meta.glob with query: '?url', import: 'default', then looking up the name, throwing if it is missing, and awaiting the loader.

Glob imports “are lazy by default”. eager: true makes URLs synchronous, but loads every match up front and can raise initial JS size or inline small assets. Every match is built either way.

SSR caveats (same page):

Using these assets with NuxtImg.

4. What the deployment docs say about a server-rendered app with assets on a separate CDN

Deployment page (deployment):

Hybrid rendering / route rules (rendering):

Prerendering (prerendering):

cdnURL and payloads (source).

AWS presets.

Effect on questions 1–3. The recommendations do not change.

Recommendations for this repo

Ranked by fit for “no Lambda round trip per image, no 403s, no hydration drift”. Every option has to meet the repo UI rule. This change touches URLs, not markup, so alt, sizes, focus and touch targets are unchanged. Verify no layout shift by keeping width/height on every image.

  1. Make every public-file URL cdnURL-aware with one documented helper.
    • Add a small universal helper: publicAsset(path) = joinURL(app.cdnURL || app.baseURL, path) from useRuntimeConfig().app. Use it for every runtime :src from content JSON and every none-provider image.
    • Leave static literals alone; the build already rewrites them (section 1).
    • Then retire the 302 middleware for /i, /v and /d.
    • Pros: documented API (no #internal import), identical on server and client, so no hydration mismatch. Removes the Lambda hop for all unresized files.
    • Cons: every dynamic call site has to use it, so it needs a guard test, and missed sites still hit the Lambda. Keep the middleware as a temporary fallback that logs the path so stragglers can be found.
  2. Resized images: a custom provider with one URL on server and client, plus a Lambda fallback that can read sources.
    • Keep a cdnIpx-style provider (documented custom provider).
    • Decide relative vs absolute from the per-request x-nitro-prerender header (useRequestHeader), not from import.meta.prerender. Otherwise the prerendered HTML holds relative URLs while the client computes absolute ones.
    • Then either rewrite the relative /_ipx/ URLs in the prerendered HTML to the CDN after prerender (a prerender:generate hook in Nitro, nitropack/dist/core/index.mjs:2131; not tested), or accept that only the first load of a prerendered page uses relative URLs.
    • Give the Lambda /_ipx handler alias + domains so it fetches sources from CloudFront (section 2).
    • Add CloudFront origin-group failover from S3 to API Gateway for /_ipx/*. Today the distribution has only the S3 origin (infra/sam/template.yaml:501-503), so this is infra work.
    • Pros: one URL everywhere, variants found by crawling are served from S3, and any other size still works.
    • Cons: the most moving parts (provider, HTML rewrite or accepted drift, IPX HTTP fetch, CloudFront failover). The first request for an uncrawled size runs sharp on Lambda, so Lambda memory and timeout need checking.
  3. Fix the variant set: only the sizes that are written.
    • Use densities / sizes presets and make every content image render on at least one prerendered route. That includes modals, which need to be rendered or listed in nitro.prerender.routes with their /_ipx/... URLs (the docs suggest this for ssr: false).
    • Drop the runtime /_ipx fallback.
    • Pros: no sharp on Lambda, everything immutable on S3.
    • Cons: any size that is not crawled is a 403. Content JSON edits need a rebuild. This is fragile for runtime-only pages.
  4. Pre-generate variants outside Nuxt (a build script with @tgmc/image/sharp writing public/_ipx/<modifiers>/<path> or a repo-owned layout) and use a none-style custom provider that emits CDN URLs.
    • Pros: fully predictable, no prerender coupling, server and client match.
    • Cons: this re-implements @nuxt/image URL encoding, or gives up its srcset logic. The variant matrix has to stay in sync with component sizes.
  5. A third-party image CDN provider (imgix, imgproxy, weserv, … with an S3/CloudFront origin).
    • Pros: any size on demand, nothing generated at build time, a documented @nuxt/image provider.
    • Cons: new vendor, cost and secrets. There is no first-party AWS/CloudFront provider in 2.1.0. Fit is unverified.
  6. Move rasters/SVGs to app/assets/ selectively. Do this for images that templates reference literally, such as UI chrome and icons not handled by @nuxt/icon. Keep content-driven media in public/ unless content JSON can name a key that maps through an import.meta.glob ?url map.
    • Pros: hashed, immutable, cdnURL-correct with no helper.
    • Cons: the glob map has to be awaited for SSR, or made eager (bigger JS). Content paths change from URLs to keys, which is a content migration. Resizing still needs options 2-5. Stable public URLs (favicons, OG images, files under /d) must stay in public/.

Unverified / open