Using CORS in Hapi


cors hapi nodejs Tutorials

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:

const server = Hapi.server({
    port: 3000,
    host: 'localhost',
    routes: {
        cors: true
    }
});

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

const server = Hapi.server({
    port: 3000,
    host: 'localhost',
    routes: {
        cors: {
            origin: ['*'], // an array of origins or 'ignore'
            headers: ['Authorization'], // an array of strings - 'Access-Control-Allow-Headers'
            exposedHeaders: ['Accept'], // an array of exposed headers - 'Access-Control-Expose-Headers',
            additionalExposedHeaders: ['Accept'], // an array of additional exposed headers
            maxAge: 60,
            credentials: true // boolean - 'Access-Control-Allow-Credentials'
        }
    }
});

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

server.route({
    method: 'GET',
    path: '/index',
    options: {
        cors: true,
        handler: async (req, h) => {
            return h.response({
                text: 'Lorem ipsum'
            });
        }
    }
});

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

server.route({
    method: 'GET',
    path: '/index',
    options: {
        cors: {
            maxAge: 60,
            credentials: true
        },
        handler: async (req, h) => {
            return h.response({
                text: 'Lorem ipsum'
            });
        }
    }
});

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🔥

comments powered by Disqus