Skip to content

Vite dev middleware swallows asset-extensioned URLs #4252

Description

@jamesarosen

Vite dev middleware swallows asset-extensioned URLs (.jpg/.png/…) even when a Nitro route matches — req._nitroHandled is set unconditionally in nitroDevMiddlewarePre.

Environment

Summary

When the Nitro Vite plugin is in use, the dev server intercepts any URL whose extension matches the built-in ASSET_EXT_RE (jsx/tsx/png/jpg/svg/webp/avif/woff2/…) and routes it to Vite's static middleware even if a user-defined Nitro route matches the URL. The intercept also poisons the late-stage Nitro fallback by setting req._nitroHandled = true, so the request never gets a chance to reach the user's route handler. Vite's [email protected] then emits the canonical 404 + Content-Security-Policy: default-src 'none' + X-Content-Type-Options: nosniff.

URLs without an extension, or with extensions not in ASSET_EXT_RE (e.g. .txt), reach the route handler normally. This produces a confusing asymmetry where /api/photos/12345.jpg 404s but /api/photos/12345.txt works.

Reproduction

Minimal vanilla repro (no TanStack Start / Nuxt / etc. needed):

package.json

{
  "name": "nitro-static-demo",
  "private": true,
  "type": "module",
  "scripts": { "dev": "vite" },
  "devDependencies": {
    "h3": "2.0.1-rc.22",
    "nitro": "3.0.260429-beta",
    "vite": "^8.0.10"
  }
}

vite.config.ts

import { defineConfig } from "vite";
import { nitro } from "nitro/vite";
export default defineConfig({ plugins: [nitro()] });

nitro.config.ts

import { defineConfig } from "nitro/config";
export default defineConfig({ scanDirs: ["."] });

routes/api/photos/[...].ts

import { defineEventHandler } from "h3";
export default defineEventHandler((event) => ({
  handlerReached: true,
  url: event.url?.pathname ?? event.path,
  params: event.context.params,
}));

Then:

pnpm install && pnpm dev
curl -si http://localhost:3000/api/photos/12345        # 200, handler reached
curl -si http://localhost:3000/api/photos/12345.txt    # 200, handler reached
curl -si http://localhost:3000/api/photos/12345.jpg    # 404 with `Content-Security-Policy: default-src 'none'`

Bisect

Same project, only the nitro version changed:

nitro version /api/photos/12345 /api/photos/12345.txt /api/photos/12345.jpg
3.0.1-alpha.2 200 200 200
3.0.260429-beta 200 200 404 ([email protected])

Vite version held constant at 8.0.11. Reverting Vite alone does not fix it; reverting Nitro alone does. So this is a Nitro regression introduced between 3.0.1-alpha.2 and 3.0.260429-beta.

Root cause

nitro/dist/vite.mjs, in the nitroDevMiddlewarePre middleware:

// nitro/dist/vite.mjs (3.0.260429-beta)
const ASSET_EXT_RE = /^(?:[jt]sx?|mjs|cjs|css|s[ac]ss|less|styl|vue|svelte|astro|mdx?|map|wasm|png|jpe?g|gif|svg|webp|avif|ico|bmp|woff2?|ttf|otf|eot|mp[34]|webm|wav|ogg|m4a)$/i;
// …
server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
  const fetchDest = req.headers["sec-fetch-dest"];
  const accept = req.headers["accept"];
  const ext = req.url.match(/\.([a-z0-9]+)(?:[?#]|$)/i)?.[1];
  const isNitroRoute = ext
    ? !!nitro.routing.routes.match(req.method || "", new URL(withBase(req.url, nitro.options.baseURL), "http://localhost").pathname)
    : false;
  const isDocumentLike = fetchDest
    ? /^(document|iframe|frame|empty)$/.test(fetchDest)
    : !(ext && ASSET_EXT_RE.test(ext) && !(typeof accept === "string" && /\btext\/html\b/.test(accept)));
  res.setHeader("vary", "sec-fetch-dest, accept");
  if (isDocumentLike && (!ext || isNitroRoute) && !/^\/(?:__|@)/.test(req.url)) {
    nitroDevMiddleware(req, res, next);
  } else {
    if (!isDocumentLike) req._nitroHandled = true;   // <-- regression
    next();
  }
});

Two problems:

  1. The condition if (isDocumentLike && (!ext || isNitroRoute) && …) already computes isNitroRoute, but only consults it under the isDocumentLike gate. Asset-extension URLs always fail isDocumentLike, so a matching Nitro route can never be reached for them.
  2. The else branch sets req._nitroHandled = true whenever !isDocumentLike, regardless of whether a Nitro route exists. The late-stage Nitro fallback registered by the same plugin (return () => { server.middlewares.use(nitroDevMiddleware); }) checks this flag and bails out, so even if Vite's static middleware would have fallen through, Nitro never sees the request.

For comparison, in 3.0.1-alpha.2 the same middleware looked like:

server.middlewares.use(function nitroDevMiddlewarePre(req, res, next) {
  const fetchDest = req.headers["sec-fetch-dest"];
  res.setHeader("vary", "sec-fetch-dest");
  if (
    (!fetchDest || /^(document|iframe|frame|empty)$/.test(fetchDest)) &&
    !req.url.match(/\.([a-z0-9]+)(?:[?#]|$)/i)?.[1] &&
    !/^\/(?:__|@)/.test(req.url)
  ) nitroDevMiddleware(req, res, next);
  else next();
});

No _nitroHandled poisoning, so the late-stage fallback got the request whenever Vite's static middleware fell through.

Suggested fix

Let a matching Nitro route override the asset-extension shortcut, and don't poison the fallback when one exists:

if ((isDocumentLike || isNitroRoute) && !/^\/(?:__|@)/.test(req.url)) {
  nitroDevMiddleware(req, res, next);
} else {
  if (!isDocumentLike && !isNitroRoute) req._nitroHandled = true;
  next();
}

This preserves the optimization (avoid a Nitro round-trip for genuine static-asset URLs) while ensuring user-defined routes always win when they actually match.

Smoking-gun headers

When the bug fires, the 404 response carries:

Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8

These are the canonical [email protected] "not found" headers — handy for confirming whether a 404 came from Vite's static middleware vs Nitro's own routing layer.

Activity

  1. katywings commented on May 10, 2026

    @katywings
    Contributor

    Noticed the same but for a h3 file handler 🙈. The new nitro dev middleware swallows files served via custom handlers / middleware.

    Since users not necesarilly use nitro routes for such handlers I think there needs a more flexible way to tell nitro when to leave a file request as is and let it be handled by the user app handler. e.g.

    {
      plugins: [
         nitro({
           // File requests like /images/xyz.jpg should be handled by the user app handler
           isAppAsset: (event) => event.url.startsWith("/images")
         }) 
      ] 
    } 
  2. added a commit that references this issue on May 18, 2026
    bbea608
  3. pi0 commented on May 19, 2026

    @pi0
    Member

    #4272 should address other issues (currently in nightly channel) 👍🏼 please ping me if still issues

  4. jantimon commented on May 20, 2026

    @jantimon

    @pi0 I tried the nightly and unfortunately it does not work for me:

    TanStack/router#7403 (comment)

  5. katywings commented on Jun 16, 2026

    @katywings
    Contributor

    @pi0 Nitro still breaks images from routes handled in custom server entries, e.g. if you use a server.ts like below, the /image.png is never called when visiting / in the browser.

    import { H3 } from "h3";
    
    const app = new H3();
    
    app.get('/', (evt) => {
      evt.res.headers.set('content-type', 'text/html')
      return `<img src="/image.png" />`
    })
    
    app.get('/image.png', () => {
      console.log('Image called')
    });
    
    export default app;
    
  6. reopened this on Jun 16, 2026
  7. reopened this on Jun 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions