Setting a cookie in http.jl so as to start a session


I appreciate this will seem obvious to those in the know, but could someone post an example of how to add a cookie server-side to a response that can be used as a session identifier? As a kind of middleware, I think. There doesn’t appear to be exactly that in the docs or this forum. I’m afraid I can’t post a MWE of me failing to get this to work as I’m on my phone ATM.

Many thanks,


You could do something like:

using UUIDs, HTTP

const SESSION_IDS = Set{UUID}()

function generate_and_set_session_id_middleware(handler)
    function (req::HTTP.Request)
        # first we pass the request on to the next handler in the chain
        resp = handler(req)
        # now that we have a response, we can generate and set the session id cookie
        session_id = uuid4()
        push!(SESSION_IDS, session_id)
        HTTP.setheader(resp, "Set-Cookie" => "MyApplicationSessionId=$session_id;")
        return resp

You could take it a step further and use the HTTP.Cookie object if you want, where you can set the expires, domain, path, etc. and then set that in the response.

1 Like