Hackernoon logoNodeJS Security Headers: 101 by@akash_tomar

NodeJS Security Headers: 101

Author profile picture

@akash_tomarAkash Tomar

Bio is WIP

When we talk about security wrt any web application its a multiple dimensional thing it will involve a number of different aspects:

  • Form validations
  • Response headers and Content Security Policyย 
  • Transport layer encryption (https)
  • Cross Site Request Forgery Tokens/ JWTs

These are just a few there would be others as well if you have SSO integration and other features as per your use case.

Today, lets just look into the setting response headers and CSP for most generic applications.ย 

Default response headers of a basic NodeJS application will look like:

To start with a good base setting let's look into the helmet package. It has a good number of middlewares for setting http headers.

npm i helmet // to install helmet
const helmet = require(โ€˜helmetโ€™);

Just using these two lines of code your response will look like:

One must be careful while setting these since misconfigured headers can cause more harm than good. For instance if you look into the X-DNS-Prefetch-Control header.

DNS prefetch greatly improves performance of your web page since it resolves DNS names even before the user actually clicks on the link, but it is considered as a information leakage vulnerability if you are creating a banking project so its better to turn it off.

Other header that helmet gives you by default are:

  • X-Frame-Options
  • Strict-Transport-Security
  • X-Download-Options
  • X-Content-Type-Options
  • X-XSS-Protection

Now that are look into something that is interesting and equally tricky, Content Security Policy

Modern web browsers allow you to restrict resources that are loaded using the Content-Security-Policy headers. It can be used to reduce risk of cross-site-scripting and click-jacking.

A very basic code example for using these header would be:

directives: {
ย ย ย ย ย  defaultSrc: ["'self'"],
ย ย ย ย ย  styleSrc: ["'self'"],
ย ย ย ย ย  scriptSrc: ["'self'", "'unsafe-inline'"],
ย ย ย  }

For the above code snippet header will look like:

default-src 'self'; style-src 'self'; script-src 'self' 'unsafe-inline'

To find more details for other directive refer docsย 

Hope this helps!

Happy Coding!


Join Hacker Noon

Create your free account to unlock your custom reading experience.