Effect CommunityEC
Effect Community2mo ago
2 replies
Ofir Tadmor

Handling CORS Middleware with Error Responses in Effect Typescript

Hi All got a question about the middleware usage for cors purposes,
we got a situation where we want to allow all origins (don't ask please )
but yet we need credentinals to be true
so we can't use the given cors middleware as we need cant hardcode the origin ,instead relaying of the origin header
see this code
const setAllowedOrigins = HttpMiddleware.make((app) =>
  Effect.gen(function*() {
    const req = yield* HttpServerRequest.HttpServerRequest
    const allowedOrigins = req.headers["origin"] ?? "*"
    let response = HttpServerResponse.empty().pipe(HttpServerResponse.setStatus(204))
    if (req.method !== "OPTIONS") {
      response = yield* app
    }
    return response.pipe(
      HttpServerResponse.setHeader("access-control-allow-origin", allowedOrigins),
      HttpServerResponse.setHeader("access-control-allow-credentials", "true"),
      HttpServerResponse.setHeader("access-control-allow-methods", "GET, HEAD, PUT, PATCH, POST, DELETE"),
      HttpServerResponse.setHeader(
        "access-control-allow-headers",
        "content-type, content-range, content-disposition, content-description, authorization, traceparent, b3"
      )
    )
  })
)

for happy path everything works, but
the problem is when my app returns an error , the headers do no set on the response ( as the it doesn't reach the part where i put the header )
how do i go about it ?

Thanks alot for your effort !
Was this page helpful?