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
- Static literal
srcin templates getscdnURL. Runtime strings do not. At build time,@vitejs/plugin-vueturns absolute staticsrcvalues onimg,video,source,imageanduseinto imports. Nuxt resolves each one topublicAssetsURL(path), which returnscdnURL || baseURL. A:srcbound at runtime is never rewritten, and neither is<NuxtImg src>. - The helper is
publicAssetsURLfrom#internal/nuxt/paths. It exists on both server and client. It is internal and not documented. The documented equivalent isjoinURL(useRuntimeConfig().app.cdnURL || useRuntimeConfig().app.baseURL, path). - The
ipxprovider ignorescdnURL. It buildsjoinURL(app.baseURL, '/_ipx', …)unless the provider gets its ownbaseURL. If thatbaseURLis absolute,@nuxt/imagetreats it as an external IPX and registers no/_ipxhandler at all, neither on the Lambda nor in the prerenderer. In that case no variants are ever generated. - Variants are written only during prerender. They come from
src/srcsetvalues rendered on prerendered HTML pages, which@nuxt/imagereports through thex-nitro-prerenderheader. Nitro drops any link that has a host, so absolute CDN URLs are never written. This works in an SSR build that prerenders some routes. Pages rendered only at runtime, and sizes computed only on the client, produce no variants. - There is no CloudFront/AWS image provider in
@nuxt/image2.1.0. The closest built-in isawsAmplify, which is for Amplify Hosting. Custom providers may return absolute URLs (documented). - The Lambda
/_ipxhandler cannot read sources whilepublic/is not deployed. Its fs storage points at../public. The only way to make it work isaliasplusdomains, which makes ipx fetch the source over HTTP from the CDN. - The deployment docs add nothing that changes questions 1–3. They do not cover a split server/CDN setup or AWS Lambda static assets.
routeRules(prerender,swr,isr,headers) are honoured natively only on Netlify and Vercel.cdnURLis applied to_payload.jsonfor prerendered routes, so those files must be on the CDN too (section 4). app/assets/gives hashed, CDN-prefixed, long-cached URLs for static imports. For names that come from content JSON, use animport.meta.glob(..., { query: '?url', import: 'default' })map. Await lazy entries before SSR uses them.new URL(..., import.meta.url)does not work with SSR (documented).
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/).
- Server:
@nuxt/nitro-server/dist/runtime/utils/paths.mjs:10-17, aliased as#internal/nuxt/paths(@nuxt/nitro-server/dist/index.mjs:768). It is also auto-imported in Nitro as__publicAssetsURL/__buildAssetsURL(@nuxt/nitro-server/dist/index.mjs:639-646). - Client: the generated
.nuxt/paths.mjstemplate (nuxt/dist/index.mjs:4137-4157), aliased at@nuxt/schema/dist/index.mjs:492. On the client it also setsglobalThis.__publicAssetsURL. - The
#internal/prefix means this is not a public API. No docs page documents importing it (unverified as supported). The documented route isuseRuntimeConfig().app(assets recommendsjoinURLwithuseRuntimeConfig().app.baseURLfor runtime paths). A cdnURL-aware version follows the same pattern withapp.cdnURL || app.baseURL.
Static literal src in a template. This one is rewritten.
- Nuxt’s default
vue.transformAssetUrlscoversimg[src],video[src,poster],source[src],image[href]anduse[href](@nuxt/schema/dist/index.mjs:77-83). - In a production build,
@vitejs/plugin-vuesetsincludeAbsolute: 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). - Nuxt’s
nuxt:vite-public-dir-resolutionresolves any id that exists inpublic/to a virtual module that exportspublicAssetsURL("<path>")(@nuxt/vite-builder/dist/index.mjs:832-849). - Vite
renderBuiltUrluses__publicAssetsURL/__buildAssetsURLat 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.
NuxtImgis not one of thetransformAssetUrlstags.useImagepasses onlyapp.baseURLto providers (@nuxt/image/dist/runtime/composables.js:9-12). The server variant does the same (@nuxt/image/dist/runtime/server/utils/image.js:9).ipxandipxStaticdefault tojoinURL(ctx.options.nuxt.baseURL, '/_ipx')(@nuxt/image/dist/runtime/providers/ipx.js:26-28,ipxStatic.js:47-49).nonereturns the src unchanged (@nuxt/image/dist/runtime/providers/none.js).
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):
- If
ipx.baseURLhas a protocol,@nuxt/imageusesipxand treats it as an external IPX. - Otherwise, a static Nitro build or
provider: 'ipxStatic'selectsipxStatic. - Otherwise, a Node preset selects
ipx. - Otherwise,
none.
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).
- When not in dev, the
/_ipx/**handler is added tonitro.options._config.handlerswithfs.dir = moduleOptions.dirs, which are the sourcepublic/dirs (@nuxt/image/dist/module.js:49-52). - The prerenderer is a second Nitro built from
_config(nitropack/dist/core/index.mjs:1996-2004), so it can resize from source. - During prerender,
NuxtImgandNuxtPicturecallprerenderStaticImages(src, srcset, event)(@nuxt/image/dist/runtime/components/NuxtImg.vue:105-106,NuxtPicture.vue:123-125). So does$img/getImagewhen an event is present (@nuxt/image/dist/runtime/image.js:12-14). prerenderStaticImageskeeps only URLs that contain/_ipx/and appends them to thex-nitro-prerenderresponse header (@nuxt/image/dist/runtime/utils/prerender.js:6-13).- 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:
- routes rendered only at runtime
- images inside unreached modals or tabs
- sizes computed only on the client
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.
- The
ipx(non-static) provider also pushes/_ipx/**into the main Nitro handlers (@nuxt/image/dist/module.js:46-48). - The handler’s fs dir is
relative(serverDir, publicDir)(module.js:22, 31), resolved against the bundle location (@nuxt/image/dist/runtime/server/routes/_ipx.js:8). - On this Lambda that
public/directory is absent, so local sources are not found. - ipx resolves
aliasbefore choosing storage, and useshttpStoragefor any id that has a protocol (ipx/dist/_chunks/node-fs.mjs:894-895). An alias such as{ '/i': 'https://<cdn>/i' }with the CDN host inimage.domains, which feedshttp.domains(module.js:34-37), lets the Lambda fetch sources from CloudFront. This is inferred from source and not tested in this repo. - Docs: “When using the default ipx provider, URL aliases are shortened on the server-side” (configuration). Runtime env vars include
NUXT_IPX_BASE_URL,NUXT_IPX_ALIAS_*andNUXT_IPX_HTTP_DOMAINS(ipx provider).
CDN image providers.
- The built-in list is in
@nuxt/image/dist/module.js:68-115. It has no CloudFront or generic S3 provider.awsAmplifyonly configures Amplify Hosting image optimisation (module.js:151-169). - Built-ins that could sit in front of S3 include
imgix,imgproxy,weserv,cloudflareandimagekit. Their setup was not researched (unverified fit). - AWS’s own CloudFront image-transformation solution was not researched (unverified).
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:
- 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. - 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:
- A per-request signal exists. Nitro sends the
x-nitro-prerenderrequest header on every prerender fetch (nitropack/dist/core/index.mjs:2085-2089), so a provider can checkuseRequestHeader('x-nitro-prerender')instead of the compile-time flag. - The client always sees
import.meta.prerender === false. The currentcdn-ipx.ts(baseURL = import.meta.prerender || !cdnURL ? undefined : …) therefore renders relative URLs in prerendered HTML and absolute URLs on the client. If the flag really istrueon the Lambda, live SSR also emits relative/_ipx/*, and those go to API Gateway → Lambda.
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).
- Output names are
<buildAssetsDir>/<name>.[hash].[ext](@nuxt/vite-builder/dist/index.mjs:3457). - The SSR URL is
__buildAssetsURL(...), which is cdnURL-aware (:3469-3471). The client URL is relative to the JS chunk, which is already on the CDN (:3463-3464). - When Nitro serves
/_nuxt/, it usesmaxAge: 31536e3(@nuxt/nitro-server/dist/index.mjs:724-727). On S3/CloudFront the cache headers come from the sync step and distribution policy, not from Nitro. app/assets/is not served at a static URL (assets).public/files “are not modified by the build process” and keep their names (public). That makespublic/the place forfavicon.ico,robots.txt,icon-*.pngand anything linked by a stable URL.
Names that come from content JSON. The docs list three patterns (assets):
- An explicit map of literal
?urlimports. - A dynamic
import()where only the filename varies. import.meta.globwithquery: '?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):
- “Await a lazy import before using its URL in server-rendered markup.”
- Vite’s
new URL(..., import.meta.url)“does not work with SSR”. - Resolution only applies to paths the build can see as literals.
Using these assets with NuxtImg.
- The source becomes a hashed
/_nuxt/…URL, absolute (https://<cdn>/_nuxt/…) on the server. - ipx validates domains for absolute inputs and returns the URL unchanged when the host is not in
domains(@nuxt/image/dist/runtime/image.js:59-64). Resizing therefore needs the CDN host indomains. - The
dirdocs warn that a non-publicsource dir withipxStatic404s for anything not crawled (configuration). - Moving files to
app/assets/solves CDN URLs and cache-busting. It does not solve resizing.
4. What the deployment docs say about a server-rendered app with assets on a separate CDN
Deployment page (deployment):
- It covers the Node server preset, other presets selected with
nitro.preset/NITRO_PRESET, static hosting (200.html/404.html), and Cloudflare features to disable (Rocket Loader, Email Obfuscation) because they cause hydration errors. - It mentions route rules only for adding a fallback page when
nuxt buildprerenders selected routes. - It does not mention
cdnURL, static assets on a separate CDN, or AWS Lambda. - It links to nitro.build/deploy for presets.
Hybrid rendering / route rules (rendering):
- Rule keys:
prerender,swr,isr,ssr: false,redirect,proxy,cors,headers,noScripts,appMiddleware. There is no separatecachekey on that page. swrcaches “on the server or a reverse proxy” for a TTL.isrcan also cache on the CDN, but only “on platforms that support it”. Netlify and Vercel are named as the only platforms where route rules map to native rules andisrreaches the CDN.- AWS is not mentioned.
- Hybrid rendering is not available with
nuxt generate.
Prerendering (prerendering):
- Selective prerendering is configured with
routes/ignore/crawlLinks,routeRules[path].prerender, ordefineRouteRules(experimentalinlineRouteRules). - Output goes to
.output/public(HTML plus_payload.json). - The page does not explain how a running server serves prerendered files next to SSR routes, and it does not mention
cdnURLor images.
cdnURL and payloads (source).
- Client navigation loads
_payload.jsonfromcdnURLonly when the route is prerendered (in the app manifest or by route rule). Otherwise it loads frombaseURL(nuxt/dist/app/composables/payload.js:106-109,:155-181). - So the
.output/publicsync must include prerendered_payload.jsonand/_nuxt/builds/meta/<buildId>.json. The manifest is served frombuildAssetsDir, which is on the CDN (@nuxt/nitro-server/dist/index.mjs:828-841). - With
serveStatic: false, how the Lambda answers a direct request for a prerendered route is not documented. Presumably it renders the page live, but this is unverified.
AWS presets.
- The Nitro AWS Lambda page (nitro.build/deploy/providers/aws) covers only the
.output/server/index.mjsLambda entry,awsLambda.streaming, and chunk inlining. It says nothing aboutpublic/,serveStatic, S3 or CloudFront. - nuxt.com/deploy lists AWS Amplify and SST, but not raw Lambda.
- The SST page sets
preset: 'aws-lambda'and defers architecture to SST’s docs (not researched; unverified).
Effect on questions 1–3. The recommendations do not change.
- No documented Nuxt or Nitro mechanism serves
public/or/_ipxfrom a CDN on Lambda. The docs leave the CDN topology (S3 sync, CloudFront behaviours, failover) to the deployer, so the infra work in recommendation 2 stays the repo’s job. routeRules.headers/swraffect only responses the Lambda itself produces. They can setCache-Controlon the Lambda/_ipxfallback and on HTML, but not on S3 objects, whose headers come from the sync.isrCDN caching is not available on this AWS setup.- New checklist item: keep
_payload.jsonand the build manifest in the S3 sync (they already live in.output/public), and do not let the 302 middleware retirement break them.
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.
- Make every public-file URL cdnURL-aware with one documented helper.
- Add a small universal helper:
publicAsset(path) = joinURL(app.cdnURL || app.baseURL, path)fromuseRuntimeConfig().app. Use it for every runtime:srcfrom content JSON and everynone-provider image. - Leave static literals alone; the build already rewrites them (section 1).
- Then retire the 302 middleware for
/i,/vand/d. - Pros: documented API (no
#internalimport), 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.
- Add a small universal helper:
- 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-prerenderheader (useRequestHeader), not fromimport.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 (aprerender:generatehook 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
/_ipxhandleralias+domainsso 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.
- Keep a
- Fix the variant set: only the sizes that are written.
- Use
densities/sizespresets and make every content image render on at least one prerendered route. That includes modals, which need to be rendered or listed innitro.prerender.routeswith their/_ipx/...URLs (the docs suggest this forssr: false). - Drop the runtime
/_ipxfallback. - 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.
- Use
- Pre-generate variants outside Nuxt (a build script with
@tgmc/image/sharp writingpublic/_ipx/<modifiers>/<path>or a repo-owned layout) and use anone-style custom provider that emits CDN URLs.- Pros: fully predictable, no prerender coupling, server and client match.
- Cons: this re-implements
@nuxt/imageURL encoding, or gives up itssrcsetlogic. The variant matrix has to stay in sync with componentsizes.
- 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/imageprovider. - Cons: new vendor, cost and secrets. There is no first-party AWS/CloudFront provider in 2.1.0. Fit is unverified.
- Pros: any size on demand, nothing generated at build time, a documented
- 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 inpublic/unless content JSON can name a key that maps through animport.meta.glob?urlmap.- 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 inpublic/.
Unverified / open
- Why
import.meta.prerenderwas observed astruein the Lambda server bundle. The source says Nitro sets it per build (nitropack/dist/rollup/index.mjs:1873). Check by grepping.output/<env>/serverfor theprerenderStaticImagesguard. - Vue 3.5 production behaviour on
src/srcsethydration mismatches. - Whether
?urlimports still inline belowassetsInlineLimit(the Nuxt docs say eager globs “can … inline small assets”). - Whether the ipx HTTP fetch from CloudFront works from Lambda with the current bucket policy.