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


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.


sourceval 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'"
sourceimport 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("/"))
  .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.