![](/style/images/good.png)
![](/style/images/bad.png)
API with NestJS #145. Securing applications with Helmet
source link: https://wanago.io/2024/02/12/api-nestjs-helmet-security/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
![API with NestJS #145. Securing applications with Helmet](https://wanago.io/wp-content/uploads/2024/02/nest_helmet-2.png)
February 12, 2024
- 1. API with NestJS #1. Controllers, routing and the module structure
- 2. API with NestJS #2. Setting up a PostgreSQL database with TypeORM
- 3. API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
- 4. API with NestJS #4. Error handling and data validation
- 5. API with NestJS #5. Serializing the response with interceptors
- 6. API with NestJS #6. Looking into dependency injection and modules
- 7. API with NestJS #7. Creating relationships with Postgres and TypeORM
- 8. API with NestJS #8. Writing unit tests
- 9. API with NestJS #9. Testing services and controllers with integration tests
- 10. API with NestJS #10. Uploading public files to Amazon S3
- 11. API with NestJS #11. Managing private files with Amazon S3
- 12. API with NestJS #12. Introduction to Elasticsearch
- 13. API with NestJS #13. Implementing refresh tokens using JWT
- 14. API with NestJS #14. Improving performance of our Postgres database with indexes
- 15. API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
- 16. API with NestJS #16. Using the array data type with PostgreSQL and TypeORM
- 17. API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM
- 18. API with NestJS #18. Exploring the idea of microservices
- 19. API with NestJS #19. Using RabbitMQ to communicate with microservices
- 20. API with NestJS #20. Communicating with microservices using the gRPC framework
- 21. API with NestJS #21. An introduction to CQRS
- 22. API with NestJS #22. Storing JSON with PostgreSQL and TypeORM
- 23. API with NestJS #23. Implementing in-memory cache to increase the performance
- 24. API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
- 25. API with NestJS #25. Sending scheduled emails with cron and Nodemailer
- 26. API with NestJS #26. Real-time chat with WebSockets
- 27. API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authentication
- 28. API with NestJS #28. Dealing in the N + 1 problem in GraphQL
- 29. API with NestJS #29. Real-time updates with GraphQL subscriptions
- 30. API with NestJS #30. Scalar types in GraphQL
- 31. API with NestJS #31. Two-factor authentication
- 32. API with NestJS #32. Introduction to Prisma with PostgreSQL
- 33. API with NestJS #33. Managing PostgreSQL relationships with Prisma
- 34. API with NestJS #34. Handling CPU-intensive tasks with queues
- 35. API with NestJS #35. Using server-side sessions instead of JSON Web Tokens
- 36. API with NestJS #36. Introduction to Stripe with React
- 37. API with NestJS #37. Using Stripe to save credit cards for future use
- 38. API with NestJS #38. Setting up recurring payments via subscriptions with Stripe
- 39. API with NestJS #39. Reacting to Stripe events with webhooks
- 40. API with NestJS #40. Confirming the email address
- 41. API with NestJS #41. Verifying phone numbers and sending SMS messages with Twilio
- 42. API with NestJS #42. Authenticating users with Google
- 43. API with NestJS #43. Introduction to MongoDB
- 44. API with NestJS #44. Implementing relationships with MongoDB
- 45. API with NestJS #45. Virtual properties with MongoDB and Mongoose
- 46. API with NestJS #46. Managing transactions with MongoDB and Mongoose
- 47. API with NestJS #47. Implementing pagination with MongoDB and Mongoose
- 48. API with NestJS #48. Definining indexes with MongoDB and Mongoose
- 49. API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose
- 50. API with NestJS #50. Introduction to logging with the built-in logger and TypeORM
- 51. API with NestJS #51. Health checks with Terminus and Datadog
- 52. API with NestJS #52. Generating documentation with Compodoc and JSDoc
- 53. API with NestJS #53. Implementing soft deletes with PostgreSQL and TypeORM
- 54. API with NestJS #54. Storing files inside a PostgreSQL database
- 55. API with NestJS #55. Uploading files to the server
- 56. API with NestJS #56. Authorization with roles and claims
- 57. API with NestJS #57. Composing classes with the mixin pattern
- 58. API with NestJS #58. Using ETag to implement cache and save bandwidth
- 59. API with NestJS #59. Introduction to a monorepo with Lerna and Yarn workspaces
- 60. API with NestJS #60. The OpenAPI specification and Swagger
- 61. API with NestJS #61. Dealing with circular dependencies
- 62. API with NestJS #62. Introduction to MikroORM with PostgreSQL
- 63. API with NestJS #63. Relationships with PostgreSQL and MikroORM
- 64. API with NestJS #64. Transactions with PostgreSQL and MikroORM
- 65. API with NestJS #65. Implementing soft deletes using MikroORM and filters
- 66. API with NestJS #66. Improving PostgreSQL performance with indexes using MikroORM
- 67. API with NestJS #67. Migrating to TypeORM 0.3
- 68. API with NestJS #68. Interacting with the application through REPL
- 69. API with NestJS #69. Database migrations with TypeORM
- 70. API with NestJS #70. Defining dynamic modules
- 71. API with NestJS #71. Introduction to feature flags
- 72. API with NestJS #72. Working with PostgreSQL using raw SQL queries
- 73. API with NestJS #73. One-to-one relationships with raw SQL queries
- 74. API with NestJS #74. Designing many-to-one relationships using raw SQL queries
- 75. API with NestJS #75. Many-to-many relationships using raw SQL queries
- 76. API with NestJS #76. Working with transactions using raw SQL queries
- 77. API with NestJS #77. Offset and keyset pagination with raw SQL queries
- 78. API with NestJS #78. Generating statistics using aggregate functions in raw SQL
- 79. API with NestJS #79. Implementing searching with pattern matching and raw SQL
- 80. API with NestJS #80. Updating entities with PUT and PATCH using raw SQL queries
- 81. API with NestJS #81. Soft deletes with raw SQL queries
- 82. API with NestJS #82. Introduction to indexes with raw SQL queries
- 83. API with NestJS #83. Text search with tsvector and raw SQL
- 84. API with NestJS #84. Implementing filtering using subqueries with raw SQL
- 85. API with NestJS #85. Defining constraints with raw SQL
- 86. API with NestJS #86. Logging with the built-in logger when using raw SQL
- 87. API with NestJS #87. Writing unit tests in a project with raw SQL
- 88. API with NestJS #88. Testing a project with raw SQL using integration tests
- 89. API with NestJS #89. Replacing Express with Fastify
- 90. API with NestJS #90. Using various types of SQL joins
- 91. API with NestJS #91. Dockerizing a NestJS API with Docker Compose
- 92. API with NestJS #92. Increasing the developer experience with Docker Compose
- 93. API with NestJS #93. Deploying a NestJS app with Amazon ECS and RDS
- 94. API with NestJS #94. Deploying multiple instances on AWS with a load balancer
- 95. API with NestJS #95. CI/CD with Amazon ECS and GitHub Actions
- 96. API with NestJS #96. Running unit tests with CI/CD and GitHub Actions
- 97. API with NestJS #97. Introduction to managing logs with Amazon CloudWatch
- 98. API with NestJS #98. Health checks with Terminus and Amazon ECS
- 99. API with NestJS #99. Scaling the number of application instances with Amazon ECS
- 100. API with NestJS #100. The HTTPS protocol with Route 53 and AWS Certificate Manager
- 101. API with NestJS #101. Managing sensitive data using the AWS Secrets Manager
- 102. API with NestJS #102. Writing unit tests with Prisma
- 103. API with NestJS #103. Integration tests with Prisma
- 104. API with NestJS #104. Writing transactions with Prisma
- 105. API with NestJS #105. Implementing soft deletes with Prisma and middleware
- 106. API with NestJS #106. Improving performance through indexes with Prisma
- 107. API with NestJS #107. Offset and keyset pagination with Prisma
- 108. API with NestJS #108. Date and time with Prisma and PostgreSQL
- 109. API with NestJS #109. Arrays with PostgreSQL and Prisma
- 110. API with NestJS #110. Managing JSON data with PostgreSQL and Prisma
- 111. API with NestJS #111. Constraints with PostgreSQL and Prisma
- 112. API with NestJS #112. Serializing the response with Prisma
- 113. API with NestJS #113. Logging with Prisma
- 114. API with NestJS #114. Modifying data using PUT and PATCH methods with Prisma
- 115. API with NestJS #115. Database migrations with Prisma
- 116. API with NestJS #116. REST API versioning
- 117. API with NestJS #117. CORS – Cross-Origin Resource Sharing
- 118. API with NestJS #118. Uploading and streaming videos
- 119. API with NestJS #119. Type-safe SQL queries with Kysely and PostgreSQL
- 120. API with NestJS #120. One-to-one relationships with the Kysely query builder
- 121. API with NestJS #121. Many-to-one relationships with PostgreSQL and Kysely
- 122. API with NestJS #122. Many-to-many relationships with Kysely and PostgreSQL
- 123. API with NestJS #123. SQL transactions with Kysely
- 124. API with NestJS #124. Handling SQL constraints with Kysely
- 125. API with NestJS #125. Offset and keyset pagination with Kysely
- 126. API with NestJS #126. Improving the database performance with indexes and Kysely
- 127. API with NestJS #127. Arrays with PostgreSQL and Kysely
- 128. API with NestJS #128. Managing JSON data with PostgreSQL and Kysely
- 129. API with NestJS #129. Implementing soft deletes with SQL and Kysely
- 130. API with NestJS #130. Avoiding storing sensitive information in API logs
- 131. API with NestJS #131. Unit tests with PostgreSQL and Kysely
- 132. API with NestJS #132. Handling date and time in PostgreSQL with Kysely
- 133. API with NestJS #133. Introducing database normalization with PostgreSQL and Prisma
- 134. API with NestJS #134. Aggregating statistics with PostgreSQL and Prisma
- 135. API with NestJS #135. Referential actions and foreign keys in PostgreSQL with Prisma
- 136. API with NestJS #136. Raw SQL queries with Prisma and PostgreSQL range types
- 137. API with NestJS #137. Recursive relationships with Prisma and PostgreSQL
- 138. API with NestJS #138. Filtering records with Prisma
- 139. API with NestJS #139. Using UUID as primary keys with Prisma and PostgreSQL
- 140. API with NestJS #140. Using multiple PostgreSQL schemas with Prisma
- 141. API with NestJS #141. Getting distinct records with Prisma and PostgreSQL
- 142. API with NestJS #142. A video chat with WebRTC and React
- 143. API with NestJS #143. Optimizing queries with views using PostgreSQL and Kysely
- 144. API with NestJS #144. Creating CLI applications with the Nest Commander
- 145. API with NestJS #145. Securing applications with Helmet
Ensuring that our application is secure is one of the most important things we must do as developers. One of the ways to protect our application from well-known vulnerabilities is to set appropriate response headers. There are quite a lot of different security-related response headers to consider. Fortunately, the helmet library can set them for us.
Helmet maintains a set of various response headers that aim to make applications more secure. When we look at their changelog, we can see that the maintainers keep the list of headers up to date by adding new ones and deprecating headers that are no longer necessary.
In this article, we learn how to use the helmet library with NestJS and its advantages.
Using the Helmet library with NestJS
To use Helmet with NestJS, we first need to install it.
npm install helmet |
We can now use it in our bootstrap function.
main.ts
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import helmet from 'helmet'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.use(helmet()); await app.listen(3000); bootstrap(); |
Now, when we make a request to our API, we can see that it responds with various new headers. Let’s go through them.
![Screenshot-from-2024-02-10-22-09-48.png](http://wanago.io/wp-content/uploads/2024/02/Screenshot-from-2024-02-10-22-09-48.png)
Content-Security-Policy
When a cross-site scripting (XSS) attack occurs, the attacker injects malicious code into our application. This often involves JavaScript code that can harm our users, for example, by stealing their cookies.
The person carrying out the XSS attack takes advantage of the browser’s inability to distinguish between a script that is part of our application and one that the attacker adds. By setting up a Content-Security-Policy header, we can specify what resources the browser can load and execute and avoid the others.
Content-Security-Policy: script-src 'self'; |
For example, script-src 'self' tells the browser not to load any scripts from origins different than the opened page. It also prevents all inline scripts and inline event handlers from running.
If you want to know more about origins and Cross-Origin Resource Sharing (CORS), check out API with NestJS #117. CORS – Cross-Origin Resource Sharing.
There are many other rules besides script-src that Helmet sets by default, such as:
default-src 'self'; base-uri 'self'; font-src 'self' https: data:; form-action 'self'; frame-ancestors 'self'; img-src 'self' data:; object-src 'none'; script-src 'self'; script-src-attr 'none'; style-src 'self' https: 'unsafe-inline'; upgrade-insecure-requests; |
If you want to know more about them, read the article that covers the Content-Security-Policy in depth: Fighting cross-site-scripting (XSS) with content security policy.
Cross-Origin-Opener-Policy
In modern web development, websites often interact with resources from multiple origins. While this is a useful feature, it also opens up security risks.
For example, one website can open another using the window.open function. The newly opened website can then access the window object of the website that opened it through the window.opener property.
Thanks to Helmet setting the Cross-Origin-Opener-Policy header to same-origin, we isolate the browsing context. Then, the window.opener property is not available if both websites don’t have the same origin.
Cross-Origin-Resource-Policy
When a website requests resources from a different origin, it is considered a cross-origin request. Browsers implement a same-origin policy to restrict such requests. The same-origin policy allows a website to access data from another page only if both have the same origin.
We can alter this behavior through Cross-Origin Resource Sharing.
However, the same-origin policy does not prevent the browser from embedding resources from other origins. For example, it can display images using the <img> tag or play media using <video> even if those resources come from other origins. The Helmet library disallows other origins from embedding our resources by setting Cross-Origin-Resource-Policy to same-origin.
Origin-Agent-Cluster
Traditionally, browsers group websites by their origin to decide how much they should trust and isolate them. The Origin-Agent-Cluster response header is a relatively new feature that tells the browser to give a website its own resources like memory and processing power. It hints that our origin would benefit from dedicated resources and helps the browser prioritize allocating them. However, we give up a few features in exchange.
Referrer-Policy
When a browser makes an HTTP request, it includes the page’s address in the Referer request header. While it might be helpful for analytics, it might also lead to malicious tracking and leaking information.
Interestingly, Referer is a typo of the word “referrer”.
By setting the Referrer-Policy header to no-referrer, the Helmet library ensures that the browser removes the Referer header completely.
Strict-Transport-Security
Whenever we visit a website using the HTTPS protocol, and the server responds with the Strict-Transport-Security header, the browser remembers it. If we try accessing this site using HTTP, we’re automatically redirected to HTTPS instead.
This can help prevent man-in-the-middle attacks where the hacker can intercept our HTTP request and redirect us to a fake version of the site we want to visit. This could result in revealing sensitive information. However, if the website uses the Strict-Transport-Security header, the described situation can’t happen if we’ve been to the real site at least once before.
If you want to know more, check out Preventing man-in-the-middle attacks with Strict Transport Security.
X-Content-Type-Options
Websites can tell the browser to download various resources, like stylesheets, images, and JavaScript files. Each one should have a Content-Type response header. For instance, a correct header value could be text/css or image/png.
Sometimes, the Content-Type might be incorrect or missing from the response. When this happens, the browser can try to figure out the correct MIME type of the resource by itself through MIME sniffing. This can lead to issues. For instance, if our site lets users upload data to the server, an attacker could upload an HTML file but label it as image/png. When other users download and open this file, it could set the stage for an XSS (Cross-Site Scripting) attack.
Fortunately, the Helmet library sets the X-Content-Type-Option response header to nosniff. This stops the browser from inspecting the file if the MIME type is missing. Therefore, always ensuring we send the correct Content-Type response header is crucial.
If you would like to read more, go to Countering MIME sniffing with X-Content-Type-Options and Content-Type headers.
X-Download-Options
Using the Helmet middleware offers enhancements even for Internet Explorer 8. It is a problem when an IE8 user downloads an HTML file and opens it directly rather than saving it first. This causes the browser to execute the HTML file in the context of the website it was downloaded from.
By setting the X-Download-Options header to noopen, the Helmet library prevents Internet Explorer 8 from opening a file directly before saving it.
X-DNS-Prefetch-Control
Browsers send DNS queries to translate a domain name into an IP address. Although DNS requests use minimal bandwidth, the delay they cause can add up. If we can anticipate which hostnames we’ll need, we can look them up in advance to save time.
<link rel="dns-prefetch" href="https://wanago.io"> |
Unfortunately, some attackers might take advantage of the DNS prefetching. The Helmet library turns it off by sending the X-DNS-Prefetch-Control response header set to off.
X-Frame-Options
Clickjacking is an attack that makes use of iframes. Picture an attacker setting up a website with various buttons. Over these buttons, they overlay a transparent iframe that displays another page.
The attacker aligns the invisible iframe with the buttons. When the user attempts to click on them, they actually end up clicking on the invisible buttons within the iframe. This action hijacks the user’s click, which is called clickjacking.
Using the X-Frame-Options header, we can control whether the browser can render a page in an iframe. Helmet, by default, sets the header’s value to SAMEORIGIN. This tells the browser to allow the page to be displayed in an iframe only on websites with the same origin.
If you want to know more about clickjacking, check out The danger of iframe clickjacking and how to deal with it
X-Permitted-Cross-Domain-Policies
Programs like Adobe Flash Player and Adobe Acrobat can include website content in documents. By default, they block all cross-domain requests similarly to browsers. This behavior can be changed by supplying a prepared crossdomain.xml policy file. If an attacker manages to insert it, it can modify the cross-domain policy for certain Adobe products.
The Helmet library sets the X-Permitted-Cross-Domain-Policies response header to none and disallows the crossdomain.xml files.
X-XSS-Protection
The X-XSS-Protection header is a feature of browsers that prevents a page from loading if the browser detects the XSS attack. However, this feature has become obsolete, particularly with adopting the Content-Security-Policy header, which provides a more effective way to handle such security risks.
Additionally, it was found that the X-XSS-Protection feature could introduce certain problems. Therefore, the Helmet library sets X-XSS-Protection to to disable it.
X-Powered-By
The X-Powered-By response header specifies the technology our application uses under the hood. Since NestJS uses Express by default, all our endpoints respond with X-Powered-By: Express.
While security by obscurity is not enough to keep our application safe, some people believe it is not a good idea to let potential attackers know that we are using Express. Because of that, the Helmet library removes the X-Powered-By header.
Summary
In this article, we’ve gone through the Helmet library by explaining how to use it in our NestJS project and what advantages it gives us. Helmet enhances web application security by setting various HTTP headers that can help protect against a range of web vulnerabilities such as Cross-Site Scripting (XSS), clickjacking, and other exploits. Most of the headers set by Helmet are especially useful when we use NestJS to serve a website. However, headers such as Strict-Transport-Security or X-Content-Type-Options can be helpful if we develop a REST API.
Incorporating Helmet into your NestJS projects, whether for serving websites or API development, significantly boosts our application’s defense against common security threats.
Series Navigation<< API with NestJS #144. Creating CLI applications with the Nest Commander
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK