NestJS

website·Indexed 41 days ago

https://docs.nestjs.com/

A progressive Node.js framework for building efficient, reliable, and scalable server-side applications using TypeScript. It provides a modular architecture featuring controllers, providers, modules, middleware, guards, interceptors, and pipes, with built-in support for dependency injection and platform agnosticism.

Tokens
166K
Snippets
887
Records
1K
Agent score
70%

What's inside NestJS

  1. Overview of GraphQL Federation in NestJS

    Federation allows splitting a monolithic GraphQL server into independent microservices. It consists of a gateway and one or more federated microservices (subgraphs). Each microservice holds part of the schema, and the gateway merges them into a single graph for the client.

    Key Constraints: Federation currently does not support subscriptions.

  2. Overview of the NestJS GraphQL CLI Plugin

    The GraphQL CLI plugin is an opt-in tool for the code-first approach that reduces boilerplate by automatically annotating classes. It analyzes the TypeScript AST to:

    • Annotate all input object, object type, and args class properties with @Field (unless @HideField is used).
    • Set the nullable property to true if a property is marked as optional (e.g., name?: string).
    • Determine the type property based on the TypeScript type (including arrays).
    • Generate field descriptions from TSDoc comments if introspectComments is enabled.

    To be analyzed, files must have one of these suffixes: .input.ts, .args.ts, .entity.ts, or .model.ts (configurable via typeFileNameSuffix).

  3. Overview of NestJS Observe MCP Server

    NestJS Observe provides a read-only MCP (Model Context Protocol) server that allows MCP-compatible clients (e.g., Claude Code, Claude Desktop, Cursor, VS Code) to query project telemetry—including regressions, slow operations, error groups, traces, jobs, and alerts—directly without manual data copying. The server uses Streamable HTTP and is stateless, operating via POST requests to https://<api-host>/mcp.
  4. Overview of NestJS Pipes

    Pipes are classes annotated with @Injectable() that implement the PipeTransform interface. They are interposed by Nest just before a controller route handler method is invoked. Pipes serve two primary purposes:

    1. Transformation: Converting input data to a desired format (e.g., string to integer).
    2. Validation: Evaluating input data and throwing an exception if it is invalid, preventing the controller method from executing.

    Pipes run inside the exceptions zone, meaning any thrown exception is handled by the global exceptions filter or context-specific filters.

  5. Overview of the NestJS Framework

    NestJS is a progressive Node.js framework designed for building efficient, reliable, and scalable server-side applications. It is built using TypeScript and leverages a modular architecture based on dependency injection and decorators. By default, NestJS can run on top of Express or Fastify.
  6. Overview of NestJS Observe

    NestJS Observe is the official, auto-instrumented observability platform for NestJS applications. Unlike generic Node.js APM agents that treat the application logic as a black box, NestJS Observe integrates directly with the NestJS request lifecycle (controllers, guards, interceptors, pipes, resolvers, and queue consumers). This allows telemetry to be expressed by class and method (e.g., OrdersService.recalculate) rather than just by HTTP route.

    Key capabilities include:

    • Request Monitoring: Throughput, latency, and failure rates for HTTP, GraphQL, gRPC, and @nestjs/microservices.
    • Distributed Tracing: Trace waterfalls with self-time ranking and cross-service correlation.
    • Error Monitoring: Stack traces with source line context and server-side defect grouping.
    • Job Tracking: Monitoring for queue consumers and cron runs (e.g., BullMQ), including wait time and retry attempts.
    • Runtime Profiling: CPU, memory, event loop delay, and garbage collection sampling.
    • Custom Metrics: Support for counters, gauges, and summaries.
    • User Activity: Per-user action grouping when identifiers are reported.
  7. Overview of NestJS Framework

    Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications. It supports both TypeScript and pure JavaScript, combining elements of Object Oriented Programming (OOP), Functional Programming (FP), and Functional Reactive Programming (FRP). By default, Nest uses Express as its underlying HTTP server framework, but it can be optionally configured to use Fastify. It provides an architectural abstraction layer while still exposing the underlying platform's APIs for third-party module compatibility.
  8. Handle NATS messages with wildcards and context

    In NestJS microservices using NATS, you can use wildcards in the @MessagePattern() decorator to match multiple subjects. The @Ctx() decorator allows access to the NatsContext, which provides metadata about the specific subject that triggered the handler.
    import { MessagePattern, Payload, Ctx } from '@nestjs/microservices';
    import { NatsContext } from '@nestjs/microservices';
    
    @MessagePattern('time.us.*')
    getDate(@Payload() data: number[], @Ctx() context: NatsContext) {
      console.log(`Subject: ${context.getSubject()}`); // e.g. "time.us.east"
      return new Date().toLocaleTimeString();
    }
  9. UnhandledExceptionInfo interface definition

    The UnhandledExceptionInfo interface is used to provide details about exceptions thrown during CQRS processing, including the exception itself and the cause (the event or command that triggered it).
    export interface UnhandledExceptionInfo< 
      Cause = IEvent | ICommand, 
      Exception = any, 
    > {
      exception: Exception;
      cause: Cause;
    }
  10. Understand the NestJS Observe telemetry view hierarchy

    The NestJS Observe dashboard organizes telemetry into three nesting levels to move from high-level detection to root-cause diagnosis:

    1. Analytics (List View): Aggregated data for all routes, jobs, spans, or metrics (throughput, latency, failure rate). Used to identify that a problem exists.
    2. Operation (Operation View): Focused on a specific entity (e.g., GET /orders/:id or a specific job name). Shows trends over time and a list of individual executions to confirm the problem's shape.
    3. Execution (Execution View): Focused on a single request, job run, or span invocation. Provides exact duration, status, user tags, errors, trace waterfalls, and correlated logs. Used for final diagnosis.
  11. Implement a basic NestJS Interceptor

    An interceptor is a class annotated with @Injectable() that implements the NestInterceptor interface. It must implement the intercept() method, which receives the ExecutionContext (providing details about the current request/process) and a CallHandler.

    To allow the route handler to execute, you must call next.handle(). Because handle() returns an RxJS Observable, you can use RxJS operators to execute logic both before and after the route handler runs.

    import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
    import { Observable } from 'rxjs';
    import { tap } from 'rxjs/operators';
    
    @Injectable()
    export class LoggingInterceptor implements NestInterceptor {
      intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
        console.log('Before...');
    
        const now = Date.now();
        return next
          .handle()
          .pipe(
            tap(() => console.log(`After... ${Date.now() - now}ms`)),
          );
      }
    }
  12. Audit application architecture using Nest Devtools

    The Audit page in Nest Devtools acts as an architectural linter, analyzing the serialized graph to surface errors, warnings, and hints. It can detect issues that standard test suites miss, such as controllers with excessive routes, modules with too many dependencies, providers named as guards that aren't registered as such, or request-scoped providers that should be converted to Durable Providers.