What is @fastify/helmet?
@fastify/helmet is a Fastify plugin that helps secure your Fastify applications by setting various HTTP headers. It is a wrapper around the Helmet.js library, which is widely used in the Express.js ecosystem for enhancing security.
What are @fastify/helmet's main functionalities?
Basic Usage
This code demonstrates how to register the @fastify/helmet plugin with a Fastify application to set various HTTP headers for security.
const fastify = require('fastify')();
const helmet = require('@fastify/helmet');
fastify.register(helmet);
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Custom Configuration
This code shows how to customize the configuration of @fastify/helmet, such as disabling the Content Security Policy and setting the frameguard to deny.
const fastify = require('fastify')();
const helmet = require('@fastify/helmet');
fastify.register(helmet, {
contentSecurityPolicy: false,
frameguard: { action: 'deny' }
});
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Using Specific Helmet Middleware
This code demonstrates how to use specific middleware options provided by Helmet, such as dnsPrefetchControl and referrerPolicy.
const fastify = require('fastify')();
const helmet = require('@fastify/helmet');
fastify.register(helmet, {
dnsPrefetchControl: { allow: true },
referrerPolicy: { policy: 'no-referrer' }
});
fastify.get('/', async (request, reply) => {
return { hello: 'world' };
});
fastify.listen(3000, err => {
if (err) throw err;
console.log('Server listening on http://localhost:3000');
});
Other packages similar to @fastify/helmet
helmet
Helmet is a middleware for Express.js that helps secure your application by setting various HTTP headers. It is the original library that @fastify/helmet wraps around. While @fastify/helmet is designed specifically for Fastify, Helmet is used in the Express.js ecosystem.
koa-helmet
koa-helmet is a middleware for the Koa.js framework that helps secure your application by setting various HTTP headers. It provides similar functionalities to @fastify/helmet but is designed for Koa.js applications.
@fastify/helmet
Important security headers for Fastify. It is a tiny wrapper around
helmet.
Install
npm i @fastify/helmet
Usage
Simply require this plugin, and the basic security headers will be set.
const fastify = require('fastify')()
const helmet = require('@fastify/helmet')
fastify.register(
helmet,
{ contentSecurityPolicy: false }
)
fastify.listen({ port: 3000 }, err => {
if (err) throw err
})
How it works
@fastify/helmet
is a tiny wrapper around helmet that adds an 'onRequest'
hook
and a reply.helmet
decorator.
It accepts the same options as helmet, and you can see more in the helmet documentation.
Apply Helmet to all your application routes
By passing { global: true }
into the options, @fastify/helmet
allows you to register Helmet for all your application
routes by default. If you want a more granular control on how to apply Helmet to your application you can choose to
disable it on a global scope by passing { global: false }
to the options. By default, this option is set to true
.
Example - enable @fastify/helmet
globally
fastify.register(helmet)
fastify.register(helmet, { global: true })
Example - disable @fastify/helmet
globally
fastify.register(helmet, { global: false })
fastify.get('/route-with-disabled-helmet', async (request, reply) => {
return { message: 'helmet is not enabled here' }
})
fastify.get('/route-with-enabled-helmet', {
helmet: {
dnsPrefetchControl: {
allow: true
},
frameguard: {
action: 'foo'
},
referrerPolicy: false
}
}, async (request, reply) => {
return { message: 'helmet is enabled here' }
})
fastify.get('/here-we-use-helmet-reply-decorator', async (request, reply) => {
if (condition) {
await reply.helmet()
} else {
await reply.helmet({ frameguard: false })
}
return {
message: 'we use the helmet reply decorator to conditionally apply helmet middlewares'
}
})
helmet
route option
@fastify/helmet
allows you to enable, disable, and customize helmet for each one of your application hooks by using the
helmet
shorthand route option when you register your application routes.
If you want to disable helmet for a specific endpoint you must pass { helmet: false }
to your route options.
If you want to enable or customize helmet for a specific endpoint you must pass a helmet configuration object to your
route options. E.g.: { helmet: { frameguard: false } }
.
Example - @fastify/helmet
configuration using the helmet
shorthand route option
fastify.register(helmet, { global: true })
fastify.get('/route-with-disabled-helmet', { helmet: false }, async (request, reply) => {
return { message: 'helmet is not enabled here' }
})
fastify.get('/route-with-enabled-helmet', async (request, reply) => {
return { message: 'helmet is enabled by default here' }
})
fastify.get('/route-with-custom-helmet-configuration', {
helmet: {
enableCSPNonces: true,
contentSecurityPolicy: {
directives: {
'directive-1': ['foo', 'bar']
},
reportOnly: true
},
dnsPrefetchControl: {
allow: true
},
frameguard: {
action: 'foo'
},
hsts: {
maxAge: 1,
includeSubDomains: true,
preload: true
},
permittedCrossDomainPolicies: {
permittedPolicies: 'foo'
},
referrerPolicy: false
}
}, async (request, reply) => {
return { message: 'helmet is enabled with a custom configuration on this route' }
})
Content-Security-Policy Nonce
@fastify/helmet
provide a simple way for csp nonces generation
. You can enable this behavior by passing
{ enableCSPNonces: true }
into the options. Then, you can retrieve the nonces
through reply.cspNonce
.
Note: This feature is implemented inside this module. It is not a valid option or supported by helmet.
If you need to use helmet feature only for csp nonce you can follow the example here.
Example - Generate by options
fastify.register(
helmet,
{ enableCSPNonces: true }
)
fastify.register(
helmet,
{
enableCSPNonces: true,
contentSecurityPolicy: {
directives: {
...
}
}
}
)
fastify.get('/', function(request, reply) {
reply.cspNonce.script
reply.cspNonce.style
})
Example - Generate by helmet
fastify.register(
helmet,
{
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: [
function (req, res) {
res.scriptNonce = crypto.randomBytes(16).toString('hex')
return `'nonce-${res.scriptNonce}'`
}
],
styleSrc: [
function (req, res) {
res.styleNonce = crypto.randomBytes(16).toString('hex')
return `'nonce-${res.styleNonce}'`
}
]
}
}
}
)
fastify.get('/', function(request, reply) {
reply.raw.scriptNonce
reply.raw.styleNonce
})
Disable Default helmet
Directives
By default, helmet
will add a default set of CSP directives to the response.
This behavior can be disabled by setting useDefaults: false
in the contentSecurityPolicy
configuration.
fastify.register(
helmet,
{
contentSecurityPolicy: {
useDefaults: false,
directives: {
'default-src': ["'self'"]
}
}
}
)
License
MIT