What's the recommended way of setting response headers and cookies in Vapor 4?

Hi. Should one create an empty Response object in the handler, assign the headers, status, and body to it, and then return it?

Are there more elegant ways of doing it?


There are a number of ways to achieve this.

You can create a response object, but the initialiser allows you to pass in the headers, status, body etc so it's all done on one line.

Option 2 is if you have something that conforms to ResponseEncodable that you want to add a cookie to, such as View or Content you can do

let response = try await myThingToReturn.encodeResponse(for: req)
return response

Thanks! The second option feels better to me.

Also, speaking of Views, can I ask a question regarding the leaf kit? Is dynamic #extend(variableName) theoretically possible? I am currently getting "reason": "import only supports string literals" when I try it.

What do you mean by dynamic extends? In general, Leaf doesn't play nice with dynamic stuff as the AST parser needs to know everything up front