DEV Community

HM
HM

Posted on

Creating an AWS lambda that acts as a proxy service

The below code is limited to POST, but can be easily extended to any HTTP Method

const https = require('https');

const destinationHostname = 'someurl.io'
const destinationPath = '/somepath/dev/v1/hola'

exports.handler = async (event) => {
    event.headers = event.headers || {}
    console.log("event", event)
    let postData = event.body
    let body
    let statusCode
    let headers
    await new Promise((resolve, reject) => {
        let options = {
            hostname: destinationHostname,
            port: 443,
            path: destinationPath,
            method: 'POST',
            headers: event.headers,
            rejectUnauthorized: false
        }

        // add additional headers if required, in my case I am setting/resetting Auth header
        options.headers['Authorization'] = 'Basic XXXX'
        // most do:
        options.header["X-Forwarded-Host"] = options.header.Host
        delete options.header.Host // also delete the host before forwarding the request

        var req = https.request(options, (res) => {
            statusCode = res.statusCode 
            headers = res.headers 
            console.log('statusCode:', res.statusCode);
            console.log('headers:', res.headers);

            let chunks = [];
            res.on("data", function (chunk) {
                chunks.push(chunk);
            });
            res.on("end", function () {
                body = Buffer.concat(chunks).toString();
                console.log("RES BODY: ", body) // body.toString());
                resolve();
            });
        })
        req.on('error', (e) => {
            console.error(e);
        });
        req.write(postData)
        req.end()
    })    

    return {
        statusCode: statusCode || 200,
        headers: headers || {'content-type': 'application/json'},
        body: body
    };
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)