diff --git a/packages/vite/src/node/preview.ts b/packages/vite/src/node/preview.ts index 067450849ee476..ab4ddfb9571778 100644 --- a/packages/vite/src/node/preview.ts +++ b/packages/vite/src/node/preview.ts @@ -100,12 +100,6 @@ export async function preview( const { spa } = config - if (spa) { - // We need to apply the plugins' server post hooks before `sirv()`. (Because - // `sirv(_, { single: true })` catches all routes.) - postHooks.forEach((fn) => fn && fn()) - } - // static assets const distDir = path.resolve(config.root, config.build.outDir) app.use( @@ -117,11 +111,10 @@ export async function preview( }) ) - if (!spa) { - // We apply the plugins' server post hooks after `sirv()` so that `sirv()` - // can serve pre-rendered pages before any SSR middleware. - postHooks.forEach((fn) => fn && fn()) + // apply post server hooks from plugins + postHooks.forEach((fn) => fn && fn()) + if (!spa) { // 404 handling (this simulates what most static hosts do) app.use(config.base, (_, res, next) => { const file = path.join(distDir, './404.html') diff --git a/packages/vite/src/node/server/index.ts b/packages/vite/src/node/server/index.ts index 752ea2d8993087..a74bc237f213b5 100644 --- a/packages/vite/src/node/server/index.ts +++ b/packages/vite/src/node/server/index.ts @@ -503,23 +503,24 @@ export async function createServer( middlewares.use(serveRawFsMiddleware(server)) middlewares.use(serveStaticMiddleware(root, server)) - // We need to apply post server hooks before `spaFallbackMiddleware()`. - // (Because `spaFallbackMiddleware()` catches all routes.) - postHooks.forEach((fn) => fn && fn()) - const isMiddlewareModeSSR = middlewareMode && middlewareMode !== 'html' if (config.spa && !isMiddlewareModeSSR) { - // SPA catch-all fallback routing + // spa fallback middlewares.use(spaFallbackMiddleware(root)) + } + + // run post config hooks + // This is applied before the html middleware so that user middleware can + // serve custom content instead of index.html. + postHooks.forEach((fn) => fn && fn()) + + if (config.spa && !isMiddlewareModeSSR) { // transform index.html middlewares.use(indexHtmlMiddleware(server)) } - // Handle 404s. - // We keep 404 handling when `config.spa === false` because some SSR tools, - // such as vite-plugin-ssr, cannot always render 404 pages. (E.g. if the - // vite-plugin-ssr user didn't define a `_error.page.js`.) + // handle 404s if (!isMiddlewareModeSSR) { // Keep the named function. The name is visible in debug logs via // `DEBUG=connect:dispatcher ...`.