mcpField
N
nodejs-express-mongodb-backend-pattern

nodejs-express-mongodb-backend-pattern

github.com/laskar-ksatria開発035 回インストール35 週間前に更新
リポジトリ

nodejs-express-mongodb-backend-pattern について

Express 5、TypeScript、MongoDB を使う Node.js REST API テンプレートの構築、解説、拡張を支援するスキルです。プロジェクト規約に加え、セキュリティ、認証、可観測性、耐障害性のパターンを扱います。

主な機能

  1. 01Express 5 と TypeScript の API 構成
  2. 02MongoDB、Mongoose、任意の Redis キャッシュ
  3. 03JWT 認証と bcrypt によるパスワードハッシュ化
  4. 04入力サニタイズとルート単位のレート制限
  5. 05Sentry によるエラー報告と過負荷検知

活用シーン

  1. 01Node.js と Express の REST API の開始
  2. 02規約に沿ったリソース、モデル、コントローラー、ルートの追加
  3. 03環境変数の設定とアプリの実行

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/laskar-ksatria/building-observable-nodejs-api --skill nodejs-express-mongodb-backend-pattern

インストール後、Claude Code で/nodejs-express-mongodb-backend-patternを入力して読み込まれたか確認します。

詳細

Node.js Express MongoDB バックエンドパターン

目的

このスキルは、エージェントが nodejs-express-mongodb-backend-pattern テンプレート(オブザーバビリティ、セキュリティ、レジリエンスを組み込んだ Node.js REST API のボイラープレート)のスキャフォールディング、説明、または適応を行う際に役立ちます。ユーザーが Express、MongoDB、Redis、Sentry、JWT 認証、本番環境を想定したミドルウェアを備えたバックエンドを求めている場合に使用します。

このスキルを使用する場合

  • ユーザーが Node.js と Express を使って新しい REST API バックエンドを作成したい場合。
  • ユーザーが本番環境ですぐに使える、または「オブザーバブルな」Node.js API テンプレートを求めている場合。
  • ユーザーが MongoDB/Mongoose、Redis、Sentry、レート制限、JWT 認証に言及し、スターターを求めている場合。
  • ユーザーがこのリポジトリ(nodejs-express-mongodb-backend-pattern)のクローン、フォーク、または構成の把握を希望している場合。
  • ユーザーが環境変数の設定、アプリの実行、またはこのテンプレートの規約に沿ったルート/コントローラーの追加手順を必要としている場合。

このスキルを使用しない場合

  • ユーザーがフロントエンドまたはフルスタックのフレームワーク(Next.js、Nuxt など)を求めている場合。
  • ユーザーが Mongoose を使わず、別のデータベース(PostgreSQL、MySQL)を明示的に希望している場合。
  • ユーザーが長時間稼働する Express サーバーではなく、サーバーレス/Lambda アーキテクチャを希望している場合。

このテンプレートの使い方

1. クローンとインストール
git clone https://github.com/laskar-ksatria/building-observable-nodejs-api.git
cd building-observable-nodejs-api
npm install
2. 環境設定
  • プロジェクトのルートに .env ファイルを作成します。
  • 必須変数:PORT、MONGODB_URI、PRIVATE_KEY、TOKEN_EXPIRED。任意の変数:SENTRY_DSN、REDIS_HOST、REDIS_PORT、REDIS_PASSWORD。必須変数が不足している場合、アプリは起動時に終了します。Redis は任意のキャッシュ(例:GET /api/user のレスポンスを 60 秒間キャッシュ)に使用されます。Redis が設定されていない場合、アプリはキャッシュなしで動作します。
  • PRIVATE_KEY 用の JWT シークレットを生成します。
    • Node:node -e "console.log(require('crypto').randomBytes(64).toString('base64'))"
    • OpenSSL:openssl rand -hex 64
3. アプリの実行
  • 開発:npm run dev
  • ビルド:npm run build の後に npm start
4. API の構成
  • ベースパス:/api
  • POST /api/user/register — ユーザー登録(email、full_name、password)
  • POST /api/user/login — ログインし、JWT を返します
  • GET /api/user — 現在のユーザー(ヘッダー:Authorization: Bearer <token>)
  • GET / — ヘルスチェック

主な機能

  • スタック: Express 5、TypeScript、Mongoose、Redis(ioredis)、Sentry、Helmet、CORS。
  • セキュリティ: NoSQL インジェクション対策、入力内の HTML の拒否、Helmet、CORS。
  • 認証: JWT + bcrypt。パスワードは保存時にハッシュ化され、JSON で返されることはありません。
  • レジリエンス: ルートごとのレート制限、過負荷の検出(toobusy)、構造化された HttpError、および予期しないエラーが発生した場合の Sentry へのフォールバック。
  • 構成: src/ に config、controllers、errors、lib、middlewares、models、routes、services、types を配置し、エントリーポイントは Sentry の初期化を行う server.ts です。

規約(重要 — コード生成時は必ず従ってください)

ファイル名
  • モデル:src/models/<entity>.model.ts
  • コントローラー:src/controllers/<entity>.controller.ts
  • ルート:src/routes/<entity>.route.ts
  • ミドルウェア:src/middlewares/<name>.ts
  • サービス:src/services/<name>.ts
  • すべてのファイル名には kebab-case を使用します。
レスポンス形式

すべての API レスポンスは次の形式に従います。

成功:

{ "success": true, "data": { ... } }

エラー:

{ "success": false, "error": { "error_id": 0, "message": "...", "errors": [] } }
app.ts のミドルウェア順序

順序が重要です。必ず次の順序に従ってください。

  1. helmet() — セキュリティヘッダー
  2. cors() — クロスオリジン設定
  3. express.json() — JSON ボディを解析(サイズ制限あり)
  4. express.urlencoded() — URL エンコードされたボディを解析
  5. securityMiddleware — NoSQL インジェクション対策 + HTML サニタイズ
  6. toobusy チェック — 過負荷の検出(HTTP 529)
  7. Cache-Control ヘッダー — no-store
  8. ルート — app.use("/api", indexRoute)
  9. ヘルスチェック — app.get("/")
  10. ErrorHandling — 最後に配置すること(グローバルエラーハンドラー)
エラー処理の規約
  • 既知/想定されるエラー:new HttpError(errorStates.someError) をスローします。設定された HTTP コードとメッセージがクライアントに返されます。
  • 新しいエラー状態の追加:src/errors/index.ts の errorStates に、一意の error_id、message、http_code を含むエントリを追加します。
  • Sentry への報告:予期しないエラー(HttpError ではないもの)は自動的に Sentry に送信されます。既知のエラーも報告する場合は、エラー状態に sentry: true を設定します。
  • Mongoose の検証エラー:自動的に収集され、errors 配列で返されます。
新しい環境変数の追加
  1. .env にキーを追加します
  2. src/env.ts の env オブジェクトに追加します
  3. import env from "../env" を使用してインポートし、env.YOUR_VAR で使用します
依存関係
{
  "dependencies": {
    "@sentry/node": "^8.x",
    "bcrypt": "^5.x",
    "cors": "^2.x",
    "dotenv": "^17.x",
    "express": "^5.x",
    "express-rate-limit": "^8.x",
    "helmet": "^8.x",
    "ioredis": "^5.x",
    "jsonwebtoken": "^9.x",
    "mongoose": "^9.x",
    "toobusy-js": "^0.5.x"
  },
  "devDependencies": {
    "@types/bcrypt": "^5.x",
    "@types/cors": "^2.x",
    "@types/express": "^4.x",
    "@types/ioredis": "^4.x",
    "@types/jsonwebtoken": "^9.x",
    "@types/toobusy-js": "^0.5.x",
    "nodemon": "^3.x",
    "ts-node": "^10.x",
    "tsx": "^4.x",
    "typescript": "^5.x"
  }
}

新しいリソースを追加する方法(手順)

ユーザーから新しいエンティティ(例:「Product」)の追加を依頼された場合は、次の手順を順番に実行します。

ステップ 1 — src/types/index.ts で型を定義する
// Product
export interface IProduct {
  name: string;
  price: number;
  description: string;
}

export interface IProductDocument extends IProduct, Document {}
ステップ 2 — モデル src/models/product.model.ts を作成する
import { Schema, model } from "mongoose";
import { IProductDocument } from "../types";

const productSchema = new Schema<IProductDocument>(
  {
    name: { type: String, required: true },
    price: { type: Number, required: true },
    description: { type: String, required: true },
  },
  { versionKey: false, timestamps: true },
);

export const ProductModel = model<IProductDocument>("Product", productSchema);
ステップ 3 — コントローラー src/controllers/product.controller.ts を作成する
import { Request, Response, NextFunction } from "express";
import { ProductModel } from "../models/product.model";
import HttpError, { errorStates } from "../errors";

class ProductController {
  static async create(req: Request, res: Response, next: NextFunction) {
    try {
      const product = await ProductModel.create(req.body);
      return res.status(201).json({ success: true, data: { product } });
    } catch (error) {
      next(error);
    }
  }

  static async getAll(req: Request, res: Response, next: NextFunction) {
    try {
      const products = await ProductModel.find();
      return res.status(200).json({ success: true, data: { products } });
    } catch (error) {
      next(error);
    }
  }
}

export default ProductController;
ステップ 4 — ルート src/routes/product.route.ts を作成する
import ProductController from "../controllers/product.controller";
import { Router } from "express";
import { RateLimit } from "../services/rate-limit";
import Authentication from "../middlewares/auth";

const router = Router();

router.post("/", RateLimit({ max: 10, ms: 60000 }), Authentication, ProductController.create);
router.get("/", RateLimit({ max: 20, ms: 60000 }), ProductController.getAll);

export default router;
ステップ 5 — src/routes/index.ts にマウントする
import { Router } from "express";
import userRoute from "./user.route";
import productRoute from "./product.route";

const router = Router();
router.use("/user", userRoute);
router.use("/product", productRoute);
export default router;

コード例

以下のスニペットは、このテンプレートで実際に使用しているコードです。新しいプロジェクトを構築する際の参考パターンとして使用してください。

プロジェクト構成
src/
├── config/
│   └── mongodb.ts          # MongoDB connection
├── controllers/
│   └── user.controller.ts  # Request handlers
├── errors/
│   └── index.ts            # HttpError, errorStates
├── lib/
│   └── utils.ts            # bcrypt, emailRegex
├── middlewares/
│   ├── auth.ts             # JWT verification
│   ├── error-handling.ts   # Global error + Sentry
│   └── security.ts         # NoSQL/HTML sanitization
├── models/
│   └── user.model.ts       # Mongoose schema
├── routes/
│   ├── index.ts            # Mounts sub-routes
│   └── user.route.ts       # /api/user routes
├── services/
│   ├── jwt.ts              # GenerateToken, VerifyToken
│   ├── rate-limit.ts       # Per-route rate limiter
│   └── redis.ts            # Optional cache (getCache, setCache, deleteCache)
├── types/
│   └── index.ts            # Shared interfaces
├── app.ts                  # Express app + middleware
├── env.ts                  # Load and export env
└── server.ts               # Entry, Sentry.init, listen
環境変数の設定(src/env.ts)
import { config } from "dotenv";
config();

const env = {
  PORT: `${process.env.PORT}`,
  REDIS_HOST: `${process.env.REDIS_HOST}`,
  REDIS_PORT: `${process.env.REDIS_PORT}`,
  SENTRY_DSN: `${process.env.SENTRY_DSN}`,
  TOKEN_EXPIRED: `${process.env.TOKEN_EXPIRED}`,
  PRIVATE_KEY: `${process.env.PRIVATE_KEY}`,
  MONGODB_URI: process.env.MONGODB_URI!,
  REDIS_PASSWORD: `${process.env.REDIS_PASSWORD}`,
};

export default env;
サーバーエントリーポイント(src/server.ts)
import * as Sentry from "@sentry/node";
import { server } from "./app";
import toobusy from "toobusy-js";
import env from "./env";
import dbConnect from "./config/mongodb";

if (env.SENTRY_DSN) {
  Sentry.init({ dsn: env.SENTRY_DSN, environment: process.env.NODE_ENV ?? "development" });
}

async function main() {
  await dbConnect();
  server.listen(env.PORT, () => {
    console.log(`Server running on http://localhost:${env.PORT}`);
  });
  process.on("SIGINT", () => { toobusy.shutdown(); process.exit(); });
  process.on("exit", () => toobusy.shutdown());
}

main().catch((err) => { console.error(err); process.exit(1); });
データベース設定(src/config/mongodb.ts)
import mongoose from "mongoose";
import env from "../env";
import * as Sentry from "@sentry/node";

export default async function dbConnect(): Promise<void> {
  try {
    await mongoose.connect(env.MONGODB_URI);
    mongoose.connection.on("error", (err) => {
      Sentry.captureException(err);
      console.error("MongoDB connection error:", err);
    });
    console.log("Connected to MongoDB");
  } catch (error) {
    console.error("Failed to connect to MongoDB:", error);
    Sentry.captureException(error);
    process.exit(1);
  }
}
型(src/types/index.ts)
import { Document, Types } from "mongoose";
import { Request } from "express";

export type TGenerateToken = { id: Types.ObjectId };

export interface IAuthRequest extends Request {
  decoded?: TGenerateToken;
}

export interface IErrorMessage {
  message: string;
  error_id: number;
  http_code: number;
  sentry?: boolean;
}

export type CreateLimitType = { max: number; ms: number };

export interface IUser {
  email: string;
  full_name: string;
  password: string;
}

export interface IUserModel extends IUser {
  _id: Types.ObjectId;
}

export interface IUserDocument extends IUser, Document {}
モデル(src/models/user.model.ts)
import { emailRegex, hashPassword } from "../lib/utils";
import { Schema, model } from "mongoose";
import { IUserDocument } from "../types";

const userSchema = new Schema<IUserDocument>(
  {
    email: {
      type: String,
      required: true,
      unique: true,
      index: true,
      validate: {
        validator: (value: string) => emailRegex.test(value),
        message: "Invalid email address",
      },
    },
    full_name: { type: String, required: true },
    password: { type: String, required: true },
  },
  { versionKey: false, timestamps: true },
);

userSchema.pre("save", async function () {
  if (!this.isModified("password")) return;
  this.password = await hashPassword(this.password);
});

export const UserModel = model<IUserDocument>("User", userSchema);
コントローラー(src/controllers/user.controller.ts)
import { Request, Response, NextFunction } from "express";
import { UserModel } from "../models/user.model";
import { comparePassword } from "../lib/utils";
import { IAuthRequest, IUserDocument } from "../types";
import HttpError, { errorStates } from "../errors";
import { GenerateToken } from "../services/jwt";
import { getCache, setCache, CACHE_USER } from "../services/redis";

class UserController {
  static async createUser(req: Request, res: Response, next: NextFunction) {
    try {
      const { email, full_name, password } = req.body;
      const user = (await UserModel.create({ email, full_name, password })) as IUserDocument;
      const access_token = GenerateToken({ id: user._id });
      return res.status(201).json({
        success: true,
        data: {
          access_token,
          user: { _id: user._id, full_name: user.full_name, email: user.email },
        },
      });
    } catch (error) {
      next(error);
    }
  }

  static async loginUser(req: Request, res: Response, next: NextFunction) {
    try {
      const { email, password } = req.body;
      const user = (await UserModel.findOne({ email })) as IUserDocument;
      if (!user) throw new HttpError(errorStates.invalidEmailOrPassword);
      const valid = await comparePassword(password, user.password);
      if (!valid) throw new HttpError(errorStates.invalidEmailOrPassword);
      const access_token = GenerateToken({ id: user._id });
      const { password: _p, ...safeUser } = user.toObject();
      return res.status(200).json({ success: true, data: { user: safeUser, access_token } });
    } catch (error) {
      next(error);
    }
  }

  static async getUser(req: IAuthRequest, res: Response, next: NextFunction) {
    try {
      const userId = req?.decoded?.id;
      if (!userId) throw new HttpError(errorStates.failedAuthentication);

      const idStr = String(userId);
      const cacheKey = CACHE_USER(idStr);
      const cached = await getCache(cacheKey);
      if (cached) {
        const user = JSON.parse(cached);
        return res.status(200).json({ success: true, data: { user } });
      }

      const user = await UserModel.findById(userId);
      if (!user) throw new HttpError(errorStates.failedAuthentication);
      const { password: _p, ...safeUser } = user.toObject();
      await setCache(cacheKey, JSON.stringify(safeUser));

      return res.status(200).json({ success: true, data: { user: safeUser } });
    } catch (error) {
      next(error);
    }
  }
}

export default UserController;
ルート

マウント(src/routes/index.ts):

import { Router } from "express";
import userRoute from "./user.route";

const router = Router();
router.use("/user", userRoute);
export default router;

ユーザーのルート(src/routes/user.route.ts):

import UserController from "../controllers/user.controller";
import { Router } from "express";
import { RateLimit } from "../services/rate-limit";
import Authentication from "../middlewares/auth";

const router = Router();

router.post("/register", RateLimit({ max: 10, ms: 60000 }), UserController.createUser);
router.post("/login", RateLimit({ max: 10, ms: 60000 }), UserController.loginUser);
router.get("/", RateLimit({ max: 3, ms: 1000 }), Authentication, UserController.getUser);

export default router;
エラー(src/errors/index.ts)
import { IErrorMessage } from "../types";

export const errorStates = {
  internalservererror: { message: "Oops! Something's off-track.", error_id: 0, http_code: 500 },
  highTraffic: { message: "Too many steps at once! Try again soon.", error_id: 1, http_code: 503 },
  rateLimit: { message: "Whoa, slow down! Try again later.", error_id: 2, http_code: 429 },
  failedAuthentication: { message: "Not Authenticated", error_id: 3, http_code: 401 },
  invalidEmailOrPassword: { message: "Invalid email or password", error_id: 4, http_code: 401 },
  tokenExpired: { message: "Session expired—log in again!", error_id: 5, http_code: 401 },
} as const;

class HttpError extends Error {
  statusCode: number;
  error_id: number;
  constructor(args: IErrorMessage) {
    super(args.message);
    this.statusCode = args.http_code;
    this.error_id = args.error_id;
    Object.setPrototypeOf(this, HttpError.prototype);
  }
}

export default HttpError;
ミドルウェア – セキュリティ(src/middlewares/security.ts)
import { NextFunction, Request, Response } from "express";

const dangerousKeyPattern = /^\$|\.|\$/;
const htmlTagPattern = /<[^>]*>/;

const sanitizeObject = <T>(value: T): T => {
  const inner = (val: unknown): unknown => {
    if (Array.isArray(val)) return val.map(inner);
    if (val && typeof val === "object") {
      const obj = val as Record<string, unknown>;
      const sanitized: Record<string, unknown> = {};
      Object.keys(obj).forEach((key) => {
        if (dangerousKeyPattern.test(key)) return;
        sanitized[key] = inner(obj[key]);
      });
      return sanitized;
    }
    if (typeof val === "string") {
      if (htmlTagPattern.test(val)) throw new Error("HTML content is not allowed in input.");
      return val;
    }
    return val;
  };
  return inner(value) as T;
};

export const securityMiddleware = (req: Request, res: Response, next: NextFunction): void => {
  try {
    req.body = sanitizeObject(req.body);

    const sanitizedQuery = sanitizeObject(req.query);
    const sanitizedParams = sanitizeObject(req.params);

    Object.keys(req.query).forEach((key) => delete (req.query as any)[key]);
    Object.assign(req.query as any, sanitizedQuery as any);

    Object.keys(req.params).forEach((key) => delete (req.params as any)[key]);
    Object.assign(req.params as any, sanitizedParams as any);

    next();
  } catch (err) {
    res.status(400).json({ message: (err as Error).message || "Invalid input." });
  }
};
ミドルウェア – エラー処理(src/middlewares/error-handling.ts)
import { Request, Response, NextFunction } from "express";
import * as Sentry from "@sentry/node";
import HttpError, { errorStates } from "../errors";

export const ErrorHandling = (error: unknown, req: Request, res: Response, next: NextFunction): void => {
  if (error instanceof HttpError) {
    const statusCode = error.statusCode ?? errorStates.internalservererror.http_code;
    if ((error as any).sentry) Sentry.captureException(error);
    res.status(statusCode).json({
      success: false,
      error: { error_id: error.error_id, message: error.message, errors: [] },
    });
    return;
  }

  const validationErrors: Array<Record<string, string>> = [];
  if ((error as any)?.errors) {
    Object.entries((error as any).errors).forEach(([key, value]: [string, any]) => {
      validationErrors.push({ [key]: value.message });
    });
  }

  Sentry.captureException(error);

  const fallback = errorStates.internalservererror;
  res.status(fallback.http_code).json({
    success: false,
    error: { error_id: fallback.error_id, message: fallback.message, errors: validationErrors },
  });
};
ミドルウェア – 認証(src/middlewares/auth.ts)
import HttpError, { errorStates } from "../errors";
import { VerifyToken } from "../services/jwt";
import { Response, NextFunction } from "express";
import { IAuthRequest } from "../types";

export default function Authentication(req: IAuthRequest, res: Response, next: NextFunction) {
  try {
    const token = req?.headers?.authorization;
    if (!token) throw new HttpError(errorStates.failedAuthentication);
    const decoded = VerifyToken(token.split("Bearer ")[1]);
    req.decoded = decoded;
    next();
  } catch (error: unknown) {
    if ((error as { name?: string })?.name === "TokenExpiredError") {
      return next(new HttpError(errorStates.tokenExpired));
    }
    next(error);
  }
}
サービス

レート制限(src/services/rate-limit.ts):

import rateLimit from "express-rate-limit";
import { errorStates } from "../errors";
import { CreateLimitType } from "../types";

export const RateLimit = ({ max, ms }: CreateLimitType) =>
  rateLimit({
    windowMs: ms,
    max,
    message: { error_id: errorStates.rateLimit.error_id, message: errorStates.rateLimit.message },
  });

JWT(src/services/jwt.ts):

import jwt from "jsonwebtoken";
import env from "../env";
import { TGenerateToken } from "../types";

export const GenerateToken = (payload: TGenerateToken): string =>
  jwt.sign(payload, env.PRIVATE_KEY, { expiresIn: env.TOKEN_EXPIRED });

export const VerifyToken = (token: string): TGenerateToken =>
  jwt.verify(token, env.PRIVATE_KEY) as TGenerateToken;

Redis(src/services/redis.ts)— 任意:

Redis はキャッシュレイヤーとして使用されます。REDIS_HOST が設定されていない場合、キャッシュはスキップされ、アプリは Redis なしで動作します。

import Redis from "ioredis";
import env from "../env";

export const CACHE_USER = (id: string) => `user:${id}`;
const USER_CACHE_TTL_SEC = 60;

class RedisClient {
  private static instance: Redis | null = null;

  public static getInstance(): Redis | null {
    if (this.instance !== null) return this.instance;
    if (!env.REDIS_HOST || env.REDIS_HOST === "") return null;
    try {
      this.instance = new Redis({
        host: env.REDIS_HOST,
        port: Number(env.REDIS_PORT) || 6379,
        password: env.REDIS_PASSWORD || undefined,
      });
      this.instance.on("error", (err) => console.error("Redis error:", err));
      return this.instance;
    } catch {
      return null;
    }
  }
}

export const setCache = async (key: string, value: string, expirySeconds = 60): Promise<void> => {
  const redis = RedisClient.getInstance();
  if (!redis) return;
  try {
    await redis.set(key, value, "EX", expirySeconds);
  } catch (err) {
    console.error("Redis setCache error:", err);
  }
};

export const getCache = async (key: string): Promise<string | null> => {
  const redis = RedisClient.getInstance();
  if (!redis) return null;
  try {
    return await redis.get(key);
  } catch (err) {
    console.error("Redis getCache error:", err);
    return null;
  }
};

export const deleteCache = async (key: string): Promise<void> => {
  const redis = RedisClient.getInstance();
  if (!redis) return;
  try {
    await redis.del(key);
  } catch (err) {
    console.error("Redis deleteCache error:", err);
  }
};

例:getUser のキャッシュ・アサイド

  • getCache(CACHE_USER(userId)) を試します。キャッシュにあれば、キャッシュされた JSON を返します。
  • なければ、DB からユーザーを読み込み、setCache(cacheKey, JSON.stringify(safeUser), 60) を実行してから返します。
  • Redis が設定されていない場合、getCache/setCache は何もしません。アプリはキャッシュなしでも動作します。
ライブラリ – ユーティリティ(src/lib/utils.ts)
import bcrypt from "bcrypt";

export const emailRegex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
const SALT_ROUNDS = 10;

export const hashPassword = async (password: string): Promise<string> =>
  bcrypt.hash(password, SALT_ROUNDS);

export const comparePassword = async (password: string, hashed: string): Promise<boolean> =>
  bcrypt.compare(password, hashed);
アプリ(src/app.ts)
import express, { Express, NextFunction, Request, Response } from "express";
import cors from "cors";
import http from "http";
import toobusy from "toobusy-js";
import helmet from "helmet";
import { securityMiddleware } from "./middlewares/security";
import indexRoute from "./routes";
import { ErrorHandling } from "./middlewares/error-handling";

toobusy.maxLag(120);

const app: Express = express();
const server = http.createServer(app);

app.use(helmet());
app.use(cors({
  origin: ["http://localhost:3005", "http://localhost:3000"],
  methods: ["GET", "POST", "PUT", "DELETE"],
  allowedHeaders: ["Content-Type", "Authorization"],
}));
app.use(express.json({ limit: "100kb" }));
app.use(express.urlencoded({ extended: false }));
app.use(securityMiddleware);

app.use((req, res, next) => {
  if (toobusy()) return res.status(529).json({ message: "High Traffic" });
  else next();
});

app.use((req, res, next) => {
  res.setHeader("Cache-Control", "no-store");
  next();
});

app.use("/api", indexRoute);

app.get("/", (req: Request, res: Response, next: NextFunction) => {
  res.send("Our Backend Running Correctly");
});

app.use(ErrorHandling);

export { app, server };

リポジトリとドキュメント

検証/完了チェックリスト

ユーザーによるこのテンプレートの実行や拡張を支援する際は、次の点を確認してください。

  • .env が存在し、少なくとも PORT、MONGODB_URI、PRIVATE_KEY、TOKEN_EXPIRED が設定されている。
  • MongoDB に接続できる(Redis を使用する場合は Redis にも接続できる)。
  • エラー監視を行う場合は、SENTRY_DSN が設定されている。
  • npm run dev の実行後、GET / が成功メッセージを返す。
  • 認証ルート(/api/user/register、/api/user/login、GET /api/user)が正しく応答する。
  • 新しいリソースが規約に従っている:型 -> モデル -> コントローラー -> ルート -> index へのマウント。

コメント