Skip to content

Commit

Permalink
Merge pull request #90 from abdelaziz-mahdy/add-cache-headers
Browse files Browse the repository at this point in the history
feat(cache): add Cache-Control middleware and update .env.example
  • Loading branch information
ghoshRitesh12 authored Dec 23, 2024
2 parents 2d5377c + dfc278b commit 2e93990
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
8 changes: 8 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,11 @@ ANIWATCH_API_MAX_REQS=70

# env to use optional redis caching functionality
ANIWATCH_API_REDIS_CONN_URL=<rediss://default:your-secure-password@your-redis-instance-name.provider.com: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
15 changes: 15 additions & 0 deletions src/config/cacheControlMiddleware.ts
Original file line number Diff line number Diff line change
@@ -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;
2 changes: 2 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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
Expand Down

0 comments on commit 2e93990

Please sign in to comment.