aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRitesh Ghosh <[email protected]>2024-12-23 18:15:01 +0530
committerGitHub <[email protected]>2024-12-23 18:15:01 +0530
commit2e93990d443e7560d5e145406133c5b9899e75e6 (patch)
tree7d79ddcf7abf4ad1eea638b9d9544316ca64e6a3
parent2d5377cbc58bd84dcd0585798e77995265c8727b (diff)
parentdfc278be08b64dc9bb3082059648c5f792a79fcb (diff)
downloadaniwatch-api-2e93990d443e7560d5e145406133c5b9899e75e6.tar.xz
aniwatch-api-2e93990d443e7560d5e145406133c5b9899e75e6.zip
Merge pull request #90 from abdelaziz-mahdy/add-cache-headers
feat(cache): add Cache-Control middleware and update .env.example
-rw-r--r--.env.example8
-rw-r--r--src/config/cacheControlMiddleware.ts15
-rw-r--r--src/server.ts2
3 files changed, 25 insertions, 0 deletions
diff --git a/.env.example b/.env.example
index 8513245..555ad04 100644
--- a/.env.example
+++ b/.env.example
@@ -23,3 +23,11 @@ ANIWATCH_API_MAX_REQS=70
# env to use optional redis caching functionality
ANIWATCH_API_REDIS_CONN_URL=<rediss://default:[email protected]:6379>
+
+# .env.example - Environment configuration file for Aniwatch API
+
+# Cache-Control settings for Vercel Edge Caching
+# ANIWATCH_API_S_MAXAGE: Specifies the maximum amount of time (in seconds) a resource is considered fresh when served by a CDN cache.
+ANIWATCH_API_S_MAXAGE=60
+# ANIWATCH_API_STALE_WHILE_REVALIDATE: Specifies the amount of time (in seconds) a resource is served stale while a new one is fetched.
+ANIWATCH_API_STALE_WHILE_REVALIDATE=30
diff --git a/src/config/cacheControlMiddleware.ts b/src/config/cacheControlMiddleware.ts
new file mode 100644
index 0000000..47035ed
--- /dev/null
+++ b/src/config/cacheControlMiddleware.ts
@@ -0,0 +1,15 @@
+import type { MiddlewareHandler } from "hono";
+
+// Define middleware to add Cache-Control header
+const cacheControlMiddleware: MiddlewareHandler = async (c, next) => {
+ const sMaxAge = process.env.ANIWATCH_API_S_MAXAGE || "60";
+ const staleWhileRevalidate = process.env.ANIWATCH_API_STALE_WHILE_REVALIDATE || "30";
+ c.header(
+ "Cache-Control",
+ `s-maxage=${sMaxAge}, stale-while-revalidate=${staleWhileRevalidate}`
+ );
+
+ await next();
+};
+
+export default cacheControlMiddleware;
diff --git a/src/server.ts b/src/server.ts
index 41a64c5..85d3fbc 100644
--- a/src/server.ts
+++ b/src/server.ts
@@ -5,6 +5,7 @@ import corsConfig from "./config/cors.js";
import { ratelimit } from "./config/ratelimit.js";
import { hianimeRouter } from "./routes/hianime.js";
+import cacheControlMiddleware from "./config/cacheControlMiddleware.js";
import { Hono } from "hono";
import { logger } from "hono/logger";
@@ -26,6 +27,7 @@ const app = new Hono<{ Variables: AniwatchAPIVariables }>();
app.use(logger());
app.use(corsConfig);
+app.use(cacheControlMiddleware);
// CAUTION: For personal deployments, "refrain" from having an env
// named "ANIWATCH_API_HOSTNAME". You may face rate limitting