2

I am writing a single page application in Elm to interface with a Django backend. The Django Rest Framework provides a CSRF token in a cookie but expects all requests to contain the token in an HTTP header.

Is there a way to declaratively instruct Elm to return the CSRF token as HTTP header with each request? E.g., along the line how I would configure it in JS/Axios:

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN"

There is an old SO question that implies to manually extract the token from the cookie and then use Http.send for each request. That would mean to wrap all HTTP request functions by hand.

Ulrich Schuster
  • 1,670
  • 15
  • 24
  • Not really sure what this question provides over the linked question? – Jakub Hampl Dec 03 '21 at 11:22
  • The linked question has an answer that is five years old. A lot has changed in Elm-Land in the meantime, it seems. Therefore, I’m asking if a solution exists in the meantime. – Ulrich Schuster Dec 03 '21 at 11:29

1 Answers1

3

Using version 2.0.0 of the elm/http library, you would need to use request in order to provide headers. It's fairly common for an application to use a customized version of these "base" methods that ask for whatever your environment requires.

get httpConfig route tagger decoder =
    Http.request
        { method = "GET"
        , headers = httpConfig.headers
        , url = httpConfig.baseUrl ++ route
        , body = Http.emptyBody
        , expect = Http.expectJson tagger decoder
        , timeout = Nothing
        , tracker = Nothing
        }

post httpConfig route value tagger decoder =
    Http.request
        { method = "POST"
        , headers = httpConfig.headers
        , url = httpConfig.baseUrl ++ route
        , body = Http.stringBody "application/vnd.api+json" (Encode.encode 0 value)
        , expect = Http.expectJson tagger decoder
        , timeout = Nothing
        , tracker = Nothing
        }
bdukes
  • 152,002
  • 23
  • 148
  • 175
  • Thanks for the clarification. Implicitly, I take your answer also to mean that there is no declarative way to instruct Elm to automatically return the CSRF token from a CSRF cookie as header field. I do indeed need to write additional code to first retrieve the cookie and then add a custom header for each request. – Ulrich Schuster Dec 03 '21 at 15:24
  • @UlrichSchuster yes – viam0Zah Dec 03 '21 at 18:44
  • Right. Because of Elm's design, nothing happens "automatically", every function can only operate on its inputs (i.e. there is no such thing as global state). – bdukes Dec 03 '21 at 21:49