Hapi: How to set CORS for entire server (or connection)

Created on 4 Dec 2014  路  11Comments  路  Source: hapijs/hapi

I see in the release notes you have:

server.connection({ cors: true });

But I don't see anywhere in the docs that cors is a valid option for server.connection and when I try to use it I get the error:

hapi/node_modules/hoek/lib/index.js:663
    throw new Error(msgs.join(' ') || 'Unknown error');
          ^
Error: Invalid connection options {
  "router": {
    "isCaseSensitive": true,
    "stripTrailingSlash": true
  },
  "routes": {
    "cache": {
      "statuses": [
        200
      ]
    },
    "cors": null,
    "files": {
      "relativeTo": "."
    },
    "json": {
      "replacer": null,
      "space": null,
      "suffix": null
    },
    "payload": {
      "failAction": "error",
      "maxBytes": 1048576,
      "output": "data",
      "parse": true,
      "timeout": 10000,
      "uploads": "/var/folders/nd/c_t721fj36x4kdpk8ygp4dzrnnjb8w/T/"
    },
    "response": {
      "options": {}
    },
    "security": null,
    "state": {
      "parse": true,
      "failAction": "error"
    },
    "timeout": {
      "server": false
    },
    "validate": {
      "options": {}
    }
  },
  "host": "0.0.0.0",
  "port": 10645,
  "cors" [1]: true
}

[1] cors is not allowed
    at Object.exports.assert (myproject/hapi/node_modules/hapi/node_modules/hoek/lib/index.js:663:11)

How can I set cors for an entire connection or server?

support

Most helpful comment

Is there a way to do this on Hapi v17?

Edit: Yes.

const server = new Hapi.Server({
  ...
  routes: {
    cors: {
      origin: ['example.com'],
      additionalHeaders: ['x-token-token']
    }
  }
})

All 11 comments

I fixed the notes. It's server.connection({ routes: { cors: true } }).

Has this behaviour since changed? Setting cors to an object on the connection does not apply the cors rules to any routes. Seems to ignore them.

If your route has any of its own CORS settings, I believe those will be used in lieu of the connection-level CORS settings. Could that be your issue?

If I set a route level cors after setting the default it actually throws a 'not allowed' error on startup.

None of the routes are doing any CORS headers with the following setup. No error, nothing. I tried setting the true to {origin: ['*']} and it made no difference. 馃槹

server.connection({
        port: 3000,
        routes: {
            cors: true
        }
    });

NEVERMIND! 馃槵 I found this https://github.com/hapijs/hapi/issues/2986
Chrome's XHR seems to add accept-language in the request which isn't an allowed header by default. Thus CORS was doing it's job.

(although must admit hard to debug!)

Is there an option to apply this behaviour when the server was already started?
I want to enable custom validate.failAction from the plugin, not at the moment of the server configuration.

On local, it uses the http://127.0.0.1:5000 make sure you have a server running on that port, and make sure it has this the port :3000 authorized for CORS

Is there a way to do this on Hapi v17?

Edit: Yes.

const server = new Hapi.Server({
  ...
  routes: {
    cors: {
      origin: ['example.com'],
      additionalHeaders: ['x-token-token']
    }
  }
})

I'm trying to get cors to work but i have no luck.
This is my configuration with Hapi 17 and Glue.

const server = await Glue.compose(serverConfig, options);
        server.route(routes, {
            cors: {
                origin: [ 'localhost:4000', 'localhost:3000' ]
            }
        });

@rickerd

For glue add _cors: true_ to manifest

const manifest = {
server: {
    port: Config.get('/port/web'),
    routes: {
      validate: {
        failAction: async (request, h, err) => {
          if (process.env.NODE_ENV === 'production') {
            // In prod, log a limited error message and throw the default Bad Request error.
            console.error('ValidationError:', err.message); // Better to use an actual logger here.
            throw Boom.badRequest(`Invalid request payload input`);
          } else {
            // During development, log and respond with the full error.
            console.error(err);
            return err;
          }
        },
      },
      cors: true,
    },
  },

//register plugins here

};

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

RohovDmytro picture RohovDmytro  路  4Comments

leore picture leore  路  4Comments

jeremiahlee picture jeremiahlee  路  4Comments

mateeyow picture mateeyow  路  5Comments

hueniverse picture hueniverse  路  4Comments