Source profileQuality 91/100

agents-inc/skills/src/skills/api-framework-express/SKILL.md

api-framework-express

Express.js routes, middleware, error handling, request/response patterns

Source repository stars
23
Declared platforms
0
Static risk flags
0
Last source update
2026-08-09
Source checked
2026-08-28

Decision brief

What it does: where it fits

Quick Guide: Express uses middleware-based request processing. The three non-negotiable patterns: modular routing via express.Router(), centralized error handling with 4-argument middleware (err, req, res, next), and correct middleware ordering (security first, error handler las…

Best for

    Not for

    • Tasks that require unconfirmed production actions or broad system permissions.
    • Environments where the pinned source and install steps cannot be inspected.

    Compatibility matrix

    Platform support, with evidence labels

    PlatformStatusEvidenceWhat to check
    CodexNot declaredNo explicit evidencePortability before use
    Claude CodeNot declaredNo explicit evidencePortability before use
    CursorNot declaredNo explicit evidencePortability before use
    Gemini CLINot declaredNo explicit evidencePortability before use
    Open the compatibility checker

    Installation

    Inspect first. Install second.

    The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

    Source-detected install commandSource
    npx skills add https://github.com/agents-inc/skills --skill "src/skills/api-framework-express"
    Safe inspection promptEditorial

    Inspect the Agent Skill "api-framework-express" from https://github.com/agents-inc/skills/blob/81d43a51211aca12c85dcc16085fa99014ec548e/src/skills/api-framework-express/SKILL.md at commit 81d43a51211aca12c85dcc16085fa99014ec548e. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

    Workflow

    What the source asks the agent to do

    1. 01

      Pattern 1: Application Setup

      Register body parsers early, mount route modules, register error handler last. See examples/core.md for full implementation.

      Register body parsers early, mount route modules, register error handler last. See examples/core.md for full implementation.Why good: Body parsers before routes so req.body is populated, error handler last to catch all errors, modular route mounting
    2. 02

      CRITICAL: Before Using This Skill

      All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

      Building REST APIs with composable middleware patternsNeed modular route organization with express.Router()Require centralized error handling across all routes
    3. 03

      Philosophy

      Middleware-first architecture. Express processes requests through a chain of middleware functions. Each middleware can modify request/response objects, end the response, or call next() to continue the chain. Everything in Express is middleware - body parsers, auth guards, logger…

      Middleware-first architecture. Express processes requests through a chain of middleware functions. Each middleware can modify request/response objects, end the response, or call next() to continue the chain. Everything…Express 4 vs 5: Express 5 (stable since 2025, now default on npm) auto-forwards errors from rejected promises in async handlers. Express 4 requires explicit try/catch + next(err) or a wrapper utility. Both versions requ…
    4. 04

      Core Patterns

      Register body parsers early, mount route modules, register error handler last. See examples/core.md for full implementation.

      Register body parsers early, mount route modules, register error handler last. See examples/core.md for full implementation.Why good: Body parsers before routes so req.body is populated, error handler last to catch all errors, modular route mountingOne Router per resource, mounted at a path prefix. See examples/routing.md for CRUD examples with parameters.
    5. 05

      Pattern 2: Modular Routes with express.Router()

      One Router per resource, mounted at a path prefix. See examples/routing.md for CRUD examples with parameters.

      One Router per resource, mounted at a path prefix. See examples/routing.md for CRUD examples with parameters.Why good: Router isolates related routes, named export, explicit error forwarding

    Permission review

    Static risk signals and limitations

    No configured static risk pattern was detected

    This is not proof of safety. Runtime behavior, indirect dependencies, and hidden external systems are outside the static scan.

    Evidence record

    Why each signal appears

    EvidenceSourceComputedTestedEditorial
    SignalValueEvidence typeMeaning
    Quality score91/100ComputedDocumentation, specificity, maintenance, and trust rules
    Repository stars23SourceRepository attention, not individual Skill quality
    Compatibility0 platformsSourceDeclared in the catalog source record
    Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

    Pinned source

    Provenance and original SKILL.md

    Repository
    agents-inc/skills
    Skill path
    src/skills/api-framework-express/SKILL.md
    Commit
    81d43a51211aca12c85dcc16085fa99014ec548e
    License
    MIT
    Collected
    2026-08-28
    Default branch
    main
    View the original SKILL.md

    API Development with Express.js

    Quick Guide: Express uses middleware-based request processing. The three non-negotiable patterns: modular routing via express.Router(), centralized error handling with 4-argument middleware (err, req, res, next), and correct middleware ordering (security first, error handler last). Express 5 (now stable, default on npm) auto-forwards async errors; Express 4 requires manual next(err) or a wrapper.


    <critical_requirements>

    CRITICAL: Before Using This Skill

    All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering, import type, named constants)

    (You MUST define error-handling middleware with 4 arguments: (err, req, res, next) - Express identifies error handlers by arity)

    (You MUST register error handlers AFTER all routes and other middleware)

    (You MUST call next(err) to forward async errors in Express 4 - Express 5 auto-forwards rejected promises)

    (You MUST use express.json() and express.urlencoded() for body parsing - req.body is undefined without them)

    </critical_requirements>


    Auto-detection: Express.js, express, app.use, app.get, app.post, app.put, app.delete, express.Router, req.params, req.query, req.body, res.json, res.status, middleware, next(), error handler, router.use, express.static, express.json, express.urlencoded

    When to use:

    • Building REST APIs with composable middleware patterns
    • Need modular route organization with express.Router()
    • Require centralized error handling across all routes
    • Building APIs that need body parsing, static files, or cookie handling
    • Creating route guards for authentication/authorization

    When NOT to use:

    • Need auto-generated OpenAPI documentation from schemas
    • Building edge/serverless functions where cold start matters
    • Need strict end-to-end type safety with schema validation
    • GraphQL APIs (use a dedicated GraphQL server)

    Key patterns covered:

    • Middleware chain with app.use() and next()
    • Modular routes with express.Router()
    • Error handling with 4-argument middleware
    • Async error forwarding (Express 4 vs 5)
    • Request validation middleware
    • Route parameters and query string handling
    • Route guards for authentication/authorization
    • Middleware ordering (security, CORS, rate limit, parsing, routes, errors)

    Detailed Resources:


    Philosophy

    Middleware-first architecture. Express processes requests through a chain of middleware functions. Each middleware can modify request/response objects, end the response, or call next() to continue the chain. Everything in Express is middleware - body parsers, auth guards, loggers, error handlers.

    Express 4 vs 5: Express 5 (stable since 2025, now default on npm) auto-forwards errors from rejected promises in async handlers. Express 4 requires explicit try/catch + next(err) or a wrapper utility. Both versions require the 4-argument signature for error handlers.


    Core Patterns

    Pattern 1: Application Setup

    Register body parsers early, mount route modules, register error handler last. See examples/core.md for full implementation.

    const app: Express = express();
    
    // Body parsing
    app.use(express.json({ limit: JSON_LIMIT }));
    app.use(express.urlencoded({ extended: true }));
    
    // Mount route modules
    app.use("/api/users", userRoutes);
    app.use("/api/products", productRoutes);
    
    // Error handler MUST be last
    app.use(errorHandler);
    
    export { app };
    

    Why good: Body parsers before routes so req.body is populated, error handler last to catch all errors, modular route mounting


    Pattern 2: Modular Routes with express.Router()

    One Router per resource, mounted at a path prefix. See examples/routing.md for CRUD examples with parameters.

    // src/routes/user-routes.ts
    const router = Router();
    
    router.get("/", async (req, res, next) => {
      try {
        const users = await getUsersFromDatabase();
        res.status(HTTP_OK).json({ data: users });
      } catch (error) {
        next(error);
      }
    });
    
    export { router as userRoutes };
    

    Why good: Router isolates related routes, named export, explicit error forwarding


    Pattern 3: Error Handling Middleware (4 Arguments)

    Express identifies error handlers by the 4-argument signature (err, req, res, next). This is the most critical Express pattern to get right. See examples/core.md for full implementation.

    // CRITICAL: Must have exactly 4 arguments
    const errorHandler = (
      err: AppError,
      req: Request,
      res: Response,
      next: NextFunction,
    ): void => {
      if (res.headersSent) {
        next(err);
        return;
      }
    
      const statusCode = err.statusCode || HTTP_INTERNAL_ERROR;
      res.status(statusCode).json({
        error: { message: err.message, code: err.code || "INTERNAL_ERROR" },
      });
    };
    

    Why good: 4 arguments for Express to recognize as error handler, checks headersSent to avoid double-response, consistent error shape

    Common mistake: 3-argument function (err, req, res) is treated as regular middleware - err becomes req, completely wrong behavior


    Pattern 4: Async Error Handling

    Express 5 auto-forwards rejected promises. Express 4 requires explicit forwarding. See examples/core.md for the asyncHandler wrapper.

    // Express 5: async errors auto-forwarded
    router.get("/:id", async (req, res) => {
      const product = await getProductById(req.params.id);
      res.status(HTTP_OK).json({ data: product });
    });
    
    // Express 4: MUST forward manually
    router.get("/:id", async (req, res, next) => {
      try {
        const product = await getProductById(req.params.id);
        res.status(HTTP_OK).json({ data: product });
      } catch (error) {
        next(error); // Required in Express 4
      }
    });
    

    Why this matters: In Express 4, unhandled async rejections cause the request to hang until timeout. Express 5 fixes this but many projects still run Express 4.


    Pattern 5: Request Validation Middleware

    Validate req.body in middleware before the route handler processes it. See examples/middleware.md for full validation patterns.

    const validateUserCreate = (
      req: Request,
      res: Response,
      next: NextFunction,
    ): void => {
      const { name, email } = req.body;
      const errors: string[] = [];
    
      if (!name || name.length < MIN_NAME_LENGTH) errors.push("Name is required");
      if (!email || !email.includes("@")) errors.push("Valid email is required");
    
      if (errors.length > 0) {
        res
          .status(HTTP_BAD_REQUEST)
          .json({ error: { message: "Validation failed", details: errors } });
        return;
      }
      next();
    };
    
    // Apply: router.post("/", validateUserCreate, createHandler);
    

    Why good: Validation separated from business logic, early return on failure, reusable across routes


    Pattern 6: Route Guards (Authentication/Authorization)

    Protect routes with middleware that validates access. See examples/middleware.md for full auth guard implementation.

    // Extend Request with user data
    interface AuthenticatedRequest extends Request {
      user?: { id: string; role: string };
    }
    
    const requireAuth = (
      req: AuthenticatedRequest,
      res: Response,
      next: NextFunction,
    ): void => {
      const token = req.headers.authorization?.replace("Bearer ", "");
      if (!token) {
        res
          .status(HTTP_UNAUTHORIZED)
          .json({ error: { message: "Authentication required" } });
        return;
      }
      req.user = verifyToken(token);
      next();
    };
    
    // Apply to all routes in router: router.use(requireAuth);
    // Apply to specific route: router.delete("/:id", requireAuth, requireRole("admin"), handler);
    

    Why good: Auth middleware reusable, role guard configurable, extends Request type for type safety


    Pattern 7: Middleware Ordering

    Order matters. Security first, error handler last. See examples/middleware.md for complete ordering example.

    1. Security headers (helmet)
    2. CORS
    3. Rate limiting (before body parsing to save resources)
    4. Body parsing (express.json, express.urlencoded)
    5. Request logging
    6. Routes
    7. 404 handler (after all routes)
    8. Error handler (LAST)
    

    Why this order: Security rejects bad requests early. Rate limiting before parsing saves CPU on abusive requests. Error handler must be last to catch all errors from routes.


    Pattern 8: Response Helpers

    Standardize API responses with typed helpers. See examples/routing.md for full implementation.

    const sendSuccess = <T>(res: Response, data: T, statusCode = HTTP_OK): void => {
      res.status(statusCode).json({ success: true, data });
    };
    
    const sendNotFound = (res: Response, resource = "Resource"): void => {
      res
        .status(HTTP_NOT_FOUND)
        .json({ success: false, error: { message: `${resource} not found` } });
    };
    

    Why good: Consistent response shape across all routes, typed helpers reduce boilerplate


    Express 5 Migration Notes

    Express 5 is the default on npm since March 2025. Key changes from Express 4:

    ChangeExpress 4Express 5
    Async errorsManual next(err)Auto-forwarded
    req.body (unparsed){}undefined
    req.queryWritableRead-only getter
    Wildcard routes/*/*splat (no root) or /{*splat} (with root)
    Optional params/:file.:ext?/:file{.:ext}
    urlencoded defaultextended: trueextended: false
    req.hostStrips portIncludes port
    Minimum Node.jsAny18+

    Removed in Express 5: req.param(), res.send(body, status), res.send(status) (use res.sendStatus()), res.json(obj, status), res.redirect(url, status), res.redirect('back') (use req.get('Referrer') || '/'), res.sendfile() (use res.sendFile()), app.del() (use app.delete()).


    <red_flags>

    RED FLAGS

    High Priority:

    • Error handler has only 3 arguments - Express treats it as regular middleware, errors silently ignored
    • Error handler registered before routes - Never catches route errors
    • Missing next(error) in async handlers (Express 4) - Unhandled promise rejection, request hangs
    • Not using express.json() middleware - req.body is undefined for JSON requests
    • Magic HTTP status codes - Use named constants (HTTP_OK = 200, HTTP_NOT_FOUND = 404)

    Medium Priority:

    • All routes in single file - Creates unmaintainable God file, use express.Router()
    • Not checking res.headersSent in error handler - Causes "headers already sent" crashes
    • Default exports on route modules - Violates project conventions
    • Wildcard CORS with credentials - Browsers reject origin: "*" with credentials: true
    • Missing rate limiting on public APIs - Vulnerable to abuse

    Gotchas & Edge Cases:

    • next('route') vs next(error) - String 'route' skips to next route handler; anything else triggers error handler
    • req.query values are always strings - Parse numbers with parseInt(val, 10)
    • express.static without auth - Files publicly accessible unless middleware guards them
    • Router mergeParams: true - Required to access parent route params in nested routers
    • Express 5: req.body is undefined when unparsed - was {} in Express 4, may break if (!req.body) checks

    </red_flags>


    <critical_reminders>

    CRITICAL REMINDERS

    Before implementing ANY Express route, verify these requirements are met:

    All code must follow project conventions in CLAUDE.md

    (You MUST define error-handling middleware with 4 arguments: (err, req, res, next) - Express identifies error handlers by arity)

    (You MUST register error handlers AFTER all routes and other middleware)

    (You MUST call next(err) to forward async errors in Express 4 - Express 5 auto-forwards rejected promises)

    (You MUST use express.json() and express.urlencoded() for body parsing - req.body is undefined without them)

    Failure to follow these rules will cause unhandled errors and broken middleware chains.

    </critical_reminders>

    Frequently asked questions

    What to verify before installation and use

    What does the api-framework-express source document cover?

    Quick Guide: Express uses middleware-based request processing. The three non-negotiable patterns: modular routing via express.Router(), centralized error handling with 4-argument middleware (err, req, res, next), and correct middleware ordering (security first, error handler las…

    How do I install api-framework-express?

    The source record exposes this install command: npx skills add https://github.com/agents-inc/skills --skill "src/skills/api-framework-express". Inspect the command and pinned source before running it.

    Alternatives

    Compare before choosing

    Computed 10045,960

    coreyhaines31/marketingskills

    ab-testing

    When the user wants to plan, design, or implement an A/B test or experiment, or build a growth experimentation program. Also use when the user mentions "A/B test," "split test," "experiment," "test this change," "variant copy," "multivariate test," "hypothesis," "should I test this," "which version is better," "test two versions," "statistical significance," "how long should I run this test," "growth experiments," "experiment velocity," "experiment backlog," "ICE score," "experimentation program

    Computed 10029,236

    garrytan/gbrain

    bulk-ingestion

    End-to-end discipline for turning any large data source (audio libraries, email takeouts, document corpora, chat exports, API dumps) into brain pages at scale. The lifecycle spine: SCHEMA → ACCESS → TRIAL → EVALUATE → IMPROVE → CODIFY → TEST → SKILLIFY → BULK → MONITOR. State is tracked in a durable JSON manifest (see MANIFEST-PATTERN.md) so any crash, session boundary, or subagent fan-out resumes from ground truth instead of memory.

    Computed 10025,136

    alirezarezvani/claude-skills

    app-store-optimization

    App Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklist

    Computed 1005,277

    dotnet/skills

    migrate-vstest-to-mtp

    Migrates .NET test projects from VSTest to Microsoft.Testing.Platform (MTP). Use when user asks to "migrate to MTP", "switch from VSTest", "enable Microsoft.Testing.Platform", "use MTP runner", set OutputType=Exe only for test projects in Directory.Build.props, or mentions EnableMSTestRunner, EnableNUnitRunner, or UseMicrosoftTestingPlatformRunner. USE FOR: MTP behavioral differences vs VSTest (exit code 8, zero tests discovered, --ignore-exit-code, TESTINGPLATFORM_EXITCODE_IGNORE); centralizing