From 934a7b1ab6145df2a6364df916a3d5c9f37e1fd8 Mon Sep 17 00:00:00 2001 From: Logan McAnsh Date: Sun, 1 Jan 2023 17:24:16 -0500 Subject: [PATCH] feat: add http/2 link header for preloading scripts Signed-off-by: Logan McAnsh --- app/entry.server.tsx | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/app/entry.server.tsx b/app/entry.server.tsx index e7bf1824..f49dfd77 100644 --- a/app/entry.server.tsx +++ b/app/entry.server.tsx @@ -90,6 +90,31 @@ export default function handleDocumentRequest( ); + // Add Link header for HTTP/2 Server Push + let modules = Object.entries(remixContext.manifest.routes); + let http2PushLinksHeaders = remixContext.staticHandlerContext.matches + .flatMap((match) => { + let routeMatch = modules.find((m) => m[0] === match.route.id); + if (!routeMatch) return []; + let routeImports = routeMatch[1].imports ?? []; + return [routeMatch[1].module, ...routeImports]; + }) + .filter(Boolean) + .concat([ + remixContext.manifest.url, + remixContext.manifest.entry.module, + ...remixContext.manifest.entry.imports, + ]); + + responseHeaders.set( + "Link", + http2PushLinksHeaders + .map((link) => `<${link}>; rel=preload; as=script; crossorigin=anonymous`) + .concat(responseHeaders.get("Link") ?? "") + .filter(Boolean) + .join() + ); + responseHeaders.set("Content-Type", "text/html"); if (process.env.NODE_ENV === "development") {