files/en-us/web/api/cookiestore/get/index.md
{{securecontext_header}}{{APIRef("Cookie Store API")}}{{AvailableInWorkers("window_and_service")}}
The get() method of the {{domxref("CookieStore")}} interface returns a {{jsxref("Promise")}} that resolves to a single cookie matching the given name or options object. The method will return the first cookie that matches.
get(name)
get(options)
This method requires one of the following:
name {{optional_inline}}
Or
options {{optional_inline}}
name
url
[!NOTE] The
urloption enables the modification of a cookie scoped under a particular URL. Service workers can obtain cookies that would be sent to any URL under their scope. From a document you may only obtain the cookies at the current URL, so the only valid URL in a document context is the document's URL.
A {{jsxref("Promise")}} that resolves with an object representing the first cookie matching the submitted name or options, or null if there is no matching cookie.
The object returned for a match contains the following properties:
domain {{experimental_inline}} {{non-standard_inline}}
expires {{experimental_inline}} {{non-standard_inline}}
name {{experimental_inline}} {{non-standard_inline}}
partitioned {{experimental_inline}} {{non-standard_inline}}
true) or not (false). See Cookies Having Independent Partitioned State (CHIPS) for more information.path {{experimental_inline}} {{non-standard_inline}}
sameSite {{experimental_inline}} {{non-standard_inline}}
secure {{experimental_inline}} {{non-standard_inline}}
true) or not (false).value {{experimental_inline}} {{non-standard_inline}}
SecurityError {{domxref("DOMException")}}
options parameter is an empty object.url option is specified but does not match the URL of the current window.url option is specified, but does not match the origin of the worker.name or options fails.This example shows how to get a particular cookie by name.
The code first creates a cookie named "cookie1" using {{domxref("CookieStore.set()")}}, logging any errors to the console.
It then waits on get() to retrieve information about that same cookie.
If the returned promise resolves with an object we log the cookie: otherwise we log that no matching cookie was found.
async function cookieTest() {
// Set test cookie
try {
await cookieStore.set("cookie1", "cookie1-value");
} catch (error) {
console.log(`Error setting cookie1: ${error}`);
}
// Get cookie, specifying name
const cookie = await cookieStore.get("cookie1");
if (cookie) {
console.log(cookie);
} else {
console.log("cookie1: Cookie not found");
}
}
cookieTest();
{{Specifications}}
{{Compat}}