cookie

Signature

def cookie(name: String): Directive1[HttpCookiePair]

Description

Extracts a cookie with a given name from a request or otherwise rejects the request with a MissingCookieRejectionMissingCookieRejection if the cookie is missing.

Use the optionalCookie directive instead if you want to support missing cookies in your inner route.

Example

Scala
val route =
  cookie("userName") { nameCookie =>
    complete(s"The logged in user is '${nameCookie.value}'")
  }

// tests:
Get("/") ~> Cookie("userName" -> "paul") ~> route ~> check {
  responseAs[String] shouldEqual "The logged in user is 'paul'"
}
// missing cookie
Get("/") ~> route ~> check {
  rejection shouldEqual MissingCookieRejection("userName")
}
Get("/") ~> Route.seal(route) ~> check {
  responseAs[String] shouldEqual "Request is missing required cookie 'userName'"
}
Java
import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.cookie;

final Route route = cookie("userName", nameCookie ->
  complete("The logged in user is '" + nameCookie.value() + "'")
);

// tests:
testRoute(route).run(HttpRequest.GET("/").addHeader(Cookie.create("userName", "paul")))
  .assertEntity("The logged in user is 'paul'");
// missing cookie
runRouteUnSealed(route, HttpRequest.GET("/"))
  .assertRejections(Rejections.missingCookie("userName"));
testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("Request is missing required cookie 'userName'");
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.