spring-bootkotlincorsgraphql-kotlin

How do you handle adding a CORS header in a Spring Boot server with graphql-kotlin?


I am building a simple Spring Server project using the GraphQL Kotlin library created & open-sourced by Expedia. I have a backend up and running, talking to the datastore, and I'm able to fetch data by sending queries via Playground.

When I try to connect from my React frontend (using Apollo), the initial OPTIONS request gets a 404 response due to a CORS issue. I am relatively new to Spring Boot and there are a lot of potential approaches documented on SO and elsewhere.

How do I intercept the response & add the appropriate Access-Control-Allow-Origin header?


Solution

  • After trying many of the aforementioned approaches, I found one that worked for my particular combination of variables.

    These, for example, did not work:

    1. WebFluxConfigurer component that overrides the addCorsMappings function
    2. @CrossOrigin annotation on the query function
    3. Add the spring boot actuator lib to the project and add management.endpoints.web.cors config to the application.yml, per the Spring documentation

    What ultimately did work for me was a custom WebFilter subclass, per this SO question: Enable CORS in Spring 5 Webflux?

    and also this tutorial, which illuminated a lot about how Spring Boot works in general.