@@ -2,15 +2,37 @@ import { parse } from 'url';
2
2
import { default as next } from 'next' ;
3
3
import type { Request } from 'firebase-functions/v2/https' ;
4
4
import type { Response } from 'express' ;
5
+ import LRU from 'lru-cache' ;
6
+ import { NextServer } from 'next/dist/server/next.js' ;
5
7
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
+ }
9
16
} ) ;
10
- const nextAppPrepare = nextApp . prepare ( ) ;
11
17
12
18
export 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 ) ;
15
37
nextApp . getRequestHandler ( ) ( req , res , parsedUrl ) ;
16
38
} ;
0 commit comments