From 603687c46b5125c10ddecb177900a579018fdf2c Mon Sep 17 00:00:00 2001 From: Caleb Braaten Date: Tue, 27 Jan 2026 17:35:34 -0800 Subject: [PATCH] Add gzip compression to responses --- index.tsx | 60 ++++++++++++++++++++----------------------------------- 1 file changed, 22 insertions(+), 38 deletions(-) diff --git a/index.tsx b/index.tsx index 7d9fe17..89901b6 100644 --- a/index.tsx +++ b/index.tsx @@ -7,6 +7,18 @@ import { NotFound } from "./src/frontend/pages/not-found"; import { Post } from "./src/frontend/pages/post"; import { dbConnection } from "./src/db"; +function compressResponse(html: string, status?: number) { + const compressed = Bun.gzipSync(Buffer.from(html)); + return new Response(compressed, { + status, + headers: { + "Content-Type": "text/html", + "Content-Encoding": "gzip", + "Vary": "Accept-Encoding" + } + }); +} + async function blogPosts(hmr: boolean) { const glob = new Bun.Glob("**/*.md"); const blogPosts: Record = {}; @@ -24,10 +36,7 @@ async function blogPosts(hmr: boolean) { const path = new URL(req.url).pathname; const post = dbConnection.getPost(path); if (!post) - return new Response(renderToString(), { - status: 404, - headers: { "Content-Type": "text/html" }, - }); + return compressResponse(renderToString(), 404); // Get adjacent posts for navigation const { previousPost, nextPost } = dbConnection.getAdjacentPosts(post.path); @@ -44,18 +53,13 @@ async function blogPosts(hmr: boolean) { // AppShell is already loaded, just send the
content if (req.headers.get("shell-loaded") === "true") { - return new Response( - renderToString(), - { - headers: { - "Content-Type": "text/html", - }, - }, + return compressResponse( + renderToString() ); } // AppShell is not loaded, send the with the
content inside - return new Response( + return compressResponse( renderToString( , - ), - { - headers: { - "Content-Type": "text/html", - }, - }, + ) ); }; } @@ -99,24 +98,15 @@ Bun.serve({ const searchParams = new URLSearchParams(req.url.split('?')[1]); if (req.headers.get("shell-loaded") === "true") { - return new Response(renderToString(), { - headers: { - "Content-Type": "text/html", - }, - }); + return compressResponse(renderToString()); } - return new Response( + return compressResponse( renderToString( , - ), - { - headers: { - "Content-Type": "text/html", - }, - }, + ) ); }, "/profile-picture.webp": () => { @@ -128,15 +118,9 @@ Bun.serve({ }, "/*": (req) => { if(req.headers.get("shell-loaded") === "true") { - return new Response(renderToString(), { - status: 404, - headers: { "Content-Type": "text/html" }, - }); + return compressResponse(renderToString(), 404); } - return new Response(renderToString(), { - status: 404, - headers: { "Content-Type": "text/html" }, - }); + return compressResponse(renderToString(), 404); } }, });