# Express + TypeScript Setup Guide
## 1. Initialize Project
```bash
mkdir my-express-app
cd my-express-app
npm init -y
```
## 2. Install Dependencies
```bash
# Production dependencies
npm install express dotenv helmet cors compression morgan winston winston-daily-rotate-file
# Development dependencies
npm install -D typescript @types/node @types/express @types/cors @types/compression @types/morgan ts-node nodemon eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin prettier eslint-config-prettier eslint-plugin-prettier
```
## 3. Initialize TypeScript
```bash
npx tsc --init
```
## 4. Project Structure
```
my-express-app/
├── src/
│ ├── config/
│ │ └── logger.ts
│ ├── middleware/
│ │ ├── errorHandler.ts
│ │ └── requestLogger.ts
│ ├── routes/
│ │ └── index.ts
│ ├── types/
│ │ └── express.d.ts
│ ├── utils/
│ │ └── asyncHandler.ts
│ ├── app.ts
│ └── server.ts
├── logs/
├── .env
├── .env.example
├── .eslintrc.json
├── .prettierrc
├── .gitignore
├── nodemon.json
├── tsconfig.json
└── package.json
```
## 5. Configuration Files
### tsconfig.json
```json
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"moduleResolution": "node",
"sourceMap": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
```
### .eslintrc.json
```json
{
"parser": "@typescript-eslint/parser",
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaVersion": 2020,
"sourceType": "module"
},
"rules": {
"@typescript-eslint/no-explicit-any": "warn",
"@typescript-eslint/explicit-function-return-type": "off",
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }]
}
}
```
### .prettierrc
```json
{
"semi": true,
"trailingComma": "es5",
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2,
"arrowParens": "always"
}
```
### nodemon.json
```json
{
"watch": ["src"],
"ext": "ts,json",
"ignore": ["src/**/*.spec.ts"],
"exec": "ts-node ./src/server.ts",
"env": {
"NODE_ENV": "development"
}
}
```
### .env.example
```
NODE_ENV=development
PORT=3000
LOG_LEVEL=debug
```
### .gitignore
```
node_modules/
dist/
logs/
.env
*.log
.DS_Store
```
## 6. Update package.json scripts
```json
{
"scripts": {
"dev": "nodemon",
"build": "tsc",
"start": "node dist/server.js",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix",
"format": "prettier --write \"src/**/*.ts\"",
"type-check": "tsc --noEmit"
}
}
```
## 7. Source Code Files
### src/config/logger.ts
```typescript
import winston from 'winston';
import DailyRotateFile from 'winston-daily-rotate-file';
import path from 'path';
const logDir = 'logs';
const logFormat = winston.format.combine(
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.errors({ stack: true }),
winston.format.splat(),
winston.format.json()
);
const consoleFormat = winston.format.combine(
winston.format.colorize(),
winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
winston.format.printf(({ timestamp, level, message, ...meta }) => {
let metaStr = '';
if (Object.keys(meta).length > 0) {
metaStr = '\n' + JSON.stringify(meta, null, 2);
}
return `${timestamp} [${level}]: ${message}${metaStr}`;
})
);
const logger = winston.createLogger({
level: process.env.LOG_LEVEL || 'info',
format: logFormat,
transports: [
new DailyRotateFile({
filename: path.join(logDir, 'error-%DATE%.log'),
datePattern: 'YYYY-MM-DD',
level: 'error',
maxFiles: '14d',
maxSize: '20m',
}),
new DailyRotateFile({
filename: path.join(logDir, 'combined-%DATE%.log'),
datePattern: 'YYYY-MM-DD',
maxFiles: '14d',
maxSize: '20m',
}),
],
});
if (process.env.NODE_ENV !== 'production') {
logger.add(
new winston.transports.Console({
format: consoleFormat,
})
);
}
export default logger;
```
### src/middleware/requestLogger.ts
```typescript
import morgan from 'morgan';
import logger from '../config/logger';
const stream = {
write: (message: string) => {
logger.http(message.trim());
},
};
const skip = () => {
const env = process.env.NODE_ENV || 'development';
return env === 'production';
};
export const requestLogger = morgan(
':method :url :status :res[content-length] - :response-time ms',
{ stream, skip }
);
```
### src/middleware/errorHandler.ts
```typescript
import { Request, Response, NextFunction } from 'express';
import logger from '../config/logger';
export class AppError extends Error {
statusCode: number;
isOperational: boolean;
constructor(message: string, statusCode: number) {
super(message);
this.statusCode = statusCode;
this.isOperational = true;
Error.captureStackTrace(this, this.constructor);
}
}
export const errorHandler = (
err: Error | AppError,
req: Request,
res: Response,
_next: NextFunction
) => {
if (err instanceof AppError) {
logger.error(`${err.statusCode} - ${err.message} - ${req.originalUrl} - ${req.method}`);
return res.status(err.statusCode).json({
status: 'error',
message: err.message,
});
}
logger.error(`500 - ${err.message} - ${req.originalUrl} - ${req.method}`, {
stack: err.stack,
});
return res.status(500).json({
status: 'error',
message: process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message,
});
};
export const notFoundHandler = (req: Request, res: Response) => {
res.status(404).json({
status: 'error',
message: `Route ${req.originalUrl} not found`,
});
};
```
### src/utils/asyncHandler.ts
```typescript
import { Request, Response, NextFunction } from 'express';
export const asyncHandler = (
fn: (req: Request, res: Response, next: NextFunction) => Promise<any>
) => {
return (req: Request, res: Response, next: NextFunction) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
};
```
### src/routes/index.ts
```typescript
import { Router, Request, Response } from 'express';
import { asyncHandler } from '../utils/asyncHandler';
import { AppError } from '../middleware/errorHandler';
import logger from '../config/logger';
const router = Router();
router.get('/', asyncHandler(async (_req: Request, res: Response) => {
logger.info('Health check endpoint accessed');
res.json({
status: 'success',
message: 'API is running',
timestamp: new Date().toISOString(),
});
}));
router.get('/test-error', asyncHandler(async (_req: Request, _res: Response) => {
throw new AppError('This is a test error', 400);
}));
export default router;
```
### src/app.ts
```typescript
import express, { Application } from 'express';
import helmet from 'helmet';
import cors from 'cors';
import compression from 'compression';
import { requestLogger } from './middleware/requestLogger';
import { errorHandler, notFoundHandler } from './middleware/errorHandler';
import routes from './routes';
import logger from './config/logger';
const app: Application = express();
// Security middleware
app.use(helmet());
// CORS
app.use(cors({
origin: process.env.CORS_ORIGIN || '*',
credentials: true,
}));
// Compression
app.use(compression());
// Body parsing
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
// Request logging
app.use(requestLogger);
// Routes
app.use('/api', routes);
// 404 handler
app.use(notFoundHandler);
// Error handler (must be last)
app.use(errorHandler);
// Graceful shutdown
process.on('SIGTERM', () => {
logger.info('SIGTERM signal received: closing HTTP server');
process.exit(0);
});
process.on('SIGINT', () => {
logger.info('SIGINT signal received: closing HTTP server');
process.exit(0);
});
export default app;
```
### src/server.ts
```typescript
import dotenv from 'dotenv';
import app from './app';
import logger from './config/logger';
dotenv.config();
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
logger.info(`Server is running on port ${PORT}`);
logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (err: Error) => {
logger.error('UNHANDLED REJECTION! 💥 Shutting down...', err);
server.close(() => {
process.exit(1);
});
});
```
## 8. VS Code Settings (Optional)
Create `.vscode/settings.json`:
```json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"typescript.preferences.importModuleSpecifier": "relative",
"files.exclude": {
"node_modules": true,
"dist": true
}
}
```
Create `.vscode/extensions.json`:
```json
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"ms-vscode.vscode-typescript-next"
]
}
```
## 9. Run the Project
```bash
# Copy environment file
cp .env.example .env
# Install dependencies (if not done)
npm install
# Run in development mode
npm run dev
# Build for production
npm run build
# Run production build
npm start
```
## 10. Test the API
```bash
# Health check
curl http://localhost:3000/api
# Test error handling
curl http://localhost:3000/api/test-error
```
Your Express + TypeScript server is now ready with:
- ✅ TypeScript with strict type checking
- ✅ Winston logger with daily rotation
- ✅ ESLint + Prettier for code quality
- ✅ Security best practices (Helmet)
- ✅ Error handling middleware
- ✅ Request logging
- ✅ Hot reload with nodemon
- ✅ VS Code integration
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )