1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
= cowboy_req:parse_cookies(3)
== Name
cowboy_req:parse_cookies - Parse cookie headers
== Description
[source,erlang]
----
parse_cookies(Req) -> [{Name, Value}]
Name :: binary() %% case sensitive
Value :: binary() %% case sensitive
----
Parse cookie headers.
Alias for link:man:cowboy_req:parse_header(3)[cowboy_req:parse_header(<<"cookie">>, Req)].
When the cookie header is missing or empty, `[]` is returned.
This function will crash on invalid cookie data. Because
invalid cookies are fairly common when dealing with browsers
(because of the string interface that the Javascript API provides),
it is recommended to filter the cookie header value before
attempting to parse it. This can be accomplished by calling
the function link:man:cowboy_req:filter_cookies(3)[cowboy_req:filter_cookies(3)]
first. This does not guarantee that parsing succeeds. If it
still fails it is recommended to send an error response or
redirect with instructions to delete the relevant cookies:
.Recover from cookie parsing errors
[source,erlang]
----
Req1 = cowboy_req:filter_cookies([session_id, token], Req0),
try cowboy_req:parse_cookies(Req1) of
Cookies ->
do_something(Req1, Cookies)
catch _:_ ->
%% We can't parse the cookies we need, unset them
%% otherwise the browser will continue sending them.
Req2 = cowboy_req:set_resp_cookie(<<"session_id">>,
<<>>, Req1, #{max_age => 0}),
Req = cowboy_req:set_resp_cookie(<<"token">>,
<<>>, Req2, #{max_age => 0}),
cowboy_req:reply(500, Req)
end.
----
== Arguments
Req::
The Req object.
== Return value
The cookies are returned as a list of key/values. Keys and
values are case sensitive binary strings.
== Changelog
* *2.0*: Only the parsed header value is returned, it is no longer wrapped in a tuple.
* *2.0*: Function introduced. Replaces `cookie/2,3` and `cookies/1`.
== Examples
.Look for a specific cookie
[source,erlang]
----
Cookies = cowboy_req:parse_cookies(Req),
{_, Token} = lists:keyfind(<<"token">>, 1, Cookies).
----
== See also
link:man:cowboy_req(3)[cowboy_req(3)],
link:man:cowboy_req:parse_header(3)[cowboy_req:parse_header(3)],
link:man:cowboy_req:filter_cookies(3)[cowboy_req:filter_cookies(3)],
link:man:cowboy_req:match_cookies(3)[cowboy_req:match_cookies(3)]
|