pedestal

Doug Harvey 2025-08-07T03:14:39.212569Z

any guidance on how I handle OPTIONS / CORS in my pedestal server would be greatly appreciated

hlship 2025-08-07T16:01:27.855039Z

What specifically are you attempt to do; there is built in support for CORS that can be further configured. In terms of OPTIONS, that's just another request method (:options), like :get or :post.

Doug Harvey 2025-08-07T21:20:34.518249Z

I know that now (but didn't until last night). for example, in my routes I have

["/api/auth/token" :post [coerce-body-interceptor content-negotiation-interceptor entity-render db-interceptor user/get-token]]
the webapp is sending a OPTIONS /api/auth/token request. Do I need to add another line in my routes for an :option for the same endpoint? Does my existing route need to change as well? Is there documentation on http://pedestal.io that talks about the built-in support? thanks for any pointers you have

Doug Harvey 2025-08-08T21:40:20.698769Z

ok. I got "something" working to the point my React app is happy. My routes for these two endpoints now looks like this:

["/api/auth/token" :post [coerce-body-interceptor content-negotiation-interceptor entity-render db-interceptor user/get-token]]
    ["/api/auth/token" :options [cors-response-auth]]

    ["/api/crossing/nearby" :post [coerce-body-interceptor content-negotiation-interceptor entity-render user/decode-jwt db-interceptor crossings/crossing-query-nearby]]
    ["/api/crossing/nearby" :options [cors-response-nearby]]
and cors-response-auth is (cors-response-nearby is the same but the server complained at start-up if I tried to use the same function in the routes):
(def cors-response-auth
  {:name ::cors-response-auth
   :enter
   (fn [context]
     (assoc context :response {:status 204 :headers {"Access-Control-Allow-Origin" (get-in context [:request :headers "origin"])
                                                     "Access-Control-Allow-Headers" "*"
     "Access-Control-Allow-Methods" "GET, POST, PUT, DELETE, OPTIONS"}})
      )})
I also had to change coerce-body-interceptor to add another header
"Access-Control-Allow-Origin" (get-in context [:request :headers "origin"])
Please critique, no need to be nice about it. I would love to know how it should be done.

mdiin 2025-08-12T08:07:01.497939Z

It has been a while since I did anything with CORS, but I believe the reason the server complains when you use cors-response-auth as the last interceptor twice is that it uses the interceptor name as the route name. If you explicitly give a route name in your route definition it should stop complaining. Like so:

#{["/api/auth/token" :options [cors-response-auth] :route-name ::cors-token-options]["/api/crossing/nearby" :options [cors-response-auth] :route-name ::cors-crossing-options]}
Apologies about the formatting.