Cookie
Framework Koa.js Cookie
Set cookie to the response
Options | Description |
---|---|
maxAge |
Sets the cookie’s expiration time in milliseconds. For example, maxAge: 1000 * 60 * 60 * 24 would set the cookie to expire after one day. |
domain |
Specifies the domain for which the cookie is valid. For example, domain: 'example.com' would set the cookie to be valid for all subdomains of example.com. |
path |
Specifies the path for which the cookie is valid. For example, path: '/' would set the cookie to be valid for all paths on the domain. |
secure |
Specifies whether the cookie can only be sent over HTTPS . For example, secure: true would set the cookie to be sent only over HTTPS. |
httpOnly |
Specifies whether the cookie can be accessed via client-side JavaScript . For example, httpOnly: true would prevent client-side JavaScript from accessing the cookie. |
sameSite |
Specifies the SameSite attribute for the cookie, which controls whether the cookie can be sent in cross-site requests . Possible values are strict , lax , or none . For example, sameSite: 'strict' would only allow the cookie to be sent in same-site requests. |
expires |
a Date object indicating the cookie's expiration date (expires at the end of session by default). |
signed |
a boolean indicating whether the cookie is to be signed (false by default ). If this is true, another cookie of the same name with the .sig suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of cookie-name=cookie-value against the first Keygrip key. This signature key is used to detect tampering the next time a cookie is received. |
overwrite |
a boolean indicating whether to overwrite previously set cookies of the same name (false by default ). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie. |
const Koa = require('koa');
const KoaApp = new Koa();
KoaApp.use(async (ctx, next) => {
ctx.cookies.set('myCookie', 'myValue', {
maxAge: 1000 * 60 * 60 * 24,
domain: 'example.com',
path: '/',
secure: true,
httpOnly: true,
sameSite: 'strict'
});
return next();
});
Delete cookie
const Koa = require('koa');
const KoaApp = new Koa();
KoaApp.use(async (ctx, next) => {
// Delete a cookie named "myCookie"
ctx.cookies.set('myCookie', null, { expires: new Date(0) });
return next();
});