Why can't I set multiple cookies
I'm trying to set multiple cookies, but it doesn't work:
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 am not receiving cookies.
+3
source to share
2 answers
ngx.header["Set-Cookie"]
is a special table and must be reassigned with a new table whenever it changes (items inserted or deleted from it do not affect 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
+3
source to share
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 = "/"})
+1
source to share