Handling CORS in Akka HTTP

DZone 's Guide to

Handling CORS in Akka HTTP

This tutorial shows a quick way for you to handle CORS requests in Akka HTTP-based microservices, with the added bonus of adding CORS headers to any HttpResponse.

· Microservices Zone ·
Free Resource

Here’s a quick tip for handling CORS requests in your Akka HTTP based microservice:

Create the following trait – CORSHandler

Handler for your Akka Http RoutesScala

trait CORSHandler{

  private val corsResponseHeaders = List(
      "Content-Type", "X-Requested-With")

  //this directive adds access control headers to normal responses
  private def addAccessControlHeaders: Directive0 = {

  //this handles preflight OPTIONS requests.
  private def preflightRequestHandler: Route = options {
      withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)))

  // Wrap the Route with this method to enable adding of CORS headers 
  def corsHandler(r: Route): Route = addAccessControlHeaders {
    preflightRequestHandler ~ r

  // Helper method to add CORS headers to HttpResponse 
  // preventing duplication of CORS headers across code
  def addCORSHeaders(response: HttpResponse):HttpResponse =


To use this trait in an actual route, we take the example route given in the Akka documentation and wrap the route with our corsHandler method defined in the above trait, as follows:

ng CORSHandler in RouteScala

get {
   // Using the CORSHandler in our actual routes 
      pathSingleSlash {
             "<html><body>Hello world!</body></html>"))
      } ~
      path("ping") {
      } ~
      path("crash") {


This trait gives us a simple way to add the CORS headers to every response that this route sends back. This CORSHandler, apart from adding response headers is also responsible for handling OPTIONS HTTP request (the preflight request) for which it sends back a 200 OK response with the header Access-Control-Allow-Methods specifying which HTTP methods can be used in subsequent calls as per the CORS specification.

This trait has a bonus method for adding CORS Headers to any HttpResponse, which is created from somewhere else in your application, say from an Exception or Rejection Handler where the response is created and sent back from a different flow than the normal route flow.

That’s it for today. Happy hacking!

akka, akka http, microservices, spring, tutorial

Published at DZone with permission of Agraj Mangal , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}