Skip to content

Commit f9b2ebd

Browse files
authored
Add hostname and port to next custom server (#50)
1 parent e69f5bd commit f9b2ebd

File tree

1 file changed

+28
-6
lines changed

1 file changed

+28
-6
lines changed

src/next.js/index.ts

Lines changed: 28 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,37 @@ import { parse } from 'url';
22
import { default as next } from 'next';
33
import type { Request } from 'firebase-functions/v2/https';
44
import 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

1218
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);
1537
nextApp.getRequestHandler()(req, res, parsedUrl);
1638
};

0 commit comments

Comments
 (0)