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.

Dat Boi
  • 115
  • 1
  • 7

2 Answers2

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
wilsonzlin
  • 2,154
  • 1
  • 12
  • 22
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 = "/"})
Alexander Altshuler
  • 2,930
  • 1
  • 17
  • 27