Catalogue / typescript-fullstack-patterns
typescript-fullstack-patterns
Older skill: source not recordedSignedBuilds typed JavaScript and TypeScript backends and frontends: layered Express services over an explicit repository contract, validated DTOs, race-safe React data hooks and auth context, and unit plus integration tests with fresh fakes. Use when the user asks to "build a TypeScript API", "add an Exp…--- name: typescript-fullstack-patterns description: >- Builds typed JavaScript and TypeScript backends and frontends: layered Express services over an explicit repository contract, validated DTOs, race-safe React data hooks and auth context, and unit plus integration tests with fresh fakes. Use when the user asks to "build a TypeScript API", "add an Express service layer", "write a React hook that fetches data", "set up Vitest or Jest tests", or "make this TS code type-safe". Not for installing unverified dependencies, migrating frameworks, or running unmeasured performance rewrites. ---
Read the project contract first
Before writing code, establish from the repository:
- Package scripts and lockfile — what actually runs and installs
- Runtime and compiler versions (Node, Deno, Bun; TypeScript major)
- Module format (CommonJS vs ESM/NodeNext) and build tool
- Framework (Express/Fastify/NestJS/Koa; React/Next/Vue/Svelte)
- Storage, authentication, and existing code conventions
The patterns below use ES6+, TypeScript 5+, Express, React 18 and Jest/Vitest as documented baselines — not claims about what is installed, and not an instruction to add anything. The owner supplies verified dependencies. Fresh confirmation is required for downloads, external requests, database mutations, credential or config changes, and deploys; an explicit edit request covers only its described local edits and tests.
Layout conventions
Backend layers: route → controller → service → repository, with models, middleware, config, utilities and types in their own modules and one entry point. Tests split into unit/, integration/, e2e/.
Frontend modules: feature and common components, hooks, contexts, services, state, types, utilities, styles, public assets — following the repository's existing shape, not an unsolicited directory migration.
TypeScript and module rules
- Strict types everywhere;
unknownplus runtime validation at external
boundaries. Property existence alone is not a type guard.
- Generics for reusable contracts; conditional/mapped types only when they
clarify a real relationship.
- Named exports for multiple contracts; a deliberate default export only
for a module's main object, matching existing consumers.
- Destructuring, spread, optional chaining, nullish coalescing and
const
improve clarity — but const does not deeply freeze objects.
- Parse numeric environment strings explicitly; do not juggle a
string | number port type silently.
Compiler settings
Backend (Node) preset: ES2022 target, matching module/resolution, outDir/rootDir, strict, esModuleInterop, resolveJsonModule, consistent casing, declarations and maps, plus the unused/implicit-return/ switch-fallthrough checks. A CommonJS project and a NodeNext ESM project need different coherent settings.
Frontend preset: DOM and DOM.Iterable libs, ESNext/bundler resolution, isolatedModules, noEmit, react-jsx, strict, current useDefineForClassFields. allowImportingTsExtensions requires a compatible emit setting. Exclude tests from the production build with a separate test config; never leave a dangling tsconfig reference.
Async and error boundaries
- Await promises; check HTTP status; then validate the parsed JSON body.
- Catch errors where you add recovery or context. An awaited caller may
handle the error, so not every function needs its own try/catch.
- Propagate failures without leaking secrets.
Promise.allfor independent all-or-fail work;allSettledwhen every
outcome must be inspected.
- Never parallelize ordered database mutations or authorization decisions.
- Immutable updates preserve unrelated objects and arrays.
export interface AccountView {id:string;email:string;name:string;role:'member'|'admin';active:boolean;createdAt:string;}
export function isAccountView(value:unknown):value is AccountView {
if(typeof value!=='object' || value===null)return false;
const row=value as Record<string,unknown>;
return typeof row.id==='string' && typeof row.email==='string' && typeof row.name==='string' &&
(row.role==='member' || row.role==='admin') && typeof row.active==='boolean' &&
typeof row.createdAt==='string' && Number.isFinite(Date.parse(row.createdAt));
}
export async function readAccount(url:string,signal:AbortSignal):Promise<AccountView> {
const response=await fetch(url,{signal});if(!response.ok)throw new Error('Account request failed');
const body:unknown=await response.json();
if(!isAccountView(body))throw new Error('Invalid account response');return body;
}Account service over a repository contract
Design rules this example follows:
passwordHashstays in the persisted row, out of DTOs and public views.- The repository enforces unique email atomically — a precheck alone races.
- List totals count the whole authorized scope, not the returned page length.
- A real adapter (for example Prisma against a verified schema) maps each
method to create/update timestamps, find-by-id/email, ordered findMany, count, update/delete, and unique-constraint error translation. Never invent the adapter's generated types.
export class ApiError extends Error {
constructor(public status:number,message:string){super(message);this.name='ApiError';}
}
export interface AccountRow {
id:string;email:string;name:string;passwordHash:string;role:'member'|'admin';active:boolean;
createdAt:Date;updatedAt:Date;
}
export interface CreateAccount {email:string;name:string;password:string;}
export interface UpdateAccount {name?:string;email?:string;active?:boolean;}
export interface AccountsRepository {
existsByEmail(email:string):Promise<boolean>;
findByEmail(email:string):Promise<AccountRow|null>;
findById(id:string):Promise<AccountRow|null>;
create(row:Omit<AccountRow,'id'>):Promise<AccountRow>;
update(id:string,patch:UpdateAccount & {updatedAt:Date}):Promise<AccountRow>;
delete(id:string):Promise<void>;
findAll(skip:number,take:number):Promise<AccountRow[]>;
count():Promise<number>;
}
export function createDto(value:unknown):CreateAccount {
if(typeof value!=='object' || value===null)throw new ApiError(400,'Object required');
const row=value as Record<string,unknown>;
if(Object.keys(row).some(k=>!['email','name','password'].includes(k)))throw new ApiError(400,'Unexpected field');
if(typeof row.email!=='string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(row.email))throw new ApiError(400,'Invalid email');
if(typeof row.name!=='string' || row.name.trim().length<2)throw new ApiError(400,'Invalid name');
if(typeof row.password!=='string' || row.password.length<8)throw new ApiError(400,'Invalid password');
return {email:row.email.trim().toLowerCase(),name:row.name.trim(),password:row.password};
}
export function updateDto(value:unknown):UpdateAccount {
if(typeof value!=='object' || value===null)throw new ApiError(400,'Object required');
const row=value as Record<string,unknown>;const patch:UpdateAccount={};
if(Object.keys(row).some(k=>!['email','name','active'].includes(k)))throw new ApiError(400,'Unexpected field');
if('email' in row){if(typeof row.email!=='string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(row.email))throw new ApiError(400,'Invalid email');patch.email=row.email.trim().toLowerCase();}
if('name' in row){if(typeof row.name!=='string' || row.name.trim().length<2)throw new ApiError(400,'Invalid name');patch.name=row.name.trim();}
if('active' in row){if(typeof row.active!=='boolean')throw new ApiError(400,'Invalid active flag');patch.active=row.active;}
return patch;
}
export class AccountsService {
constructor(private repository:AccountsRepository,private hash:(password:string)=>Promise<string>){}
view(row:AccountRow){const {id,email,name,role,active}=row;return {id,email,name,role,active,createdAt:row.createdAt.toISOString()};}
async create(value:unknown){
const data=createDto(value);
if(await this.repository.existsByEmail(data.email))throw new ApiError(409,'Account already exists');
const now=new Date(),passwordHash=await this.hash(data.password);
const row=await this.repository.create({email:data.email,name:data.name,passwordHash,role:'member',active:true,createdAt:now,updatedAt:now});
return this.view(row);
}
async get(id:string){const row=await this.repository.findById(id);if(!row)throw new ApiError(404,'Account not found');return this.view(row);}
async update(id:string,value:unknown){await this.get(id);return this.view(await this.repository.update(id,{...updateDto(value),updatedAt:new Date()}));}
async remove(id:string){await this.get(id);await this.repository.delete(id);}
async list(page=1,pageSize=20){
if(!Number.isInteger(page)||page<1||!Number.isInteger(pageSize)||pageSize<1||pageSize>100)throw new ApiError(400,'Invalid pagination');
const [rows,total]=await Promise.all([this.repository.findAll((page-1)*pageSize,pageSize),this.repository.count()]);
return {data:rows.map(row=>this.view(row)),pagination:{page,pageSize,total}};
}
}Name length ≥ 2, password ≥ 8, page size default 20 / cap 100 are example policies. Confirm the product's real rules and add maximum lengths and rate limits. Use an approved password-hashing implementation and never echo plaintext. Email normalization (here: trim and lowercase) must match the product's actual policy.
Express route adapter
- Authentication verifies signature, algorithm, issuer, audience and expiry
with the project's trusted JWT library and key policy, then validates the returned principal. A type cast does not validate a payload.
- Parse the
Bearerheader strictly; a decoded token is not a verified one. - Authorization independently checks ownership and role per operation —
never substitute authentication for it.
- Inject the verified middleware rather than inventing a JWT service.
import { Router } from 'express';
import type {Request,Response,NextFunction,RequestHandler,ErrorRequestHandler} from 'express';
import {AccountsService,ApiError} from './accounts-service';
export function accountRoutes(service:AccountsService,authenticate:RequestHandler,
authorize:(operation:'get'|'update'|'delete'|'list')=>RequestHandler,confirmMutation:RequestHandler){
const router=Router();
const wrap=(work:(request:Request,response:Response)=>Promise<void>):RequestHandler =>
(request,response,next:NextFunction)=>{void work(request,response).catch(next);};
router.post('/',confirmMutation,wrap(async(request,response)=>{response.status(201).json({success:true,data:await service.create(request.body)});}));
router.get('/',authenticate,authorize('list'),wrap(async(request,response)=>{
const text=(value:unknown,fallback:number)=>value===undefined?fallback:typeof value==='string'&&/^\d+$/.test(value)?Number(value):NaN;
const result=await service.list(text(request.query.page,1),text(request.query.pageSize,20));response.json({success:true,...result});
}));
router.get('/:id',authenticate,authorize('get'),wrap(async(request,response)=>{response.json({success:true,data:await service.get(String(request.params.id))});}));
router.put('/:id',authenticate,authorize('update'),confirmMutation,wrap(async(request,response)=>{response.json({success:true,data:await service.update(String(request.params.id),request.body)});}));
router.delete('/:id',authenticate,authorize('delete'),confirmMutation,wrap(async(request,response)=>{await service.remove(String(request.params.id));response.status(204).send();}));
return router;
}
export const errors:ErrorRequestHandler=(error,request,response,next)=>{
if(response.headersSent){next(error);return;}
const known=error instanceof ApiError,status=known?error.status:500;
// Attach a reviewed sanitized logger here; never log body/token/query secrets.
response.status(status).json({success:false,error:{statusCode:status,message:known?error.message:'Internal server error'}});
};Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 18.9 kB | fa3712c9e5d0 |
| examples.json | 2.1 kB | 5dd4b1f5face |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 2 Oct 2026 |
Locking a skill to one version needs Pro.