Index of every page on this site: llms.txt
All skills
mcollina avatar

/node

@c75d70d
by Matteo Collinamcollina/skills2k stars
146
Run it yourself

Provides domain-specific best practices for Node.js development with TypeScript, covering type stripping, async patterns, error handling, streams, modules, testing, performance, caching, logging, and more. Use when setting up Node.js projects with native TypeScript support, configuring type stripping (--experimental-strip-types), writing Node 22+ TypeScript without a build step, or when the user mentions 'native TypeScript in Node', 'strip types', 'Node 22 TypeScript', '.ts files without compilation', 'ts-node alternative', or needs guidance on error handling, graceful shutdown, flaky tests, profiling, or environment configuration in Node.js. Helps configure tsconfig.json for type stripping, set up package.json scripts, handle module resolution and import extensions, and apply robust patterns across the full Node.js stack.

Use this Skill: https://skilld.dev/gh/mcollina/skills/node

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

ruleserror-handling.md

≈979 tokens on demand. Your agent reads this file only when SKILL.md points to it.

Error Handling in Node.js

Custom Errors with @fastify/create-error

Use @fastify/create-error for creating custom errors with codes:

import createError from '@fastify/create-error';

const NotFoundError = createError('NOT_FOUND', '%s not found', 404);
const ValidationError = createError('VALIDATION_ERROR', '%s', 400);
const DatabaseError = createError('DATABASE_ERROR', 'Database operation failed: %s', 500);

// Usage
throw new NotFoundError('User');
throw new ValidationError('Email is required');

Minimal Error Code Implementation

If you prefer no dependencies, use this minimal pattern:

interface AppErrorOptions {
  code: string;
  statusCode?: number;
  cause?: Error;
}

function createAppError(message: string, options: AppErrorOptions): Error {
  const error = new Error(message, { cause: options.cause });
  (error as any).code = options.code;
  (error as any).statusCode = options.statusCode ?? 500;
  Error.captureStackTrace(error, createAppError);
  return error;
}

// Factory functions for common errors
function notFound(resource: string): Error {
  return createAppError(`${resource} not found`, { code: 'NOT_FOUND', statusCode: 404 });
}

function validationError(message: string): Error {
  return createAppError(message, { code: 'VALIDATION_ERROR', statusCode: 400 });
}

function databaseError(message: string, cause?: Error): Error {
  return createAppError(message, { code: 'DATABASE_ERROR', statusCode: 500, cause });
}

// Usage
throw notFound('User');
throw validationError('Email is required');

Checking Error Codes

Check errors by code, not by class:

function isAppError(error: unknown): error is Error & { code: string; statusCode: number } {
  return error instanceof Error && 'code' in error && 'statusCode' in error;
}

try {
  await fetchUser(id);
} catch (error) {
  if (isAppError(error) && error.code === 'NOT_FOUND') {
    return null;
  }
  throw error;
}

Async Error Handling

Always use try-catch with async/await and propagate errors properly:

async function fetchUser(id: string): Promise<User> {
  try {
    const user = await db.users.findById(id);
    if (!user) {
      throw notFound('User');
    }
    return user;
  } catch (error) {
    if (isAppError(error)) {
      throw error;
    }
    throw databaseError('Failed to fetch user', error as Error);
  }
}

Unhandled Rejections and Exceptions

Do not handle unhandledRejection and uncaughtException manually. Use close-with-grace which handles these automatically and triggers graceful shutdown.

See graceful-shutdown.md for proper shutdown handling.

Fastify Error Handling

Fastify has built-in error handling:

import Fastify from 'fastify';

const app = Fastify({ logger: true });

app.setErrorHandler((error, request, reply) => {
  const statusCode = (error as any).statusCode ?? 500;
  const code = (error as any).code ?? 'INTERNAL_ERROR';

  request.log.error(error);

  reply.status(statusCode).send({
    error: {
      code,
      message: error.message,
    },
  });
});

Never Swallow Errors

Never use empty catch blocks that hide errors:

// BAD - error is swallowed
try {
  await riskyOperation();
} catch (error) {
  // Do nothing
}

// GOOD - handle or re-throw
try {
  await riskyOperation();
} catch (error) {
  logger.error({ err: error }, 'Operation failed');
  throw error;
}

Error Cause Chain

Use the cause option to preserve error chains:

try {
  await externalService.call();
} catch (error) {
  throw new Error('Service call failed', { cause: error });
}

Source: SKILL.md on GitHub

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

1 warning2mo5 checks · Risk SAFE
  • Gen Agent Trust Hub2mo

    This skill provides a comprehensive set of Node.js best practices and design patterns, focusing on performance, observability, and robust architecture. No security issues were detected.

  • Socket2mo

    No alerts

  • Snyk2mo

    Risk: LOW · No issues

  • Runlayer8mo

    2/17 files flagged

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at c75d70d. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub last month.

Activeupdated 9 months ago
Other metadata
metadata
{
  "tags": "node, nodejs, javascript, typescript, type-stripping, backend, server"
}

README badge

README badge for mcollina/skills/node