NodeJS Security Headers: 101

NodeJS Security Headers: 101 hackernoon.com3 months ago in #Dev Love20

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’); app.use(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: app.use(helmet.contentSecurityPolicy({ 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! Comments Tags Subscribe to get your daily round-up of top tech stories!  » Read More

Like to keep reading?

This article first appeared on If you'd like to keep reading, follow the white rabbit.

View Full Article

Leave a Reply