serverclojurecorsgraphqlpedestal

How to set CORs using Lacinia Pedestal?


I'm setting up a lacinia-pedestal graphql server using Clojure, and attempting to access it with client-side javascript code using apollo. However, I'm unable to access the /graphql endpoint on localhost because I'm attempting to access it from a localhost origin (localhost:3000) that is not allowed by CORs. How do I set CORs using lacinia-pedestal?

Here is the server-side code (set up using the lacinia tutorial https://lacinia.readthedocs.io/en/latest/tutorial/component.html)

(ns project.server
  (:require [com.stuartsierra.component :as component]
            [com.walmartlabs.lacinia.pedestal :as lp]
            [io.pedestal.http :as http]))

(defrecord Server [schema-provider server]

  component/Lifecycle

  (start [this]
    (assoc this :server (-> schema-provider
                            :schema
                            (lp/service-map {:graphiql true})
                            http/create-server
                            http/start)))

  (stop [this]
    (http/stop server)
    (assoc this :server nil)))

(defn new-server
  []
  {:server (-> {}
               map->Server
               (component/using [:schema-provider]))})

Client-side code is super simple (using Apollo):

const client = new ApolloClient({
  uri: "http://localhost:8888/graphql"
});

Solution

  • Update: I managed to solve it by merging my lacinia pedestal service map with a standard pedestal service map.

     (start [this]
        (assoc this :server (-> schema-provider
                                :schema
                                (lp/service-map {:graphiql true})
                                (merge {::http/allowed-origins (constantly true)})
                                http/create-server
                                http/start)))