Helmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help!
These are the lines written on top of the npm's helmet page.
Most of you might have come across this code
app.use(helmet()) in your codebase/boilerplates. Let's dive deep into helmet today.
In simple words, Helmet adds/secures HTTP headers returned by your express app.
Most of the newbie devs tend to ignore this (secured HTTP headers).
helmet() is a wrapper around 15 middlewares, 11 of them are used by default with preset settings.
Let's see those 11 headers in detail:
Used for mitigating XSS Attacks. Helps control what domain/subdomain, which protocol, what kind of media should talk to the server.
As the name of this header suggests, the browser tries to resolve DNS while (in parallel) loading the page content. DNS resolution for what? - For the links, images, etc referenced on the page which is being loaded. Prefetching occurs in the background. Helps reduce latency. By default, helmet sets this as
CT in this header stands for Certificate Transparency. Catch that misissued certificate on that site.
A well-known header to prevent clickjacking up to a certain extent. Gets overridden by
frame-ancestorsdirective of Content Security Policy header.
This headers makes very less difference even if turned off. Set to
expressby default in Express framework.
or HSTS in short, tells browsers that the website should only be accessible via HTTP(S) protocol. No HTTP please! Takes one mandatory param max-age (which is 180 days in helmet) and 2 optional params includeSubDomains (defaults to true) & preload (defaults to false) in options.
Specific to Internet Explorer, this header forces potentially unsafe files and instead downloads them directly, thus preventing script injections since the file is no longer opened in the security context of the site.
helmet.noSniff sets the X-Content-Type-Options header to nosniff. Browsers in some cases try to guess the MIME types by looking at bytes of resources shared by the server. Hey Browser! Don't do that. That's MIME sniffing. Let me give you a nosniff in the Content Type Options.
Ah! That's a little tricky. Check this article for a detailed description.
Server dictates what all referrer information it needs in the
Referer(Oh yeah! That's a misspell) header via
Referrer-Policyheader. It defaults to no-referrer in case of using helmet.
Oh, Stop! I detected an xss attack.
If it's 0 - Disables XSS filtering.
If it's 1 - Enables XSS filtering. sanitize and then load if XSS is detected.
If it's 1; mode=block - Enables XSS filtering. Do not sanitize, just stop the rendering altogether.
So that was all about the 11 default headers Helmet sets. A snippet from Helmet's NPM Page: