React app cannot receive cookies from aws lambda backend

159 views Asked by At

I'm developing a server with AWS Lambda on Serverless Framework, and using serverless-offline to test locally. I just want to send cookies to my react app.

backend code.

import { APIGatewayProxyHandlerV2 } from "aws-lambda";


const oneDayMillis = 1 * 24 * 60 * 60 * 1000;

export const handler: APIGatewayProxyHandlerV2 = async (event) => {
  const expires = new Date(Date.now() + oneDayMillis).toUTCString();
  return { 
    headers: {'Set-Cookie': `name=hardyeats; Path=/; Expires=${expires}; ; httponly;`},
    statusCode: 200 
  }
}

serverless.ts allowing cors.

    httpApi: {
      cors: {
        allowedOrigins: ["${self:custom.env.${opt:stage}.ALLOWED_ORIGIN}"],
        allowedHeaders: ['Content-Type'],
        allowedMethods: ['GET','POST','PUT','DELETE'],
        allowCredentials: true
      }
    },

and react code, tiny.

function Login() {


  useEffect(()=>{
    fetch(`${process.env.REACT_APP_API_SERVER_URL}/oauth/login`)
    .then(res => console.log(res.headers))
  },[])

  return (
    <></>
  );
}

No matter how hard I try, I can't help but get empty headers. How can my react app receive cookies from my backend? With POSTMAN, then I can receive cookies. Thanks in advance.

1

There are 1 answers

0
hardyeats On

sls offline needs another option.

sls offline --disableCookieValidation

and frontend fetch needs credentials option.

fetch(`${process.env.REACT_APP_API_SERVER_URL}/oauth/login`, {
    credentials: 'include'
})