To optimize performance and reduce memory usage, @cloudflare/next-on-pages uses a lazy loading strategy. Instead of evaluating the entire application code at once, the generated Cloudflare Worker only imports the specific route code required to handle an incoming request.
When you build your application, the CLI categorizes the vercel build output into two types of files:
- Route files: These export functions that produce a route result (e.g., a server-side rendered page or an API route response) for a specific request.
- Chunk files: These contain shared code deduplicated across different routes to reduce the overall JavaScript bundle size.
The execution flow works as follows:
- The main
_worker.js uses dynamic imports (import()) to load only the necessary Route file when a request matches a route. - The Route file then uses static imports (
import * from) to pull in the specific Chunk files it requires.
This ensures that code is only evaluated and run when it is actually needed to handle a request.
flowchart TD
subgraph _worker.js
worker["default export { fetch }"]:::worker
end
_worker.js -.-> routeA
_worker.js -.-> routeB
_worker.js -.-> ...routes...
_worker.js -.-> apiRouteX
_worker.js -.-> apiRouteY
routeA --> chunk1
routeA --> chunk2
routeB --> chunk1
routeB --> chunk3
...routes...:::multi --> ...chunks...:::multi
apiRouteX --> chunk5
apiRouteX --> chunk3
apiRouteX --> chunk6
apiRouteY --> chunk6
apiRouteY --> chunk4
classDef multi opacity:0.8,stroke:transparent,fill:transparent
classDef worker fill:transparent