def optionalHeaderValueByName(headerName: Symbol): Directive1[Option[String]]
def optionalHeaderValueByName(headerName: String): Directive1[Option[String]]


Optionally extracts the value of the HTTP request header with the given name.

The optionalHeaderValueByName directive is similar to the headerValueByName directive but always extracts an OptionOptional value instead of rejecting the request if no matching header could be found.


sourceval route =
  optionalHeaderValueByName("X-User-Id") {
    case Some(userId) => complete(s"The user is $userId")
    case None         => complete(s"No user was provided")
  } ~ // can also be written as:
    optionalHeaderValueByName("X-User-Id") { userId =>
      complete {
        userId match {
          case Some(u) => s"The user is $u"
          case _       => "No user was provided"

// tests:
Get("/") ~> RawHeader("X-User-Id", "Joe42") ~> route ~> check {
  responseAs[String] shouldEqual "The user is Joe42"
Get("/") ~> Route.seal(route) ~> check {
  responseAs[String] shouldEqual "No user was provided"
sourceimport static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.optionalHeaderValueByName;

final Route route = optionalHeaderValueByName("X-User-Id", userId -> {
  if (userId.isPresent()) {
    return complete("The user is " + userId.get());
  } else {
    return complete("No user was provided");

// tests:
final RawHeader header = RawHeader.create("X-User-Id", "Joe42");
  .assertEntity("The user is Joe42");

testRoute(route).run(HttpRequest.GET("/")).assertEntity("No user was provided");
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.