Hapi: Checking the "Accepts" Header

Created on 27 Jun 2014  路  8Comments  路  Source: hapijs/hapi

Is there a configuration option or existing method to check an incoming requests's Accepts header before the handler is executed? If the Accepts header is asking for XML and the server only support, JSON, the server should send a 406 status code.

There are a few different ways to solve this problem with the existing features and configurations (pre, onPreHandler, in the handler itself...). Is there a preferred way to check the Accepts header for these situations?

If not, would you be willing to entertain an accepts route config option?

feature

Most helpful comment

I so very need this :(

All 8 comments

You're right, there's no built in standard way. Using a prerequisite or an onPreHandler extension would likely be your best bet as things are now.

An accepts route config option could be useful, though, I agree.

If you have some time, feel free to give implementing it a shot and submit a pull request. If not, I'll add thinking about this to my list. Unless someone else beats me to it.

Content negotiation is a much bigger topic than just rejecting unknown accept types. The reality is that when you support conneg, you want more than just rejecting some types, but also to automatically generate the right response from a generic internal type.

@hueniverse I agree that full content negotiation is a larger topic. I was not going to try to implement full content negotiation; just the small part of rejecting a request with a 406 if the Accepts header is different from the routes eventual Content-Type.

Would you be interested in such a PR or should I stop and wait for a full content negotiation solution (if there is one down the road)?

You could probably use the accepts library (https://www.npmjs.org/package/accepts#readme) off the request.raw.req property? (P.S. I have no authority in here, just butting in)

var accepts = require('accepts');

server.route({
  method: 'GET',
  path: '/hello',
  handler: function (request, reply) {
    var accept = accepts(request.raw.req);
    switch (accept.types('html', 'text')) {
      case 'html':
        // reply with html
        break;
      case 'text':
        // reply with text
        break;
      default:
        // reply with 406
        break;
    }
  }
});

Is there any real world need for this?

I'll take it as a no.

I so very need this :(

This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kevinsimper picture kevinsimper  路  4Comments

hovmand picture hovmand  路  3Comments

jeffbski picture jeffbski  路  5Comments

midknight41 picture midknight41  路  4Comments

RohovDmytro picture RohovDmytro  路  4Comments