Get the value of a cookie
Find one cookie by name in a Cookie header string.
function getCookie({ cookie, name }) { const match = `; ${cookie}`.split(`; ${name}=`); return match.length > 1 ? match.pop().split(';').shift() : null; }
Input & expected output
Input
{
"cookie": "theme=dark; session=abc123",
"name": "session"
}Expected output
"abc123"The edge case
Input
{
"cookie": "theme=dark",
"name": "session"
}Expected output
nullKnow the limits
- A missing cookie returns null; the original returned the whole cookie string for an unknown name.
- In a browser pass document.cookie; on a server, the request’s Cookie header.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Get the value of a cookie from the original 1loc collection by Nguyen Huu Phuoc. Copyright (c) 2020 phuoc-ng. MIT licensed.
Takes the cookie string as input and returns null for a missing name; the original returned the whole string. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Convert Celsius to Fahrenheit — Apply the temperature conversion without rounding the result.
- Convert hex to RGB — Expand #rgb if needed and read the red, green and blue channels.
- Convert URL parameters to object — Read a query string into an object; repeated keys become arrays.