files/en-us/web/api/cookiestore/set/index.md
{{securecontext_header}}{{APIRef("Cookie Store API")}}{{AvailableInWorkers("window_and_service")}}
The set() method of the {{domxref("CookieStore")}} interface sets a cookie with the given name and value or options object.
set(name, value)
set(options)
This method requires one of the following:
name {{optional_inline}}
value {{optional_inline}}
Or
options {{optional_inline}}
domain {{Optional_Inline}}
null.expires {{Optional_Inline}}
null.maxAge {{Optional_Inline}}
expires and maxAge are set, the set() call fails with a TypeError. Defaults to null.name
partitioned {{Optional_Inline}}
false. If set to true, the set cookie will be a partitioned cookie. See Cookies Having Independent Partitioned State (CHIPS) for more information.path {{Optional_Inline}}
/.sameSite {{Optional_Inline}}
value
[!NOTE] While the values can be set here and will be used internally, some browsers will only return
nameandvalueoptions from {{domxref("CookieStore.get()")}} and {{domxref("CookieStore.getAll()")}}.
A {{jsxref("Promise")}} that resolves with {{jsxref("undefined")}} when setting the cookie completes.
SecurityError {{domxref("DOMException")}}
expires and maxAge properties are set.name and value or options fails in any other way.This example sets a cookie by passing a name and value of "cookie1" and "cookie1-value", respectively.
The other properties of the cookie are set with default values, as defined in the options parameter.
The code first waits for the cookie to be set: as this operation can fail, the operation is performed in a try...catch block and any errors are logged to the console.
It then gets and logs the cookie that was just set.
async function cookieTest() {
// Set cookie: passing name and value
try {
await cookieStore.set("cookie1", "cookie1-value");
} catch (error) {
console.log(`Error setting cookie1: ${error}`);
}
// Get the cookie and log its values
const cookie = await cookieStore.get("cookie1");
console.log(cookie);
}
This example sets a cookie by passing an options object with name, value, expires, and partitioned.
The code first waits for the cookie to be set: as this operation can fail, the operation is performed in a try...catch block and any errors are logged to the console.
It then gets and logs the cookie that was just set.
async function cookieTest() {
const day = 24 * 60 * 60 * 1000;
const cookieName = "cookie2";
try {
// Set cookie: passing options
await cookieStore.set({
name: cookieName,
value: `${cookieName}-value`,
expires: Date.now() + day,
partitioned: true,
});
} catch (error) {
log(`Error setting ${cookieName}: ${error}`);
console.log(error);
}
// Log the new cookie
const cookie = await cookieStore.get(cookieName);
console.log(cookie);
}
{{Specifications}}
{{Compat}}