Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set-Cookie in response of Azure Function not being set together with the Location header after redirection

I'm aware that 302 redirections in cross-domain situations can make cookies get lost, but the API / Azure Function is on the same domain as the redirectUrl. Considering the following code snippet:

const expirationDate = new Date(Date.now())
expirationDate.setHours(expirationDate.getHours() + 24)

logger.add(`Token cookie expiration date set to: ${expirationDate}`)

const headers = {
   Location: `${auth?.redirectUrl}?clientName=${clientName}`,
   "Set-Cookie": `token=${
      auth?.token
   }; Expires=${expirationDate.toUTCString()}; Path=/;`,
}

After the browser redirects to the redirectUrl, the cookie canno't be found in the browser's Application tab, as it gets lost somehow. I'm guessing that's a specific problem of Azure Functions and that it wouldn't happen if I used express.js, for example. How can I set cookies while 302-redirecting at the same time?

like image 468
Ericson Willians Avatar asked Oct 16 '25 02:10

Ericson Willians


1 Answers

It seems you can no longer set cookies the way you are trying to. It also does not work when you return 200 instead of 302. The newest recommended way does work however.

Working example code:

context.res = {
    status: 302, /* Defaults to 200 */
    // body: responseMessage,
    headers: {
        Location: "https://localhost",
    },
    cookies: [
        {
            name: "token",
            value: "mytokenvalue",
            maxAge: 60 * 10,
            // expires: xxx,
            path: "/"
        }
    ]
};

See also: Better way to set cookies and other repeatable headers in Javascript Http functions

like image 200
Alex AIT Avatar answered Oct 17 '25 14:10

Alex AIT