How come I cannot set multiple cookies
Asked Answered
M

2

6

I'm trying to set multiple cookies, but it's not working:

if type(ngx.header["Set-Cookie"]) ~= "table" then
    ngx.header["Set-Cookie"] = {}
end
table.insert(ngx.header["Set-Cookie"], "Cookie1=abc; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie2=def; Path=/")
table.insert(ngx.header["Set-Cookie"], "Cookie3=ghi; Path=/")

On the client I do not receive any cookies.

Martinmas answered 17/5, 2017 at 6:10 Comment(0)
L
6

ngx.header["Set-Cookie"] is a special table, and must be reassigned to with a new table every time you modify it (elements inserted or removed from it have no effect on the cookies that will be sent to the client):

if type(ngx.header["Set-Cookie"]) == "table" then
    ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", unpack(ngx.header["Set-Cookie"]) }
else
    ngx.header["Set-Cookie"] = { "AnotherCookieValue=abc; Path=/", ngx.header["Set-Cookie"] }
end
Laudable answered 17/5, 2017 at 6:13 Comment(0)
S
3

You can use https://github.com/cloudflare/lua-resty-cookie

local ck = require "resty.cookie"
local cookie, err = ck:new()
cookie:set({key = "Cookie1", value = "abc", path = "/"})
cookie:set({key = "Cookie2", value = "def", path = "/"})
cookie:set({key = "Cookie3", value = "ghi", path = "/"})
Squaw answered 19/5, 2017 at 9:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.