Gathering detailed insights and metrics for @fastify/cookie
Gathering detailed insights and metrics for @fastify/cookie
Gathering detailed insights and metrics for @fastify/cookie
Gathering detailed insights and metrics for @fastify/cookie
@jollose/core
### [UTIL PARA BFF] Si se necesita dar soporte para cookies solo hay que instalar @fastify/cookie el plugin se cargará automáticamente.
@fastify/secure-session
Create a secure stateless cookie session for Fastify
@fastify/csrf-protection
A plugin for adding CSRF protection to Fastify.
@fastify/session
a session plugin for fastify
npm install @fastify/cookie
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
260 Stars
350 Commits
67 Forks
18 Watching
3 Branches
63 Contributors
Updated on 25 Nov 2024
JavaScript (85.36%)
TypeScript (14.64%)
Cumulative downloads
Total Downloads
Last day
-17.1%
51,827
Compared to previous day
Last week
6.1%
318,144
Compared to previous week
Last month
-1.9%
1,289,758
Compared to previous month
Last year
110.6%
13,136,285
Compared to previous year
2
A plugin for Fastify that adds support for reading and setting cookies.
This plugin's cookie parsing works via Fastify's onRequest
hook. Therefore,
you should register it prior to any other onRequest
hooks that will depend
upon this plugin's actions.
It is also possible to import the low-level cookie parsing and serialization functions.
@fastify/cookie
v2.x
supports both Fastify@1 and Fastify@2.
@fastify/cookie
v3 only supports Fastify@2.
1npm i @fastify/cookie
or
1yarn add @fastify/cookie
1const fastify = require('fastify')() 2 3fastify.register(require('@fastify/cookie'), { 4 secret: "my-secret", // for cookies signature 5 hook: 'onRequest', // set to false to disable cookie autoparsing or set autoparsing on any of the following hooks: 'onRequest', 'preParsing', 'preHandler', 'preValidation'. default: 'onRequest' 6 parseOptions: {} // options for parsing cookies 7}) 8 9fastify.get('/', (req, reply) => { 10 const aCookieValue = req.cookies.cookieName 11 // `reply.unsignCookie()` is also available 12 const bCookie = req.unsignCookie(req.cookies.cookieSigned); 13 reply 14 .setCookie('foo', 'foo', { 15 domain: 'example.com', 16 path: '/' 17 }) 18 .cookie('baz', 'baz') // alias for setCookie 19 .setCookie('bar', 'bar', { 20 path: '/', 21 signed: true 22 }) 23 .send({ hello: 'world' }) 24})
1import type { FastifyCookieOptions } from '@fastify/cookie' 2import cookie from '@fastify/cookie' 3import fastify from 'fastify' 4 5const app = fastify() 6 7app.register(cookie, { 8 secret: "my-secret", // for cookies signature 9 parseOptions: {} // options for parsing cookies 10} as FastifyCookieOptions)
serialize
and parse
1const { serialize, parse } = require('@fastify/cookie') 2const fastify = require('fastify')() 3 4fastify.get('/', (req, reply) => { 5 const cookie = serialize('lang', 'en', { 6 maxAge: 60_000, 7 }) 8 9 reply.header('Set-Cookie', cookie) 10 11 reply.send('Language set!') 12})
secret
(String
| Array
| Buffer
| Object
):
String
or Buffer
can be passed to use as secret to sign the cookie using cookie-signature
.Array
can be passed if key rotation is desired. Read more about it in Rotating signing secret.Object
. Read more about it in Custom cookie signer.hook
: the Fastify Hook to register the parsing of cookie into. Default: onRequest
.
algorithm
: the algorithm to use to sign the cookies. Default: sha256
.
parseOptions
: An Object
to modify the serialization of set cookies.
It is recommended to use sha256
or stronger hashing algorithm as well as a secret
that is at least 20 bytes long.
Specifies the value for the Domain
Set-Cookie
attribute. By default, no
domain is set, and most clients will consider the cookie to apply to only the current domain.
Specifies a function that will be used to encode a cookie's value. Since value of a cookie has a limited character set (and must be a simple string), this function can be used to encode a value into a string suited for a cookie's value.
The default function is the global encodeURIComponent
, which will encode a JavaScript string
into UTF-8 byte sequences and then URL-encode any that fall outside of the cookie range.
Specifies the Date
object to be the value for the Expires
Set-Cookie
attribute.
By default, no expiration is set, and most clients will consider this a "non-persistent cookie" and
will delete it on a condition like exiting a web browser application.
Note: the cookie storage model specification states that if both expires
and
maxAge
are set, then maxAge
takes precedence, but it is possible not all clients by obey this,
so if both are set, they should point to the same date and time.
Specifies the boolean
value for the HttpOnly
Set-Cookie
attribute. When truthy,
the HttpOnly
attribute is set, otherwise it is not. By default, the HttpOnly
attribute is not set.
Note: be careful when setting this to true
, as compliant clients will not allow client-side
JavaScript to see the cookie in document.cookie
.
Specifies the number
(in seconds) to be the value for the Max-Age
Set-Cookie
attribute.
The given number will be converted to an integer by rounding down. By default, no maximum age is set.
Note: the cookie storage model specification states that if both expires
and
maxAge
are set, then maxAge
takes precedence, but it is possible not all clients by obey this,
so if both are set, they should point to the same date and time.
Specifies the boolean
value for the Partitioned
Set-Cookie
attribute. When truthy, the Partitioned
attribute is set, otherwise it is not. By default, the
Partitioned
attribute is not set.
⚠️ Warning: This is an attribute that has not yet been fully standardized, and may change in the future without reflecting the semver versioning. This also means many clients may ignore the attribute until they understand it.
More information about can be found in the proposal.
Specifies the string
to be the value for the Priority
Set-Cookie
attribute.
'low'
will set the Priority
attribute to Low
.'medium'
will set the Priority
attribute to Medium
, the default priority when not set.'high'
will set the Priority
attribute to High
.More information about the different priority levels can be found in the specification.
⚠️ Warning: This is an attribute that has not yet been fully standardized, and may change in the future without reflecting the semver versioning. This also means many clients may ignore the attribute until they understand it.
Specifies the value for the Path
Set-Cookie
attribute. By default, the path
is considered the "default path".
Specifies the boolean
or string
to be the value for the SameSite
Set-Cookie
attribute.
true
will set the SameSite
attribute to Strict
for strict same site enforcement.false
will not set the SameSite
attribute.'lax'
will set the SameSite
attribute to Lax
for lax same site enforcement.'none'
will set the SameSite
attribute to None
for an explicit cross-site cookie.'strict'
will set the SameSite
attribute to Strict
for strict same site enforcement.More information about the different enforcement levels can be found in the specification.
Note: This is an attribute that has not yet been fully standardized, and may change in the future. This also means many clients may ignore this attribute until they understand it.
Specifies the boolean
value for the Secure
Set-Cookie
attribute. When truthy,
the Secure
attribute is set, otherwise it is not. By default, the Secure
attribute is not set.
Note: be careful when setting this to true
, as compliant clients will not send the cookie back to
the server in the future if the browser does not have an HTTPS connection.
Cookies are parsed in the onRequest
Fastify hook and attached to the request
as an object named cookies
. Thus, if a request contains the header
Cookie: foo=foo
then, within your handler, req.cookies.foo
would equal
'foo'
.
You can pass options to the cookie parse by setting an object named parseOptions
in the plugin config object.
The method setCookie(name, value, options)
, and its alias cookie(name, value, options)
, are added to the reply
object
via the Fastify decorateReply
API. Thus, in a request handler,
reply.setCookie('foo', 'foo', {path: '/'})
will set a cookie named foo
with a value of 'foo'
on the cookie path /
.
name
: a string name for the cookie to be setvalue
: a string value for the cookieoptions
: an options object as described in the cookie serialize documentationoptions.signed
: the cookie should be signedoptions.secure
: if set to true
it will set the Secure-flag. If it is set to "auto"
Secure-flag is set when the connection is using tls.Following are some of the precautions that should be taken to ensure the integrity of an application:
options.httpOnly
cookies to prevent attacks like XSS.options.signed
) to ensure they are not getting tampered with on client-side by an attacker.__Host-
Cookie Prefix to avoid Cookie Tossing attacks.The method clearCookie(name, options)
is added to the reply
object
via the Fastify decorateReply
API. Thus, in a request handler,
reply.clearCookie('foo', {path: '/'})
will clear a cookie named foo
on the cookie path /
.
name
: a string name for the cookie to be clearedoptions
: an options object as described in the cookie serialize
documentation. Its optional to pass options
objectThe method parseCookie(cookieHeader)
is added to the fastify
instance
via the Fastify decorate
API. Thus, fastify.parseCookie('sessionId=aYb4uTIhdBXC')
will parse the raw cookie header and return an object { "sessionId": "aYb4uTIhdBXC" }
.
Key rotation is when an encryption key is retired and replaced by generating a new cryptographic key. To implement rotation, supply an Array
of keys to secret
option.
Example:
1fastify.register(require('@fastify/cookie'), { 2 secret: [key1, key2] 3})
The plugin will always use the first key (key1
) to sign cookies. When parsing incoming cookies, it will iterate over the supplied array to see if any of the available keys are able to decode the given signed cookie. This ensures that any old signed cookies are still valid.
Note:
secret
array.Example:
1fastify.get('/', (req, reply) => {
2 const result = reply.unsignCookie(req.cookies.myCookie)
3
4 if (result.valid && result.renew) {
5 // Setting the same cookie again, this time plugin will sign it with a new key
6 reply.setCookie('myCookie', result.value, {
7 domain: 'example.com', // same options as before
8 path: '/',
9 signed: true
10 })
11 }
12})
The secret
option optionally accepts an object with sign
and unsign
functions. This allows for implementing a custom cookie signing mechanism. See the following example:
Example:
1fastify.register(require('@fastify/cookie'), { 2 secret: { 3 sign: (value) => { 4 // sign using custom logic 5 return signedValue 6 }, 7 unsign: (value) => { 8 // unsign using custom logic 9 return { 10 valid: true, // the cookie has been unsigned successfully 11 renew: false, // the cookie has been unsigned with an old secret 12 value: 'unsignedValue' 13 } 14 } 15 } 16})
The method unsignCookie(value)
is added to the fastify
instance, to the request
and the reply
object
via the Fastify decorate
, decorateRequest
and decorateReply
APIs, if a secret was provided as option.
Using it on a signed cookie will call the the provided signer's (or the default signer if no custom implementation is provided) unsign
method on the cookie.
Example:
1fastify.register(require('@fastify/cookie'), { secret: 'my-secret' }) 2 3fastify.get('/', (req, rep) => { 4 if (fastify.unsignCookie(req.cookie.foo).valid === false) { 5 rep.send('cookie is invalid') 6 return 7 } 8 9 rep.send('cookie is valid') 10})
Sometimes the service under test should only accept requests with signed cookies, but it does not generate them itself.
Example:
1 2test('Request requires signed cookie', async () => { 3 const response = await app.inject({ 4 method: 'GET', 5 url: '/', 6 headers: { 7 cookies : { 8 'sid': app.signCookie(sidValue) 9 } 10 }, 11 }); 12 13 expect(response.statusCode).toBe(200); 14});
with Signer
1const { Signer } = require('@fastify/cookie'); 2 3const signer = new Signer('secret'); 4const signedValue = signer.sign('test'); 5const {valid, renew, value } = signer.unsign(signedValue);
with sign/unsign utilities
1const { fastifyCookie } = require('@fastify/cookie'); 2 3const signedValue = fastifyCookie.sign('test', 'secret'); 4const unsignedvalue = fastifyCookie.unsign(signedValue, 'secret');
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
10 commit(s) and 3 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
Reason
security policy file detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 7
Details
Reason
Found 13/24 approved changesets -- score normalized to 5
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More