Skip to content

Commit

Permalink
Don't encode responses with Cache-Control: no-transform
Browse files Browse the repository at this point in the history
  • Loading branch information
glenjamin committed Sep 27, 2015
1 parent c2af8bd commit 9d98c8b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
17 changes: 17 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@ var zlib = require('zlib')
module.exports = compression
module.exports.filter = shouldCompress

/**
* Regex to match no-transform directive in a cache-control header
*/
var NO_TRANSFORM_REGEX = /(?:^|,)\s*?no-transform\s*?(?:,|$)/

/**
* Compress response data with gzip / deflate.
*
Expand Down Expand Up @@ -135,6 +140,18 @@ function compression(options) {
return
}

// Don't compress for Cache-Control: no-transform
// https://tools.ietf.org/html/rfc7234#section-5.2.1.6
var cacheControl = res.getHeader('Cache-Control')
if (cacheControl) {
var noTransform = NO_TRANSFORM_REGEX.test(cacheControl)
if (noTransform) {
nocompress('no-transform')
return
}
}


// vary
vary(res, 'Accept-Encoding')

Expand Down
46 changes: 46 additions & 0 deletions test/compression.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,52 @@ describe('compression()', function(){
.expect(200, done)
})

describe("Cache-Control", function() {

[
'no-transform',
'public, no-transform',
'no-transform, private',
'no-transform , max-age=1000',
'max-age=1000 , no-transform'
].forEach(function(headerValue) {
it('should skip Cache-Control: ' + headerValue, function(done){
var server = createServer({ threshold: 0 }, function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.setHeader('Cache-Control', headerValue)
res.end('hello, world')
})

request(server)
.get('/')
.set('Accept-Encoding', 'gzip')
.expect(shouldNotHaveHeader('Content-Encoding'))
.expect(200, done)
})
});

[
'not-no-transform',
'public',
'no-transform-thingy'
].forEach(function(headerValue) {
it('should not skip Cache-Control: ' + headerValue, function(done){
var server = createServer({ threshold: 0 }, function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.setHeader('Cache-Control', headerValue)
res.end('hello, world')
})

request(server)
.get('/')
.set('Accept-Encoding', 'gzip')
.expect('Content-Encoding', 'gzip')
.expect(200, done)
})
});

})

it('should skip unknown accept-encoding', function(done){
var server = createServer({ threshold: 0 }, function (req, res) {
res.setHeader('Content-Type', 'text/plain')
Expand Down

0 comments on commit 9d98c8b

Please sign in to comment.