Practical coding, configuration, and process rules to build, operate, and audit GDPR & HIPAA-compliant web/API services with TypeScript, Node.js, and Express/NestJS.
Failed a compliance audit recently? You're not alone. Most development teams discover compliance gaps during audits when fixing them costs 10x more than building them right from the start.
Every developer has been there: building features fast, shipping code, then suddenly facing a compliance audit that reveals your application processes personal data without proper consent mechanisms, stores PHI in plain text, or lacks the audit trails required by law.
The real problem isn't understanding GDPR or HIPAA requirements—it's consistently implementing compliant patterns while maintaining development velocity. You end up with:
These Cursor Rules establish privacy-by-design patterns as your default TypeScript development approach. Instead of retrofitting compliance, you'll build applications that are compliant by construction.
Every controller, service, and data model follows consistent security patterns. Every data access gets logged. Every piece of PHI gets encrypted. Every user consent is properly tracked and enforced.
Automated Compliance Evidence Collection
Security-First Development Patterns
Proactive Risk Management
Streamlined Multi-Framework Support
Before: Manually implementing HIPAA controls for each endpoint, forgetting audit logs, storing PHI in plain text during development.
After:
@UseGuards(ConsentGuard, RbacGuard, MfaGuard)
@Controller('patients')
export class PatientController {
@Post()
async create(@Body() dto: CreatePatientDto, @Req() req: Request) {
assertLawfulBasis(req, 'consent'); // Auto-validates GDPR lawful basis
return this.svc.create(dto, req.context.userId); // Encrypted storage by default
}
}
Every controller automatically enforces consent, role-based access, and MFA. The framework handles audit logging, data encryption, and lawful basis validation without manual intervention.
Before: Building custom endpoints for GDPR data exports, deletion requests, and consent management—each with different patterns and potential security gaps.
After: Data subject rights become standardized service methods:
// Automatic data discovery across all models
await this.dataSubjectService.exportData(userId);
// Compliant deletion with audit trail
await this.dataSubjectService.deleteData(userId, 'withdrawal_of_consent');
The rules ensure consistent handling of data subject requests with proper audit trails and encrypted exports.
Before: Remembering to encrypt sensitive fields manually, managing keys inconsistently, dealing with performance impacts of encryption/decryption.
After: Field-level encryption becomes transparent:
@Entity()
export class Patient {
@Encrypted({ key: 'patient-data' })
@Column()
socialSecurityNumber: string; // Automatically encrypted in database
@Encrypted({ key: 'patient-data' })
@Column()
medicalRecord: string; // Uses envelope encryption with KMS
}
Encryption keys rotate automatically, performance stays optimized with read replicas, and compliance requirements are met by default.
npm install zod @casl/ability argon2 helmet express-rate-limit
npm install --save-dev @typescript-eslint/eslint-plugin
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"exactOptionalPropertyTypes": true,
"useUnknownInCatchVariables": true
}
}
The rules automatically organize your compliance-focused code:
src/
modules/<feature>/
controller.ts // HTTP layer with guards
service.ts // Business logic with audit logging
dto.ts // Zod schemas + OpenAPI generation
model.ts // Encrypted data models
policy.ts // RBAC rules as code
Pre-commit: Schemas validated, sensitive data scanning
CI Pipeline: OpenSCAP security scans, compliance evidence generation
Release: DPIA regeneration, RoPA updates, audit log verification
Measurable Compliance Improvements:
Development Velocity Benefits:
Risk Reduction:
Start building compliance into your development workflow today. Your future audit self will thank you.
You are an expert in TypeScript, Node.js (Express/NestJS), PostgreSQL, AWS, Terraform, Kubernetes, OpenAPI, GDPR, and HIPAA.
Key Principles
- Privacy-by-Design & Default: architect every feature to minimise personal data collection and retention.
- Automate everything: discovery, classification, scanning, testing, evidence collection.
- Treat compliance failures as P0 incidents; fail closed, not open.
- Immutable audit trails: every access, change, and deletion must be logged, tamper-evident, and retained per regulation (6 yrs HIPAA / defined GDPR ROPA lifecycle).
- Defence in depth: encryption, RBAC, MFA, network segmentation, continuous monitoring.
- Document and map each data flow; keep RoPA (Records of Processing Activities) version-controlled.
TypeScript
- Enable `strict`, `noImplicitAny`, `exactOptionalPropertyTypes`, `useUnknownInCatchVariables` in tsconfig.
- Use `interface` for DTOs exposed via OpenAPI; use `type` for internal utility unions.
- Use `zod` (or `@sinclair/typebox`) schemas co-located with DTOs for runtime validation; generate OpenAPI specs from schemas.
- Never store PHI/PII in enums, environment variables, or code comments.
- Directory convention:
src/
modules/<feature>/
controller.ts // HTTP entry
service.ts // business logic
dto.ts // interfaces + zod
model.ts // prisma/sequelize model
policy.ts // access-control rules
- Naming: use descriptive, affirmative names (`isEncrypted`, `hasConsent`).
- Do NOT disable ESLint privacy/security rules (e.g., `@typescript-eslint/no-unsafe-member-access`).
Error Handling & Validation
- Catch boundary: HTTP layer — convert thrown `ComplianceError` & `ValidationError` to 4xx with structured body: `{ code, title, detail, correlationId }`.
- Validate headers, params, body, and scopes with zod before touching business logic.
- On validation failure, log redacted payload (mask PHI) and return `400`.
- Use early returns for failures; the happy path last.
- Breach/incident workflow: any `SecurityIncidentError` triggers async publish to `security.incidents` Kafka topic; dedicated worker files 24-hr GDPR/HIPAA notifications.
Framework: Express & NestJS
- Prefer NestJS for modularity; controllers must declare `@UseGuards(ConsentGuard, RbacGuard, MfaGuard)`.
- Express: mount `helmet`, `csurf`, `hpp`, `express-rate-limit` globally.
- Use `cookie-parser` with `sameSite=strict`, `secure`, `httpOnly` flags; obtain explicit opt-in via CMP before setting non-essential cookies.
- All controllers return typed DTOs; response serialization MUST strip internal fields (`stripUnknown:true`).
- Always pipe DB queries through an ORM that supports field-level encryption (e.g., TypeORM + `typeorm-encrypted`).
Additional Sections
Security & Cryptography
- Encrypt all PHI/PII at rest (AES-256-GCM) and in transit (TLS 1.3, fips-compliant ciphers).
- Store encryption keys in AWS KMS with automatic rotation ≤ 365 days.
- Derive data keys per tenant with Envelope Encryption.
- Hash user passwords with Argon2id (≥ 3 iterations, memory ≥ 64 MiB).
- Implement MFA (TOTP or WebAuthn) for all privileged roles.
- Apply role-based access control (RBAC) via CASL/OPA; policies stored as code.
Data Discovery & Classification
- Integrate Cyera/Microsoft Purview scanner in CI nightly to label S3, RDS, Logs buckets; push findings to Security Lake.
- Tag datasets using the format `privacy:<classification>` (e.g., `privacy:phi`)
Logging & Monitoring
- Use structured JSON logs (pino/winston) with fields: `timestamp`, `service`, `traceId`, `userId`, `dataClassification`.
- Mask data by default; only log last 4 chars of identifiers.
- Forward logs to SIEM; create anomaly dashboards for data-access frequency.
Testing
- Unit: validate zod schemas against positive & negative fixtures.
- Integration: run Postman/Newman collection with mock PHI tokens.
- Compliance: schedule weekly OpenSCAP / Trivy scans; fail build if findings ≥ medium.
- Annual HIPAA Security Rule audit: automate via Scytale API; export PDF evidence.
- PTaaS quarterly; patch CVEs within 30 days (7 days for critical).
Performance & Scalability
- Leverage read-replicas; never replicate decrypted columns.
- Cache tokenised data, not raw PII.
- Use gzip/brotli with `vary:accept-encoding` while stripping sensitive response headers.
Infrastructure (IaC)
- Terraform: enable AWS Config rules `encrypted-volumes`, `restricted-ssh`, `cloudtrail-enabled`.
- Kubernetes: enforce `PodSecurityStandard:restricted`, default seccomp, fsGroup.
- Use NetworkPolicies to isolate `phi-services` namespace.
Documentation & Evidence
- Each PR must update CHANGELOG and, when touching data models, the RoPA markdown.
- Generate Data Protection Impact Assessment (DPIA) PDF on prod releases using `dpia-cli`.
- Store signed Business Associate Agreement (BAA) & Data Processing Agreement (DPA) PDFs in `/compliance/docs`.
Common Pitfalls
- Forgetting to log lawful basis → add `@LawfulBasis("consent"|"contract"|...)` decorator.
- Storing raw IP addresses without truncation/anonymisation.
- Delayed revocation of ex-employee access; integrate HR off-boarding webhook to IAM.
Example: Secure Controller (NestJS)
```ts
// src/modules/patient/controller.ts
@UseGuards(ConsentGuard, RbacGuard, MfaGuard)
@ApiBearerAuth()
@Controller('patients')
export class PatientController {
constructor(private readonly svc: PatientService) {}
@Post()
async create(@Body() dto: CreatePatientDto, @Req() req: Request) {
assertLawfulBasis(req, 'consent'); // throws ComplianceError if missing
return this.svc.create(dto, req.context.userId);
}
}
```
Release Checklist
- [ ] All schemas validated
- [ ] OpenAPI diff reviewed
- [ ] DPIA regenerated
- [ ] SIEM alert threshold adjusted if new endpoints added
- [ ] RoPA updated & committed
- [ ] All secrets rotated if scope change