Search code examples
securityhaskellhttp-headersyesod

How can I add an header to all endpoints in Yesod appication?


I have an application. I need to add an specific header to all responses. It's clear how to do it with an specific endpoint using addHeader.

Let's say this one: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

Question:

How can I configure an header once for all endpoints?


Solution

  • You can alter the yesodMiddleware :: Yesod site => HandlerFor site res -> HandlerFor site res field in the instance Yesod App of your App. For example with:

    instance Yesod App where
        -- ...
        yesodMiddleware handler = do
            addHeader "X-Frame-Options" "sameorigin"
            defaultYesodMiddleware handler

    The yesodMiddleware is thus functionality that is "wrapped around" the target handler. You can do tasks before you query the handler, and after the handler (for example to postprocess the result).