---
name: secure-node-typescript
description: 'Write secure-by-default Node.js and TypeScript applications following security best practices. Use when: (1) Writing new Node.js/TypeScript code, (2) Creating API endpoints or middleware, (3) Handling user input or form data, (4) Implementing authentication or authorization, (5) Working with secrets or environment variables, (6) Setting up project configurations (tsconfig, eslint), (7) User mentions security concerns, (8) Reviewing code for vulnerabilities, (9) Working with file paths or child processes, (10) Setting up HTTP headers or CORS.'
title: secure-node-typescript
canonical_url: https://skilld.dev/gh/joacod/skills/secure-node-typescript
last_updated: 2026-09-25T16:17:07.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> Supporting files, fetch one when the Skill refers to it: [assets/eslint-security.config.js](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/assets/eslint-security.config.js), [assets/tsconfig.secure.json](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/assets/tsconfig.secure.json), [references/authentication.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/authentication.md), [references/dependencies.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/dependencies.md), [references/error-logging.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/error-logging.md), [references/filesystem-paths.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/filesystem-paths.md), [references/http-security.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/http-security.md), [references/input-validation.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/input-validation.md), [references/operational.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/operational.md), [references/runtime-safety.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/runtime-safety.md), [references/security-index.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/security-index.md), [references/typescript-safety.md](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/references/typescript-safety.md), [scripts/audit-tsconfig.py](https://skilld.dev/api/skills-raw/joacod/skills/secure-node-typescript/scripts/audit-tsconfig.py).
>
> If the user asked to install this Skill, run `npx skilld install joacod/skills/secure-node-typescript`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/secure-node-typescript`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/joacod/skills/secure-node-typescript) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/secure-node-typescript`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/secure-node-typescript --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/secure-node-typescript --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Secure Node.js TypeScript

## Overview

Write secure-by-default Node.js and TypeScript applications that neutralize common server-side threats. This skill provides security guidelines organized by domain, with inline patterns for the most critical controls.

All guidelines are mapped to [OWASP Top 10:2025](https://owasp.org/Top10/) categories for compliance tracking and audit purposes. See `references/security-index.md` for the complete OWASP mapping.

## Security Tiers

Apply guidelines based on the code context:

| Tier         | When to Apply             | Key Focus Areas                                                                |
| ------------ | ------------------------- | ------------------------------------------------------------------------------ |
| **Always**   | All Node.js/TS code       | Strict TypeScript, input validation, no hardcoded secrets, safe error handling |
| **API/HTTP** | Web endpoints, middleware | Headers (helmet), rate limiting, CORS, body limits, Content-Type validation    |
| **Auth**     | Authentication features   | Password hashing (argon2), JWT validation, secure cookies, RBAC                |
| **Data**     | External data processing  | SQL injection, XSS sanitization, prototype pollution, schema validation        |
| **Runtime**  | Dynamic code, processes   | No eval, safe child_process, path traversal prevention                         |

## Quick Patterns

The 10 most critical security controls. Apply these by default.

### 1. Enable Strict TypeScript

```json
// tsconfig.json
{
  "compilerOptions": {
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noUncheckedIndexedAccess": true
  }
}
```

### 2. Validate All Inputs with Zod

```typescript
// DO: Schema validation at entry points
import { z } from 'zod'

const UserSchema = z.object({
  email: z.string().email(),
  age: z.number().int().min(0).max(150),
})

// In route handler
const result = UserSchema.safeParse(req.body)
if (!result.success) {
  return res.status(400).json({ error: 'Invalid input' })
}
const user = result.data // Type-safe validated data
```

### 3. Use Parameterized Queries

```typescript
// DON'T: String concatenation (SQL injection)
const query = `SELECT * FROM users WHERE id = ${userId}`

// DO: Parameterized queries
const result = await db.query('SELECT * FROM users WHERE id = $1', [userId])
```

### 4. Hash Passwords with Argon2

```typescript
import argon2 from 'argon2'

// Hash password
const hash = await argon2.hash(password, { type: argon2.argon2id })

// Verify password
const valid = await argon2.verify(hash, password)
```

### 5. Set Security Headers with Helmet

```typescript
import helmet from 'helmet'
import express from 'express'

const app = express()
app.use(helmet()) // Sets HSTS, CSP, X-Frame-Options, etc.
app.disable('x-powered-by')
```

### 6. Limit Request Body Size

```typescript
// DO: Enforce strict body limits
app.use(express.json({ limit: '1kb' })) // Adjust based on expected payload

// DON'T: Unlimited body parsing (DoS risk)
app.use(express.json())
```

### 7. Sanitize File Paths

```typescript
import path from 'node:path'

// DO: Resolve and validate paths
const ALLOWED_DIR = '/app/uploads'
const safePath = path.resolve(ALLOWED_DIR, userInput)

if (!safePath.startsWith(ALLOWED_DIR)) {
  throw new Error('Path traversal attempt blocked')
}
```

### 8. Never Expose Stack Traces

```typescript
// DO: Generic error response to clients
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error(err) // Log full error internally
  res.status(500).json({ error: 'Internal server error' }) // Generic to client
})

// DON'T: Expose error details
res.status(500).json({ error: err.message, stack: err.stack })
```

### 9. Use Environment Variables for Secrets

```typescript
// DO: Load secrets from environment
import 'dotenv/config'

const dbPassword = process.env.DB_PASSWORD
if (!dbPassword) throw new Error('DB_PASSWORD required')

// DON'T: Hardcoded secrets
const dbPassword = 'secret123' // Never do this
```

### 10. Import with node: Protocol

```typescript
// DO: Explicit Node.js built-in imports (prevents typosquatting)
import { createServer } from 'node:http'
import { readFile } from 'node:fs/promises'
import path from 'node:path'

// DON'T: Implicit imports
import { createServer } from 'http' // Could resolve to malicious package
```

## Reference Loading Guide

Load reference files based on the task at hand:

| Task                                     | Load Reference                    |
| ---------------------------------------- | --------------------------------- |
| Project setup, tsconfig, type safety     | `references/typescript-safety.md` |
| Form validation, user input, API params  | `references/input-validation.md`  |
| Login, sessions, JWT, passwords, RBAC    | `references/authentication.md`    |
| Headers, CORS, rate limiting, CSP        | `references/http-security.md`     |
| eval, child_process, prototype pollution | `references/runtime-safety.md`    |
| File uploads, path handling, regex       | `references/filesystem-paths.md`  |
| npm audit, lockfiles, supply chain       | `references/dependencies.md`      |
| Error handling, logging, monitoring      | `references/error-logging.md`     |
| Linters, CI/CD, threat modeling          | `references/operational.md`       |
| Full guideline lookup                    | `references/security-index.md`    |

## Audit Script

Validate a project's `tsconfig.json` for security-relevant settings:

```bash
python3 scripts/audit-tsconfig.py /path/to/project
```

The script checks for:

- `strict: true` enabled
- `noImplicitAny` enabled
- `strictNullChecks` enabled
- `noUncheckedIndexedAccess` enabled
- Other security-relevant compiler options

## Assets

Template configurations available in `assets/`:

- `tsconfig.secure.json` - Strict TypeScript configuration template
- `eslint-security.config.js` - ESLint security plugin configuration

Copy and adapt these to your project as a starting point.

## Resources

- Security index: `references/security-index.md`
- TypeScript safety: `references/typescript-safety.md`
- Input validation: `references/input-validation.md`
- Authentication: `references/authentication.md`
- HTTP security: `references/http-security.md`
- Runtime safety: `references/runtime-safety.md`
- Filesystem paths: `references/filesystem-paths.md`
- Dependencies: `references/dependencies.md`
- Error logging: `references/error-logging.md`
- Operational: `references/operational.md`
