dougmoscrop / serverless-http

Use your existing middleware framework (e.g. Express, Koa) in AWS Lambda 🎉
Other
1.72k stars 165 forks source link

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

Open nie7321 opened 4 years ago

nie7321 commented 4 years ago

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 commented 4 years ago

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?

SachinShekhar commented 4 years ago

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

SachinShekhar commented 4 years ago

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.