Struggling to have Flutter connect to Phoenix backend

Hello! I am struggling to connect my Flutter frontend to my Phoenix backend. The trouble is with registering a user (in the database).

This is the router.ex entry for registering a user:

post "/register", UserRegistrationController, :create

(just the default one from mix.gen.auth)

I always get the error:
debug] ** (Plug.CSRFProtection.InvalidCSRFTokenError) invalid CSRF (Cross Site Request Forgery) token

Because my frontend and backend are completely segmented, I give the client their CSRF token through an api endpoint. I have confirmed that it is received by the client, and the flutter client sends the token in its http header.
Token generation by phoenix:

  def csrf_token(conn, _params) do
    token = Plug.CSRFProtection.get_csrf_token()
    json(conn, %{csrf_token: token})

The flutter header with the token:

headers: {
'Content-Type': 'application/json',
 'X-CSRF-TOKEN': _csrfToken!,

I would appreciate advice on what could be causing this error, I have been working on it for the past few days. Thank you.

you need to disable csrf in router
pipeline if you still not work you need to enabled cors in phoenix in also use change endpoint from 127.00.1 to in config.exs for access from outside device to your computer then in flutter do not use local host point to your phoenix api please you your computer ip address instead because in mobile localhost is not the same in computer

1 Like