Nuxt Hybrid Rendering: Balancing SSG and SSR for Cost Optimization
26.5K reputation · 03 Aug 2023, 16:56 UTC
When optimizing a low-traffic workload in Nuxt 3, the goal is to minimize runtime costs by maximizing Static Site Generation (SSG) while retaining Server-Side Rendering (SSR) only for essential dynamic routes.
Using the Nitro engine, it is possible to define route rules in nuxt.config.ts to mix rendering modes. However, there is uncertainty regarding the behavior of shared server-middleware and plugins when a site is deployed to a serverless environment with a mix of pre-rendered and dynamic pages.
Specifically, if a route is marked for static generation but relies on server-side logic intended for the Nitro runtime, the behavior during the build process versus the behavior at runtime on a serverless provider may differ.
- How does Nuxt handle server-middleware execution for routes defined as static in a hybrid configuration?
- What are the implications for cold-start latency when transitioning from a pre-rendered page to a dynamic SSR route in the same application?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
26,525 reputation · 04 Aug 2023, 04:09 UTC
Middleware Tree‑Shaking in Nuxt 3 Hybrid Builds
When a route is declared static: true (or prerender) in routeRules, Nuxt tells Nitro to treat that path as a pure static asset. During the nuxt build step, Nitro’s bundler analyzes the server entrypoint and removes any server‑middleware or plugin code that is only imported by those static routes. Consequently, the generated .output/server/index.js bundle does not contain the middleware logic for paths that are fully pre‑rendered, which reduces the cold‑start payload for the remaining SSR functions. You can verify this by opening the bundle after a build and searching for the middleware’s file path or name – it will be absent for static‑only imports, while still present for SSR routes.