Skip to content

fix(firebase-frameworks): prepare the Next.js server once, not per request - #687

Open
leoortizz wants to merge 1 commit into
mainfrom
fix/next-memoize-prepare
Open

leoortizz wants to merge 1 commit into
mainfrom
fix/next-memoize-prepare

Conversation

@leoortizz

@leoortizz leoortizz commented Aug 31, 2026

Copy link
Copy Markdown
Member

Problem

handle() called await nextApp.prepare() on every request. Since Next 13.4.15 that is no longer a no-op in production: each call re-runs the router server initialization, leaking a process-level error listener and rebuilding the render server, until the instance runs out of memory.

Fixes #574.

Fix

Prepare once at module load and await the shared promise — matching the documented custom server example and the existing express, nuxt3 and sveltekit adapters.

Verification

Deployed to Cloud Run at 512MiB. Next 14.2.35, 501 routes, 1500 requests.

Before: listeners grew by one per request, memory grew 0.47 MB per request, and the container was killed twice for exceeding its memory limit.

Memory limit of 512 MiB exceeded with 513 MiB used.
Memory limit of 512 MiB exceeded with 516 MiB used.

After: listeners flat at 3, memory flat at ~144 MB, zero restarts.

request

handle() called nextApp.prepare() on every request. Since Next 13.4.15
that is
no longer a no-op in production: each call re-runs the router server
initialization, leaking a process-level error listener and rebuilding
the render
server, until the instance is OOM-killed.

Prepare once at module load and await the shared promise, matching the
custom
server example in the Next.js docs and the existing express, nuxt3 and
sveltekit
adapters: https://nextjs.org/docs/pages/guides/custom-server

Fixes #574

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request extracts the nextApp.prepare() call to the module's top level to avoid preparing the Next.js app on every request. However, executing this heavy initialization at module load time can cause deployment failures and slow down cold starts in Firebase/Cloud Functions. The reviewer suggested lazily initializing the preparation promise on the first request instead.

Comment thread packages/firebase-frameworks/src/next.js/index.ts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant