Skip to content

Snippets "Rewrite links on HTML pages" example is missing headers validation #23067

Closed
@dungahk

Description

@dungahk

Existing documentation URL(s)

What changes are you suggesting?

Add checks on whether the header exists before using it, as the get method can return null and the code calls the startsWith String method.

diff --git a/rewrite.js b/rewrite.js
index e34e765..63b4554 100644
--- a/rewrite.js
+++ b/rewrite.js
@@ -25,7 +25,13 @@ export default {
             .on("img", new AttributeRewriter("src"));
 
         const res = await fetch(request);
+        if (!res.headers.has("Content-Type")) {
+          return res;
+        }
         const contentType = res.headers.get("Content-Type");
+        if (typeof contentType !== "string") {
+          return res;
+        }
 
         // If the response is HTML, it can be transformed with
         // HTMLRewriter -- otherwise, it should pass through

Additional information

Return value of the get method: https://developer.mozilla.org/en-US/docs/Web/API/Headers/get#return_value

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions