From fa83790dff1578c2fb6a53831ca0330eb84c8eba Mon Sep 17 00:00:00 2001 From: Kalle <38327916+Sendouc@users.noreply.github.com> Date: Sun, 13 Aug 2023 15:36:29 +0300 Subject: [PATCH] Privately cache user build tab response to avoid repeated requests --- app/routes/u.$identifier/builds/index.tsx | 4 ++-- app/utils/remix.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/app/routes/u.$identifier/builds/index.tsx b/app/routes/u.$identifier/builds/index.tsx index b845a377b..d19e7bdd4 100644 --- a/app/routes/u.$identifier/builds/index.tsx +++ b/app/routes/u.$identifier/builds/index.tsx @@ -1,4 +1,3 @@ -import { json } from "@remix-run/node"; import type { ActionFunction, LoaderArgs } from "@remix-run/node"; import { useLoaderData, useMatches } from "@remix-run/react"; import { z } from "zod"; @@ -13,6 +12,7 @@ import { atOrError } from "~/utils/arrays"; import { notFoundIfFalsy, parseRequestFormData, + privatelyCachedJson, type SendouRouteHandle, } from "~/utils/remix"; import { userNewBuildPage } from "~/utils/urls"; @@ -66,7 +66,7 @@ export const loader = async ({ params, request }: LoaderArgs) => { throw new Response(null, { status: 404 }); } - return json({ + return privatelyCachedJson({ builds, weaponCounts: calculateWeaponCounts(), }); diff --git a/app/utils/remix.ts b/app/utils/remix.ts index f39224799..614a99cd0 100644 --- a/app/utils/remix.ts +++ b/app/utils/remix.ts @@ -2,6 +2,7 @@ import { z } from "zod"; import { type TFunction, type Namespace } from "react-i18next"; import { type RouteMatch } from "@remix-run/react"; import type navItems from "~/components/layout/nav-items.json"; +import { json } from "@remix-run/node"; export function notFoundIfFalsy(value: T | null | undefined): T { if (!value) throw new Response(null, { status: 404 }); @@ -150,3 +151,13 @@ export type SendouRouteHandle = { /** The name of a navItem that is active on this route. See nav-items.json */ navItemName?: (typeof navItems)[number]["name"]; }; + +/** Caches the loader response with "private" Cache-Control meaning that CDN won't cache the response. + * To be used when the response is different for each user. This is especially useful when the response + * is prefetched on link hover. + */ +export function privatelyCachedJson(data: T) { + return json(data, { + headers: { "Cache-Control": "private, max-age=20" }, + }); +}