Cache-Control

Cache-Control general-header field is used to specify deirectives that MUST be obeyed by all caching mechanisms along the request/response chain.

When the Cache-Control allow to cache, like Cache-Control: public, max-age: 86400, it means that in this day the browser can use the cahce directly without any request to server.a

1
2
3
4
5
6
7
import http: 'http'
let server = http.createServer((req, res) => {
res.setHeader('Cache-Control', 'public', 'max-age=86400')
res.end('hello world')
})

server.listen(3000)

Etag

Used for conditional HTTP request.

Etag represents Version of Resource, browser will add If-None-Match in headers with request. If the resource on server has not been modified, code 304 will be returned.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import http from 'http'

let server = http.createServer((req, res) => {
console.log(req.url, req.headers['if-none-match'])
if (req.headers['if-none-match']) {
// check if resource modified
res.statusCode = 304
res.end()
} else {
res.setHeader('Etag', '0000000')
res.end('hello world')
}
})

server.listen(3000)

Last-Modified

Similar to Etag, Last-Modified represents if the resource modified. It uses time when modified instead of version tag.

The key in header is If-Modified-Since

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import http from 'http'

let server = http.createServer((req, res) => {
console.log(req.url, req.headers['if-modified-since'])
if (req.headers['if-modified-since']) {
// check timestamp
res.statusCode = 304
res.end()
} else {
res.setHeader('Last-Modified', new Date().toString())
res.end('hello world')
}
})

server.listen(3000)