Restify and CORS support

Just a quick note about my day job.  Today I spent hours hunting down an issue related to using Restify with an Angular client.  Of course the solution involved just two lines of well placed code.  That part of the solution involved a significant but undocumented feature in Restify was a little irritating (not documenting a feature that's vital to running production quality code seems like quite an oversight.)

I'm talking about Restify's support for CORS (Cross Origin Resource Sharing.)  If that term is unfamiliar to you, there's plenty of documentation on the web.  But when developing apps with Angular (or any client-side Javascript) making HTTP Requests to a REST API server on a host other than the web host, you'll eventually encounter the "Method not supported" and "XMLHttpRequest Origin is not allowed by Access-Control-Allow-Origin" errors.

To get past these errors, try looking for 'CORS' on the Restify site. Googling CORS and Restify will yield the 'official' Restify solution.  It goes something like this:

server.use( restify.CORS( {origins: ['*']}) );
server.use( restify.fullResponse() );

You can pass a list of origin urls to the CORS plugin. Passing '*' means 'any origin', a value you don't want to use in production (it's fine to get something up and running.) To put it another way, your API should only accept requests from trusted hosts.

Things get a little more complicated when adding custom headers (the issue causing hours of debugging to solve.)  For example, our Angular client needs to pass an API auth token when make preflight calls to our REST server.   If the server doesn't pass back the right "Access-Control-Allow" style headers, the request will fail.

Say you have a custom header "my-custom-header" (must be all lower-caps.)  Here's the code that tells Restify's CORS handler all about that header:

    restify.CORS.ALLOW_HEADERS.push( 'my-custom-header' );
    server.use(restify.CORS({ headers: [ 'my-custom-header' ], origins: ['*'] }));

Restify is a fine framework for Node. Still, I do wish API authors would keep their documentation up to date.