DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Trending

  • The Rise of the Intelligent AI Agent: Revolutionizing Database Management With Agentic DBA
  • Continuous Quality Engineering: The Convergence of CI/CD, Chaos Testing, and AI-Powered Test Orchestration
  • Microservice Madness: Debunking Myths and Exposing Pitfalls
  • 10 Predictions Shaping the Future of Web Data Extraction Services
  1. DZone
  2. Coding
  3. Java
  4. Handling CORS in Akka HTTP

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.

By 
Agraj Mangal user avatar
Agraj Mangal
·
May. 22, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
33.2K Views

Join the DZone community and get the full member experience.

Join For Free

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(
    `Access-Control-Allow-Origin`.*,
    `Access-Control-Allow-Credentials`(true),
    `Access-Control-Allow-Headers`("Authorization",
      "Content-Type", "X-Requested-With")
  )

  //this directive adds access control headers to normal responses
  private def addAccessControlHeaders: Directive0 = {
    respondWithHeaders(corsResponseHeaders)
  }

  //this handles preflight OPTIONS requests.
  private def preflightRequestHandler: Route = options {
    complete(HttpResponse(StatusCodes.OK).
      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 =
    response.withHeaders(corsResponseHeaders)

}

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 
   corsHandler(
      pathSingleSlash {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`,
             "<html><body>Hello world!</body></html>"))
      } ~
      path("ping") {
          complete("PONG!")
      } ~
      path("crash") {
          sys.error("BOOM!")
      }
   )
}

Explanation

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 (toolkit)

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

Opinions expressed by DZone contributors are their own.

Related

  • Distributing Data and Logic: Enhancing Performance, Resilience, and Efficiency With Akka
  • All the Cloud’s a Stage and All the WebAssembly Modules Merely Actors
  • Writing a Chat With Akka
  • Video Streaming With Akka Streams

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: