Get the value of a cookie

Find one cookie by name in a Cookie header string.

JavaScript Version 1.0.0 · MIT · .md

get-the-value-of-a-cookie.js
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

null

Know 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.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.