Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hapijs v17 set header before sending response in plugin

I want to create a HapiJS plugin for v17 to append to the response some custom headers, for cors but shouldn't matter.

const cors = {
    name: 'cors',
    version: '1.0.0',
    async register(server) {
        logger.debug('Initiating CORS internal plugin...');
        const { port } = server;
        originPort = port;

        server.ext('onPreResponse', async (request, h) => {

        return h
            .response()
            .header('Access-Control-Allow-Origin', resOrigin)
            .header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE')
            .header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization')
            .header('Access-Control-Allow-Credentials', 'true')
            .header('Access-Control-Max-Age', 1728000);
    });
},

};

Here's what I have so far. I don't think it's right as I get an error.

I've also tried:

  server.ext('onPreResponse', async (request, h) => {
        const { response } = request;

        response.header('Access-Control-Allow-Origin', resOrigin);
        response.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
        response.header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, Authorization');
        response.header('Access-Control-Allow-Credentials', 'true');
        response.header('Access-Control-Max-Age', 1728000);

        return h.continue;
   });

This seems to work locally but fails during testing.

console.error node_modules/hapi/lib/core.js:126
    Debug: internal, implementation, error 
        TypeError: response.header is not a function
        at header (/home/node/app/src/lib/cors.js:47:22)
        at <anonymous>
        at process._tickDomainCallback (internal/process/next_tick.js:228:7)

How do I acheive this in HapiJS v17? The API appears to have been completely refactored in this version and there is very little examples of what specifically I'm trying to do in this version of Hapi.

Thanks!

like image 487
Dan Avatar asked Sep 14 '25 00:09

Dan


1 Answers

When you return Boom errors your response behaviour changes. Try this.

exports.plugin = {
    async register(server, options) {
        server.ext('onPreResponse', async (request, h) => {
            const {response} = request;

            if (response.isBoom) {
                response.output.headers['Access-Control-Allow-Credentials'] = 'true';
                response.output.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,DELETE';
            } else {
                response.header('Access-Control-Allow-Credentials', 'true');
                response.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
            }

            return h.continue;
        });
    },
    name: 'cors'        
};
like image 171
metoikos Avatar answered Sep 15 '25 20:09

metoikos