title | description |
---|---|
Working with HTTP Cache Response Header |
Tutorial on how to work with HTTP Cache Response header in Fano Framework |
To add http cache header (RFC 7324), Fano Framework provides built-in middleware
TCacheControlMiddleware
.
To add HTTP cache header, create middleware or register its factory class TCacheControlMiddlewareFactory
within container.
container.add(
'cacheControl',
TCacheControlMiddlewareFactory.create().useETag()
);
and then, attach middleware to route that will need to be added with HTTP cache header.
router.get(
'/',
container['homeController'] as IRequestHandler
).add(container['cacheControl'] as IMiddleware);
When this middleware attached to route, additional steps is taken:
- If method is not cacheable (not GET nor HEAD) then nothing is done else,
Cache-Control
header is added to response header,- If ETag is used then MD5 hash of response body is computed and
ETag
header is added to response with hash value of response body. - If request contains
If-None-Match
header, its value is compared with ETag value, if they are matched orIf-None-Match
equals"*"
, then response is considered not modified. - If ETag comparison return false and response contains header
Last-Modified
and request contains headerIf-Modified-Since
, both headers values are compared. IfLast-Modified
is older then response is considered not modified. - If response is not modified, instance
TNotModifiedResponse
is returned instead. Read Not modified response section for more information this class.
Read source code if you want to know more.
cacheType()
method set type of cache, accepts value of ctPrivate
or ctPublic
value. If it is not set ctPrivate
is assumed.
container.add(
'cacheControl',
TCacheControlMiddlewareFactory.create().cacheType(ctPublic)
);
noStore()
method enable no-store
value.
container.add(
'cacheControl',
TCacheControlMiddlewareFactory.create().noStore()
);
maxAge()
method set max-age
value.
container.add(
'cacheControl',
//set max-age=3600 (1 hour)
TCacheControlMiddlewareFactory.create().maxAge(60*60)
);
if max-age is set with 0 value, it implies no-cache
.
useETag()
method enable ETag
header. When enable, ETag
response header is added to response with value equals to MD5 hash of response body.
container.add(
'cacheControl',
TCacheControlMiddlewareFactory.create().useETag()
);
mustRevalidate
method enable must-revalidate
value.
container.add(
'cacheControl',
TCacheControlMiddlewareFactory.create().mustRevalidate()
);
All methods above can be chained,
container.add(
'cacheControl',
TCacheControlMiddlewareFactory.create()
.cacheType(ctPublic)
.mustRevalidate()
.useETag()
);
To prevent browser from caching response, you can use something like following example
container.add(
'no-cache',
TCacheControlMiddlewareFactory.create()
.noStore()
.mustRevalidate()
);
or you can use TNoCacheMiddleware
which specifically provided for this purpose
container.add('no-cache', TNoCacheMiddlewareFactory.create());