setCookie

Signature

def setCookie(first: HttpCookie, more: HttpCookie*): Directive0 

Description

Adds a header to the response to request the update of the cookie with the given name on the client.

Use the deleteCookie directive to delete a cookie.

Example

Scala
sourceval route =
  setCookie(HttpCookie("userName", value = "paul")) {
    complete("The user was logged in")
  }

// tests:
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "The user was logged in"
  header[`Set-Cookie`] shouldEqual Some(`Set-Cookie`(HttpCookie("userName", value = "paul")))
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.setCookie;

final Route route =
    setCookie(HttpCookie.create("userName", "paul"), () -> complete("The user was logged in"));

// tests:
final HttpHeader expected = SetCookie.create(HttpCookie.create("userName", "paul"));

testRoute(route)
    .run(HttpRequest.GET("/"))
    .assertEntity("The user was logged in")
    .assertHeaderExists(expected);