feat(backend): add well cache control for assets

This commit is contained in:
Julien Oculi 2024-07-11 12:22:22 +02:00
parent 972a94f5dc
commit 5263280085
3 changed files with 23 additions and 1 deletions

1
.gitignore vendored
View file

@ -18,3 +18,4 @@ static/dev
# Dev cache files
cache/
!src/cache/

View file

@ -1,4 +1,5 @@
import { FreshContext } from '$fresh/server.ts'
import { useCache } from ':src/cache/middleware.ts'
import { useCsp } from ':src/csp/middleware.ts'
import { useSecurityHeaders } from ':src/security_headers/middleware.ts'
import { useServiceworker } from ':src/serviceworker/middleware.ts'
@ -16,7 +17,8 @@ export async function handler(request: Request, ctx: FreshContext) {
useSecurityHeaders(request, response, ctx)
await useCsp(request, response, ctx)
useSession(request, response, ctx)
useServiceworker(request, response, ctx)
useServiceworker(request, response, ctx)
useCache(request, response, ctx)
return response
}

19
src/cache/middleware.ts vendored Normal file
View file

@ -0,0 +1,19 @@
import { FreshContext } from '$fresh/server.ts'
export function useCache(
_request: Request,
response: Response,
ctx: FreshContext,
) {
if (ctx.config.dev) return
if (
ctx.url.pathname.match(
/(.+\.|_)((css)|(ttf)|(woff2)|(png)|(svg)|(jpe?g)|(avif))/,
)
) {
response.headers.set(
'Cache-Control',
'public, max-age=31536000, immutable',
)
}
}