How to prevent caching JS and CSS files in Magento 2

If you're using nginx on local environment, probably also copy-paste nginx.conf.sample provided by Magento as your configuration.

But... this config contains something that might make you crazy, because CSS, JS and almost every other file from pub/static might not change after page reload, because their expiration date was set to one year.

Let's fix it!

  1. Find out where are your nginx configuration files are stored, then open file with M2 configuration i.e. /usr/local/etc/nginx/magento2.conf and find this block:

    if ($MAGE_MODE = "production") {
        expires max;
    }
    location ~* .(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
        add_header Cache-Control "public";
        add_header X-Frame-Options "SAMEORIGIN";
        expires +1y;
                
  2. By default ico, jpg, jpeg... files from pub /static expiries after one year. Let’s add some conditions to disable caching for stores with developer mode defined on nginx level or simply set expires off; without any conditions.

    location /static/ {
        if ($MAGE_MODE = "production") {
            expires max;
        }
        location ~* .(ico|jpg|jpeg|png|gif|svg|js|css|swf|eot|ttf|otf|woff|woff2)$ {
            add_header Cache-Control "public";
            add_header X-Frame-Options "SAMEORIGIN";
    
            if ($MAGE_MODE = "developer") {
                expires off;
            }
            if ($MAGE_MODE != "developer") {
                expires +1y;
            }
                
  3. Reload nginx i.e. using sudo nginx -s reload – voilà!