Join our Newsletter — 33% off our NHI Course
Home› Guides› TypeScript and JavaScript Secure Coding Guide: Language Pitfalls…
Guide Application Security

TypeScript and JavaScript Secure Coding Guide: Language Pitfalls and Safer Patterns

PDF for newsletter subscribers · free to read online

← All guides
By NHI Mgmt Group, edited by Lalit Choda Updated 27 October 2026 14 min read
On this page

TypeScript makes JavaScript code easier to reason about, but its types disappear at compile time, so they cannot protect a program from the data an attacker actually sends. Many security defects in front-end and server-side JavaScript come from the language itself rather than any framework: dynamic code execution through eval and its relatives, HTML injection sinks in the DOM, prototype pollution through ordinary objects, loose equality and type coercion, and regular expressions that backtrack for minutes. This guide covers those language-level pitfalls, what the TypeScript compiler can and cannot catch, safer patterns for each, how to enforce them with compiler flags, lint rules and browser policies, and how to measure progress. It is written for developers, reviewers and application security engineers working in any JavaScript runtime; framework-specific advice lives in the React and Next.js Security Guide, the Angular Security Guide and the Node.js Security Guide.

Key takeaways

  • Types are erased. The TypeScript handbook states that type annotations never change runtime behaviour, and type assertions carry no runtime check, so every value from outside the process needs runtime validation.
  • Remove dynamic code execution. eval, new Function and string arguments to setTimeout and setInterval are injection sinks; there is almost always a data-driven alternative.
  • Write text, not HTML. Use textContent and DOM construction instead of innerHTML and document.write, and enforce it in the browser with Trusted Types.
  • Do not use plain objects as dictionaries for untrusted keys. Map, Set, Object.create(null) and Object.hasOwn prevent prototype pollution and object injection.
  • Make the compiler and linter do the policing. strict, noUncheckedIndexedAccess, noEmitOnError and lint rules banning any and implied eval turn these rules into build failures.

What TypeScript does and does not protect

TypeScript checks code against declared types and then emits JavaScript with the types removed. That makes it excellent at catching internal mistakes and useless as an input filter.

FeatureWhat the compiler guaranteesWhat happens at runtime
Type annotation (req.body as LoginRequest, function f(id: number))Callers inside the codebase pass the declared typeNothing. An HTTP body, postMessage payload or JSON.parse result can be any shape
Type assertion (as, <T>)None; the developer overrides the checkerThe handbook notes there is no runtime checking and no exception if the assertion is wrong
Non-null assertion (value!)NoneRemoves null and undefined from the type without checking
anyDisables further type checking for that valueErrors propagate silently through every property access
unknownForces narrowing before useSame value, but the code must check it first
Emitting with errorsBy default tsc still emits JavaScript when there are type errorsCode that failed type checking can ship unless noEmitOnError is set or CI fails on errors

Validate at every trust boundary

  • Type external data as unknown: request bodies, query parameters, headers, cookies, localStorage, message events, WebSocket frames, environment variables and third-party API responses enter as unknown, not as a domain type.
  • Parse, then trust: run a schema validator (JSON Schema validators or TypeScript-first schema libraries) that rejects unknown properties and returns a typed value only after checks pass. Derive the TypeScript type from the schema so the two cannot drift.
  • Allowlist properties: copy the fields an operation needs instead of spreading a request body into a model ({...req.body}), which is how mass assignment happens. ASVS 5.0 V15.3.3 requires limiting the fields each action may set.
  • Validate on the server: client-side TypeScript validation is a usability feature. See the Input Validation and Output Encoding Guide.

Dynamic code execution: eval and its relatives

MDN describes eval() as an injection sink: its argument is parsed and executed as JavaScript with the caller's privileges, and direct eval can read and change variables in the surrounding scope. ASVS 5.0 V1.3.2 requires applications to avoid eval() and other dynamic code execution features.

Dangerous patternWhySafer replacement
eval(str), indirect (0, eval)(str)Executes arbitrary code; direct eval also exposes local scopeData structures, lookup tables, a purpose-built expression parser
new Function(str), AsyncFunction constructorParses a string as a function body; still implicit evaluationPre-written functions selected from an allowlisted map
setTimeout("doThing()", 1000), setInterval(str)String argument is compiled as codesetTimeout(() => doThing(), 1000)
eval("(" + json + ")")Executes anything embedded in the "JSON"JSON.parse(json) followed by schema validation
eval("obj." + name)Code injection through the property nameobj[name] only after checking name against an allowlist; MDN warns that unconstrained bracket access enables object injection
String event handlers (el.setAttribute("onclick", str))Compiled as code when the event firesel.addEventListener("click", handler)
Server-side template or VM evaluation of user inputServer-side code executionLogic-less templates; never treat a VM context as a security sandbox

Enforce it: a Content Security Policy with script-src or default-src blocks eval by default unless 'unsafe-eval' is present, so keeping 'unsafe-eval' out of the policy turns any remaining eval into a visible error. Where a library genuinely needs evaluation, MDN describes the 'trusted-types-eval' keyword with require-trusted-types-for 'script' as safer than 'unsafe-eval', because it only allows eval where Trusted Types are enforced. In the build, enable ESLint's no-eval, no-implied-eval and no-new-func rules. See the Content Security Policy Guide.

DOM injection sinks and safe rendering

The Trusted Types API documentation groups the dangerous browser APIs into three families. Any untrusted string reaching one of them is a DOM XSS candidate.

Sink familyExamplesSafe alternative
HTML sinksinnerHTML, outerHTML, insertAdjacentHTML(), document.write(), DOMParser.parseFromString(), iframe.srcdoc, Range.createContextualFragment()textContent, createElement plus append; a sanitiser such as DOMPurify only when markup must be rendered
JavaScript sinkseval(), Function(), script.text and script.textContent, string setTimeout, event-handler attributes via setAttributeFunctions and listeners, never strings
Script URL sinksscript.src, new Worker(url), importScripts(), serviceWorker.register()Fixed, same-origin or allowlisted URLs
Navigation and URL attributeslocation.href = input, a.href, window.open(input)Parse with new URL() and allow only https: (and known hosts); ASVS 5.0 V1.2.2 asks applications to block javascript: and data:
  • setAttribute is not automatically safe: OWASP's DOM-based XSS cheat sheet notes it is safe only for non-executing attributes such as title, class and value, not on* handlers, href or src.
  • JSON.stringify is not output encoding: embedding its output in an inline <script> block can still break out of the script context; serve data as JSON from an endpoint or a type="application/json" element read with textContent.
  • Trusted Types: with the CSP directive require-trusted-types-for 'script', assigning a plain string to a sink throws a TypeError; code must pass TrustedHTML, TrustedScript or TrustedScriptURL objects created by a named policy, and the trusted-types directive allowlists policy names. MDN lists the API as Baseline 2026, newly available since February 2026, so older browsers may lack it; use a default policy only as a migration aid. See the Trusted Types and DOM XSS Prevention Guide.
  • DOM clobbering: HTML elements with id or name attributes can shadow global variables. ASVS 5.0 V3.2.3 asks for explicit declarations, strict type checks and no globals stored on document.

See the Cross-Site Scripting (XSS) Prevention Guide for encoding contexts in depth.

Objects, prototypes and dynamic property access

Every ordinary JavaScript object inherits from Object.prototype. Code that merges, clones or assigns properties using keys from untrusted input can write to __proto__, constructor or prototype and change the behaviour of every object in the process. ASVS 5.0 V15.3.6 requires code that prevents prototype pollution, for example by using Set() or Map() instead of object literals.

  • Use Map and Set for keyed data: lookups do not touch the prototype chain, which is OWASP's first recommendation in the Prototype Pollution Prevention Cheat Sheet.
  • Null-prototype objects: where a plain object is needed, create it with Object.create(null) so there is no prototype to pollute.
  • Own-property checks: use Object.hasOwn(obj, key), which MDN recommends over hasOwnProperty() because it works on null-prototype objects and cannot be overridden; the in operator also sees inherited properties.
  • Reject dangerous keys in merge and set-by-path helpers: refuse __proto__, constructor and prototype as path segments, and prefer maintained libraries that already do so.
  • Freeze prototypes as defence in depth: Object.freeze(Object.prototype) blocks additions, but freezing is shallow and may break libraries that patch built-ins, so test first. On Node.js the --disable-proto=delete flag removes __proto__, though constructor.prototype remains reachable.
  • Left-hand-side input: OWASP warns against untrusted data on the left of an assignment (window[userInput] = ...); add an allowlist between input and property name.

See the Prototype Pollution Guide.

Equality, coercion and type confusion

JavaScript's loose operators convert types before comparing, and TypeScript's types do not survive to runtime to stop it. ASVS 5.0 V15.3.5 requires explicit type checks and strict equality to avoid type juggling.

PitfallExample of the riskPattern
Loose equality =="0" == 0 and null == undefined are true, so a role or flag comparison can match unexpected inputAlways === and !==; enable the eqeqeq lint rule
Truthiness checks on security valuesif (user.isAdmin) accepts the string "false" from a parsed bodyCompare against the exact boolean after schema validation
Array where a string was expectedA query string such as ?role=a&role=b becomes an array in many parsers, so role.includes("admin") behaves differentlyValidate type as well as value. See the HTTP Parameter Pollution and Parser Differential Guide
Object where a primitive was expectedNoSQL operators such as {"$ne": null} passed as a password fieldReject non-string values for string fields before building queries
Number precisionIDs above Number.MAX_SAFE_INTEGER lose precision after JSON.parse, so two records can share an IDTransmit large IDs as strings or use BigInt
Unchecked index accessmap[key] typed as defined when it may be undefinedEnable noUncheckedIndexedAccess

Regular expressions and the event loop

Backtracking regex engines, including the default engine in JavaScript runtimes, can take exponential time on crafted input when a pattern contains a repeated group that itself contains repetition or overlapping alternation, such as (a+)+$ or (a|aa)+$, as the OWASP ReDoS description explains. Because JavaScript runs application code on a single event loop, one slow match blocks every other request on a Node.js process and freezes the page in a browser. ASVS 5.0 V1.3.12 requires regular expressions free of exponential backtracking, and V1.2.9 requires escaping metacharacters when user input becomes part of a pattern.

  • Never build a pattern from raw input (new RegExp(userInput)); escape it or use string methods such as includes and startsWith.
  • Bound input length before matching, and anchor patterns.
  • Lint for unsafe patterns with a regex-safety rule in CI, and review nested quantifiers by hand.
  • Move heavy matching off the main thread to a worker with a timeout where patterns must stay complex.

See the Regular Expression Denial of Service (ReDoS) Guide.

Compiler and lint settings that enforce the rules

SettingEffect
"strict": trueTurns on the strict family, including noImplicitAny, strictNullChecks, strictFunctionTypes, strictPropertyInitialization, useUnknownInCatchVariables and alwaysStrict
noUncheckedIndexedAccessAdds undefined to index-signature reads such as process.env.X, forcing a check; not part of strict
exactOptionalPropertyTypesDistinguishes an absent property from one set to undefined; not part of strict
noEmitOnErrorStops tsc emitting JavaScript when type checking fails
Lint: no-eval, no-implied-eval, no-new-func, eqeqeqBlocks dynamic code and loose equality
Lint (typescript-eslint): no-explicit-any, no-unsafe-assignment, no-unsafe-member-access, no-non-null-assertionStops any and assertions from leaking unvalidated data
CSP without 'unsafe-eval' or 'unsafe-inline', plus require-trusted-types-for 'script'Runtime enforcement in the browser

Rolling it out

  1. Measure first: run the linter with the new rules in warning mode and count violations per rule and per package.
  2. Fix the sinks: remove eval and string timers, then replace HTML sinks with text APIs or a single sanitising wrapper.
  3. Turn on compiler flags package by package, starting with code that handles requests and messages; add noEmitOnError to the build.
  4. Deploy Trusted Types in report-only mode (Content-Security-Policy-Report-Only) and collect violation reports before enforcing.
  5. Enforce: make lint rules errors in CI, switch the CSP to enforcing, and keep the report-only header for new code paths. Roll back by reverting the header, not by re-adding 'unsafe-eval'.

Detection and measurement

  • CSP and Trusted Types violation reports: collect them centrally; a spike after a release usually means a new sink, and reports from unknown script origins can indicate injection.
  • Static analysis findings: track SAST rules for code injection, DOM XSS, prototype pollution and ReDoS by repository. See the SAST Triage Guide.
  • Server-side errors: schema validation failures and event-loop lag alerts in Node.js services show both probing and ReDoS attempts.

Metrics:

  • Count of eval, new Function and string timer calls in first-party code (target zero).
  • Count of HTML sink assignments outside the approved sanitising wrapper.
  • Share of packages compiling with strict and noUncheckedIndexedAccess.
  • Number of any, as casts and ! assertions at trust boundaries, trending down.
  • Trusted Types violations per week after enforcement.
  • Share of external inputs passing through a schema validator.

Common failure patterns

  • Casting the request body: const input = req.body as CreateUser treated as validated, so extra fields such as role reach the database.
  • One innerHTML for convenience: a notification or rich-text widget writes server data through innerHTML, and stored content becomes script.
  • Deep merge of user settings: a home-grown merge(defaults, userJson) walks __proto__ and sets an isAdmin default on every object.
  • Regex validation of email or URLs from the internet with nested quantifiers, letting one request stall a Node.js service.
  • Secrets in the bundle: API keys placed in front-end environment variables that the bundler inlines, readable in every user's browser. See the Secrets Management Guide.
  • Type errors ignored in CI because the build emits anyway, so the strict settings exist only on developer machines.

Framework mapping

PracticeOWASP ASVS 5.0NIST SP 800-53 Rev. 5NIST CSF 2.0
Runtime validation of external inputV2.2.2, V15.3.3SI-10PR.PS-06
No dynamic code executionV1.3.2SI-10PR.PS-06
Safe DOM rendering and URL handlingV3.2.2, V3.2.3, V1.2.2SI-10PR.PS-06
Prototype pollution preventionV15.3.6SI-10PR.PS-06
Strict equality and type checksV15.3.5SI-10PR.PS-06
ReDoS-safe regular expressionsV1.3.12, V1.2.9SI-10PR.PS-06
Compiler, lint and SAST in the pipelinen/aSA-11, SA-15PR.PS-06

For threat modelling, ATT&CK T1059.007 JavaScript covers attacker-run script, and T1189 Drive-by Compromise covers malicious script delivered through compromised pages. ISO/IEC 27001:2022 Annex A control A.8.28 Secure coding is the natural home for these rules.

Practitioner checklist

  • All external data is typed as unknown and validated with a schema before use; no as casts on request bodies or message payloads.
  • First-party code contains no eval, new Function or string timers, and lint rules block new ones.
  • Untrusted text reaches the DOM only through textContent or a single reviewed sanitising wrapper.
  • Trusted Types run in report-only and then enforced mode, with an allowlisted set of policy names.
  • CSP omits 'unsafe-eval' and 'unsafe-inline'.
  • Untrusted keys go into Map or null-prototype objects; merge helpers reject __proto__, constructor and prototype.
  • Strict equality is enforced and security flags are compared to exact values.
  • Regular expressions are reviewed for nested quantifiers, input length is bounded, and patterns are never built from raw input.
  • strict, noUncheckedIndexedAccess and noEmitOnError are on, and CI fails on type errors.
  • No secrets are injected into client bundles.

Standards and references

Related NHI Mgmt Group resources: Trusted Types and DOM XSS Prevention Guide · Prototype Pollution Guide · Client-Side Security Guide · Secure Code Review Guide · Input Validation and Output Encoding Guide

PDF for subscribers

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. Subscribe to our weekly NHI & AI Identity Journal and we’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Researched and written by the NHI Mgmt Group editorial team using AI tools, under the editorial direction of Lalit Choda. Facts are drawn from the sources listed on this page and checked by our automated quality process. Last updated 27 October 2026. Spotted an error? Use our contact page.
NHI Mgmt Group, the independent authority on Non-Human Identity, IAM and Agentic AI security. nhimg.org

PDF Downloads for Newsletter Subscribers

Get the guide

Enter your details and we’ll email you a download link.

The full guide is free to read online. The PDF is a thank you for subscribing.

Fill in all fields marked * and tick the PDF box to continue.