optionalCookie

Signature

def optionalCookie(name: String): Directive1[Option[HttpCookiePair]]

Description

Extracts an optional cookie with a given name from a request.

Use the cookie directive instead if the inner route does not handle a missing cookie.

Example

Scala
sourceval route =
  optionalCookie("userName") {
    case Some(nameCookie) => complete(s"The logged in user is '${nameCookie.value}'")
    case None             => complete("No user logged in")
  }

// tests:
Get("/") ~> Cookie("userName" -> "paul") ~> route ~> check {
  responseAs[String] shouldEqual "The logged in user is 'paul'"
}
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "No user logged in"
}
Java
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.optionalCookie;

final Route route = optionalCookie("userName", optNameCookie -> {
  if (optNameCookie.isPresent()) {
    return complete("The logged in user is '" + optNameCookie.get().value() + "'");
  } else {
    return complete("No user logged in");
  }
}
);

// tests:
testRoute(route).run(HttpRequest.GET("/").addHeader(Cookie.create("userName", "paul")))
  .assertEntity("The logged in user is 'paul'");
testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("No user logged in");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.