Claude
Skills
Sign in
Back

nodejs-backend-typescript

Included with Lifetime
$97 forever

Node.js backend development with TypeScript, Express/Fastify servers, routing, middleware, and database integration

Backend & APIs

What this skill does

# Node.js Backend Development with TypeScript

---
progressive_disclosure:
  entry_point:
    summary: "TypeScript backend patterns with Express/Fastify, routing, middleware, database integration"
    when_to_use:
      - "When building REST APIs with TypeScript"
      - "When creating Express/Fastify servers"
      - "When needing server-side TypeScript"
      - "When building microservices"
    quick_start:
      - "npm init -y && npm install -D typescript @types/node tsx"
      - "npm install express @types/express zod"
      - "Create tsconfig.json with strict mode"
      - "npm run dev"
  token_estimate:
    entry: 75
    full: 4700
---

## TypeScript Setup

### Essential Configuration

**tsconfig.json** (strict mode recommended):
```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "types": ["node"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}
```

**package.json scripts**:
```json
{
  "scripts": {
    "dev": "tsx watch src/server.ts",
    "build": "tsc",
    "start": "node dist/server.js",
    "test": "vitest"
  }
}
```

### Development Dependencies
```bash
npm install -D typescript @types/node tsx vitest
npm install -D @types/express  # or @types/node (Fastify has built-in types)
```

## Express Patterns

### Basic Express Server

**src/server.ts**:
```typescript
import express, { Request, Response, NextFunction } from 'express';
import { z } from 'zod';

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Type-safe request handlers
interface TypedRequest<T> extends Request {
  body: T;
}

// Routes
app.get('/health', (req: Request, res: Response) => {
  res.json({ status: 'ok', timestamp: new Date().toISOString() });
});

// Start server
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});
```

### Router Pattern

**src/routes/users.ts**:
```typescript
import { Router } from 'express';
import { z } from 'zod';
import { validateRequest } from '../middleware/validation';

const router = Router();

const createUserSchema = z.object({
  email: z.string().email(),
  name: z.string().min(2),
  age: z.number().int().positive().optional(),
});

router.post(
  '/users',
  validateRequest(createUserSchema),
  async (req, res, next) => {
    try {
      const userData = req.body; // Type-safe after validation
      // Database insert logic
      res.status(201).json({ id: 1, ...userData });
    } catch (error) {
      next(error);
    }
  }
);

export default router;
```

### Middleware Patterns

**src/middleware/validation.ts**:
```typescript
import { Request, Response, NextFunction } from 'express';
import { z, ZodSchema } from 'zod';

export const validateRequest = (schema: ZodSchema) => {
  return (req: Request, res: Response, next: NextFunction) => {
    try {
      req.body = schema.parse(req.body);
      next();
    } catch (error) {
      if (error instanceof z.ZodError) {
        res.status(400).json({
          error: 'Validation failed',
          details: error.errors,
        });
      } else {
        next(error);
      }
    }
  };
};
```

**src/middleware/auth.ts**:
```typescript
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';

interface JwtPayload {
  userId: string;
  email: string;
}

declare global {
  namespace Express {
    interface Request {
      user?: JwtPayload;
    }
  }
}

export const authenticate = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  const token = req.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    return res.status(401).json({ error: 'No token provided' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as JwtPayload;
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
};
```

### Error Handling

**src/middleware/errorHandler.ts**:
```typescript
import { Request, Response, NextFunction } from 'express';

export class AppError extends Error {
  constructor(
    public statusCode: number,
    message: string,
    public isOperational = true
  ) {
    super(message);
    Object.setPrototypeOf(this, AppError.prototype);
  }
}

export const errorHandler = (
  err: Error,
  req: Request,
  res: Response,
  next: NextFunction
) => {
  if (err instanceof AppError) {
    return res.status(err.statusCode).json({
      error: err.message,
      ...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
    });
  }

  console.error('Unexpected error:', err);
  res.status(500).json({
    error: 'Internal server error',
    ...(process.env.NODE_ENV === 'development' && {
      message: err.message,
      stack: err.stack,
    }),
  });
};
```

## Fastify Patterns

### Basic Fastify Server

**src/server.ts**:
```typescript
import Fastify from 'fastify';
import { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
import { Type } from '@sinclair/typebox';

const fastify = Fastify({
  logger: {
    level: process.env.LOG_LEVEL || 'info',
  },
}).withTypeProvider<TypeBoxTypeProvider>();

// Type-safe route with schema validation
fastify.route({
  method: 'POST',
  url: '/users',
  schema: {
    body: Type.Object({
      email: Type.String({ format: 'email' }),
      name: Type.String({ minLength: 2 }),
      age: Type.Optional(Type.Integer({ minimum: 0 })),
    }),
    response: {
      201: Type.Object({
        id: Type.Number(),
        email: Type.String(),
        name: Type.String(),
      }),
    },
  },
  handler: async (request, reply) => {
    const { email, name, age } = request.body;
    // Auto-typed and validated
    return reply.status(201).send({ id: 1, email, name });
  },
});

const start = async () => {
  try {
    await fastify.listen({ port: 3000, host: '0.0.0.0' });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();
```

### Plugin Pattern

**src/plugins/database.ts**:
```typescript
import { FastifyPluginAsync } from 'fastify';
import fp from 'fastify-plugin';
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';

declare module 'fastify' {
  interface FastifyInstance {
    db: ReturnType<typeof drizzle>;
  }
}

const databasePlugin: FastifyPluginAsync = async (fastify) => {
  const pool = new Pool({
    connectionString: process.env.DATABASE_URL,
  });

  const db = drizzle(pool);
  fastify.decorate('db', db);

  fastify.addHook('onClose', async () => {
    await pool.end();
  });
};

export default fp(databasePlugin);
```

### Hooks Pattern

**src/hooks/auth.ts**:
```typescript
import { FastifyRequest, FastifyReply } from 'fastify';
import jwt from 'jsonwebtoken';

declare module 'fastify' {
  interface FastifyRequest {
    user?: {
      userId: string;
      email: string;
    };
  }
}

export const authHook = async (
  request: FastifyRequest,
  reply: FastifyReply
) => {
  const token = request.headers.authorization?.replace('Bearer ', '');

  if (!token) {
    return reply.status(401).send({ error: 'No token provided' });
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as {
      userId: string;
      email: string;
    };
    request.user = decoded;
  } catch (error) {
    return reply.status(401).send({ error: 'Invalid token' });
  }
};
```

## Request Validation

### Zod with Express

```typescript
import { z } from 'zod';

const userSchema = z.object({
  email: z.string().email(),
  password: z.string().min(8),
  profile: z.object({
    firstName: z.string(),
    lastName: z.string(),
    age: z.number().int().positive(),
  }),
  tags: z.array(z.string()).optional(),
});

type CreateUserInput = z.infer<

Related in Backend & APIs