Ervadac
Ervadac

Reputation: 956

Best way to serve static files using versioning with nginx / node

I actually have:

  1. Nginx running to serve static files (css, js, etc.)
  2. Node with express.js, template engine: ECT (I may change for Swig)

I am currently trying to find the best way to distribute static files with a custom prefix with versioning:

So to do that, I only set a variable containing the prefix (which depends on the environment). Then for each request, I set add the prefix to locals in an express middleware in order to access this variable in any html template:

this.use(function(req, res, next) {
    res.locals.staticPrefix = staticPrefix;
    next();
});

But since I also want these static files to be also cached by the client's browser, Nginx serves these files with expire = 30d.

Now to force a client to retrieve a static file (if it has changed for example), I need to provide static urls with a dynamic url parameter.

My first idea would be to set a version variable when I start the nodejs app to append it to the final url:

var staticVersion = new Date().getTime();

So in the html template, the final url for a 'myFile.css' would like this: staticPrefix + 'myFile.css?' + staticVersion

In this case, I only need to restart the nodejs application when one of the static files has been updated. It will make the url to change (according to the new date) and the client to do a new request of the file.

Is there a better way to handle this situation with node?

Upvotes: 0

Views: 2051

Answers (1)

vmx
vmx

Reputation: 8397

Best way to handle static assets like css/js files is to minify them in production. Use file name based on file contents. This way every time you change anything in js/css files, the minification code will take care of generating new file if needed. You can hook minification script to run post deployment.

I have written a package smush to help with minification tasks. Head onto its github page for example usage and sample codes.

You could use other tools/package for minification if it suits better to your use case.

Coming back to your question, you can set the root dir for nginx to static dir of your node server(/path/to/node/server/public?). This way nginx will cache and serve your static files. The node server will not be bothered to serve the static assets afterwards.

Let me know if this makes sense or if you need any further clarification.

Upvotes: 1

Related Questions