Using CORS in Hapi

If you are using Node.js and Hapi framework, it’s easy to configure CORS without any packages.

To enable CORS for all routes in Hapi server we can set the cors value to true:

or we can set the cors value to the next object:

To enable CORS for a single route we can add the cors property to route.options object:

Also, you can pass the cors as object with properties:

The cors object supports the next properties:

  • origin – an array of strings. (‘Access-Control-Allow-Origin’)
  • maxAge – number of seconds. (‘Access-Control-Max-Age’)
  • headers – an array of strings. (‘Access-Control-Allow-Headers’)
  • additionalHeaders – an array of additional strings for previous property
  • exposedHeaders – an array of strings. (”Access-Control-Expose-Headers’)
  • additionalExposedHeaders – an array of additional strings for previous property
  • credentials – allow user credentials. (‘Access-Control-Allow-Credentials’)

You can read more about all these properties in the official Hapi documentation.

Learning Hapi.js? Buy my Hapi.js Handbook🔥

If you liked this, please help spread the word by hitting the recommend button below. Thanks!