Cloudflare doesn't cache as expected

Solution 1:

You have to set the Page Rule in the CloudFlare Admin panel. The first step to using Page Rules is to define a pattern that defines when the rule is triggered. These patterns can be simple, such as a single URL, or complicated including multiple wildcards. Imagine you have a content management system with a single URL:

http://www.testlifeinuk.com

Now if you try to create a rule with URL Pattern:

http://www.testlifeinuk.com

Only the homepage will be cached!

If you would like to cache the whole website, you have to use the Wildcard in this way:

 *testlifeinuk.com/*

In this way all the pages and resources will be cached by Cloudflare like this:

http://www.testlifeinuk.com/dist/lifeinuk.js
http://www.testlifeinuk.com/mypage.html
https://www.testlifeinuk.com/mypage.html
https://testlifeinuk.com/mypage.html

and the result of the header will be:

HTTP/1.1 200 OK
Date: Mon, 25 May 2015 10:21:05 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.4.39-0+deb7u2
Expires: Mon, 25 May 2015 10:51:05 GMT
Cache-Control: public, max-age=1800
Pragma: no-cache
Vary: Accept-Encoding
CF-Cache-Status: HIT            <<<<< Look this parameter
Server: cloudflare-nginx
CF-RAY: 1ec082ee43150e60-MXP
Content-Encoding: gzip

regards

Solution 2:

Aside what @Michelangelo mentioned about you need to setup CloudFlare Page Rules at first, you also need to make sure you're set response headers correctly, so that you won't override the default caching behavior:

If the Cache-Control header is set to "private", "no-store", "no-cache", or "max-age=0", or if there is a cookie in the response, then CloudFlare will not cache the resource. Otherwise, if the Cache-Control header is set to "public" and the "max-age" is greater than 0, or if the Expires headers are set any time in the future, we will cache the resource.

See: https://support.cloudflare.com/hc/en-us/articles/202775670-How-Do-I-Tell-Cloudflare-What-to-Cache-

And that's why @Rudy Lee said don't forget to set maxAge option because default maxAge is 0 in Express.

See: https://expressjs.com/en/api.html#express.static