How to set multiple cookies in pheonix?

Hello,

I was searching the documentation to find a way to set multiple session cookies from my pheonix api to my frontend, in my case a nextjs app.

I need to set a cookie with my userid and another one with my user role.

How can i set my cookies?

Also I am not looking for JWT or local storage.

Thank you in advance

I think you are searching for Plug.Conn.put_session/3, or–if you need more detailed control over the cookie itself–Plug.Conn.put_resp_cookie/4.

1 Like

Thanks that show how i can plug it in, but i am wondering how I can set them in my endpoint.

The documentation only gives this example

defmodule HelloWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :hello
. . .
  plug Plug.Session,
    store: :cookie,
    key: "_hello_key",
    signing_salt: "Jk7pxAMf"
. . .
end

Do I redo this plug again with my new key like this?


defmodule HelloWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :hello

  plug Plug.Session,
    store: :cookie,
    key: "_hello_key",
    signing_salt: "Jk7pxAMf"


  plug Plug.Session,
    store: :cookie,
    key: "_second_cookie_key",
    signing_salt: "Jk7pxAMf"

end

Then i add them like this?

put_resp_cookie(conn, “_hello_key”)
put_resp_cookie(conn, “_second_cookie_key”)

Or there is another way?

Well, Plug.Session actually just stores a single value which again is a map serialized, signed and encrypted.

If you really want to have distinct cookie values, you have no choice but to use Plug.Conn.put_resp_cookie/4 .

Can you show me an example on how to use this Plug.Conn.put_resp_cookie/4 ?

Because i can’t imagine how it looks and the documentation doesn’t provide an example in this case?

Thanks

conn = put_resp_cookie(conn, "foo", "bar")

You may need to tweak the options.

2 Likes

I think you don’t need that additional Plug.Session plug to add cookies with put_resp_cookie as @wolfiton showed in his first reply?

Also I was wondering, why do we have put_resp_cookie but no get_resp_cookie, what is the idiomatic way to retrieve one of the cookies then?

Hi @thojanssens1

We use the plug so that we can attach our cookie with the conn that will be send in to the view.
This article should explain better how plug works https://elixirschool.com/en/lessons/specifics/plug/
https://hexdocs.pm/phoenix/plug.html

so you manually sign and encrypt the value you pass to put_resp_cookie/4 right?

You can use tokens for this and create them with Phoenix token.

Then you use them in your cookie

Here is an example form the documentation

user_id = 1
token = Phoenix.Token.sign(MyApp.Endpoint, "user salt", user_id)
Phoenix.Token.verify(MyApp.Endpoint, "user salt", token, max_age: 86400)
{:ok, 1}

Here is the documentation https://hexdocs.pm/phoenix/Phoenix.Token.html

Also a good read https://phoenixframework.org/blog/sessions

1 Like