API-gateway-lambda : Cookie not getting saved in browser

Viewed 170

I'm trying to know how to use cookies with AWS-Lambda with the serverless framework as per this blogpost and following is my serverless.yml code

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: /post
          method: post
          cors: 
            origin : 'https://xyz.netlify.app'

and Lambda function as per following

"use strict";
const cookie = require("cookie");

module.exports.hello = async (event) => {
  const body = JSON.parse(event.body);
  const name = body.name;
  const value = body.value;
  return {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "https://xyz.netlify.app",
      "Access-Control-Allow-Credentials": true,
      "Set-Cookie": cookie.serialize(name, value, {
        expires: new Date(new Date().getTime() + 10 * 1000),
      }),
    },
    body: JSON.stringify(
      {
        input: event,
      },
      null,
      2
    ),
  };

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  // return { message: 'Go Serverless v1.0! Your function executed successfully!', event };
};

As you can notice, I already have configured the code to avoid any cors issue. While try to send a post request as per following,

        const name = document.getElementById('name')
        const value = document.getElementById('value')
        const post_btn = document.getElementById('post_btn')

    post_btn.addEventListener('click', () => {
    console.log(name.value, value.value)
    const post_url = 'https://abcdxyz59t9.execute-api.ap-south-1.amazonaws.com/dev/post'

    const user = {
        name: name.value,
        value: value.value
    };

    // request options
    const options = {
        method: 'POST',
        body: JSON.stringify(user),
        headers: {
            'Content-Type': 'application/json'
        }
    }

    // send POST request
    fetch(post_url, options)
        .then(res => res.json())
        .then(res => console.log(res));
})

I do get a Set-Cookie header like below enter image description here

But the cookie doesn't get saved in the browser.

enter image description here That's not the case when I directly try to hit a get request with that URL without the cors in the browser. Can anyone please tell me what to do?

0 Answers
Related