serverless-http icon indicating copy to clipboard operation
serverless-http copied to clipboard

Can't access cookies from Express w/ 2.0 message format

Open nie7321 opened this issue 4 years ago • 3 comments

I'm unable to get access to the cookies with Express' usual parseCookies() middleware when using the 2.0 message format for an HTTP API (the new API gateway thingy).

It looks like the cookies are separated out from the headers in the AWS message. These should probably be put back into the headers section so frameworks can access them like normal?

nie7321 avatar May 14 '20 20:05 nie7321

I am able to do a request transformation and get it working:

const serverless = require('serverless-http');
const app = require('./app');

module.exports.handler = serverless(app, {
  request: (req, event) => {
    // serverless-http isn't capturing the cookies from the v2.0 API Gateway message,
    // so fix that up.
    if (event.cookies !== undefined && event.cookies.length > 0) {
      req.headers.cookie = event.cookies.join(';');
    }

    return req;
  },
});

but it would be nice if the lib did it out of the box -- I can take a stab at a PR?

nie7321 avatar May 14 '20 21:05 nie7321

You can just check event.version === 2.0 instead of checking event.cookies !== undefined && event.cookies.length > 0.

SachinShekhar avatar Jun 17 '20 20:06 SachinShekhar

BTW, cookies from payload version 2.0 gets serialized by this library. Here's the code: https://github.com/dougmoscrop/serverless-http/blob/master/lib/provider/aws/create-request.js#L21

const initialHeader = event.version === '2.0' && Array.isArray(event.cookies)
    ? { cookie: event.cookies.join('; ') }
    : {};

  return Object.keys(event.headers).reduce((headers, key) => {
    headers[key.toLowerCase()] = event.headers[key];
    return headers;
  }, initialHeader);

I haven't tested it. Maybe, there's a bug.

SachinShekhar avatar Jun 17 '20 20:06 SachinShekhar