@@ -2,15 +2,37 @@ import { parse } from 'url';
22import { default as next } from 'next' ;
33import type { Request } from 'firebase-functions/v2/https' ;
44import type { Response } from 'express' ;
5+ import LRU from 'lru-cache' ;
6+ import { NextServer } from 'next/dist/server/next.js' ;
57
6- const nextApp = next ( {
7- dev : false ,
8- dir : process . cwd ( ) ,
8+ const nextAppsLRU = new LRU < string , NextServer > ( {
9+ // TODO tune this
10+ max : 3 ,
11+ allowStale : true ,
12+ updateAgeOnGet : true ,
13+ dispose : ( server ) => {
14+ server . close ( ) ;
15+ }
916} ) ;
10- const nextAppPrepare = nextApp . prepare ( ) ;
1117
1218export const handle = async ( req : Request , res : Response ) => {
13- const parsedUrl = parse ( req . url , true ) ;
14- await nextAppPrepare ;
19+ const { hostname, protocol, url } = req ;
20+ const port = protocol === 'https' ? 443 : 80 ;
21+ const key = [ hostname , port ] . join ( ':' ) ;
22+ // I wish there was a better way to do this, but it seems like this is the
23+ // way to go. Should investigate more if we can get hostname/port to be
24+ // dynamic for middleware.
25+ let nextApp = nextAppsLRU . get ( key ) ;
26+ if ( ! nextApp ) {
27+ nextApp = next ( {
28+ dev : false ,
29+ dir : process . cwd ( ) ,
30+ hostname,
31+ port
32+ } ) ;
33+ nextAppsLRU . set ( key , nextApp ) ;
34+ }
35+ await nextApp . prepare ( ) ;
36+ const parsedUrl = parse ( url , true ) ;
1537 nextApp . getRequestHandler ( ) ( req , res , parsedUrl ) ;
1638} ;
0 commit comments