Skip to main content
jg-packages

Search

    NestJS

    jg-nestjs

    NestJS for HTTP APIs: an ApiException, a filter and an interceptor for the jg-api-response envelope, schema validation, CORS, and app bootstrap.

    v0.5.1Node.jsESMMIT

    npm

    npm install jg-nestjs

    pnpm

    pnpm add jg-nestjs

    Usage

    Answering in one envelope

    Register the filter and the interceptor once, and every response uses the { success, data, error } envelope from jg-api-response:

    ts
    import { Module } from '@nestjs/common';
    import { APP_FILTER, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
    import { ApiExceptionFilter, ApiResponseInterceptor, SchemaValidationPipe } from 'jg-nestjs';
    
    @Module({
      providers: [
        { provide: APP_FILTER, useClass: ApiExceptionFilter },
        { provide: APP_INTERCEPTOR, useClass: ApiResponseInterceptor },
        { provide: APP_PIPE, useClass: SchemaValidationPipe },
      ],
    })
    export class AppModule {}

    A handler’s result becomes { success: true, data, error: null }, and a 204 sends no body. An error becomes { success: false, error: { code, message, data } }:

    Error Status What the client sees
    ApiException its status, 400 to 599 its code, message, and data
    Another Exception, such as a jg package’s from resolveStatus, else 500 its code, message, and data
    Nest’s HttpException its status HTTP_EXCEPTION, with its message
    A client error Express’s middleware built for clients (expose: true), such as a body over the limit its 4xx statusCode HTTP_EXCEPTION, with its message
    Anything else from resolveStatus, else 500 INTERNAL_ERROR and a generic message, never the error’s own message

    Throw an ApiException for failures the client should understand:

    ts
    import { ApiException } from 'jg-nestjs';
    
    throw new ApiException('The project was not found.', {
      code: 'PROJECT_NOT_FOUND',
      status: 404,
      severity: 'expected',
    });

    Define a module’s errors once with defineApiErrorCatalog, so every throw site uses the same code, message, status, and severity, and a handler recognizes them by kind:

    ts
    import { defineApiErrorCatalog } from 'jg-nestjs';
    
    const projectErrors = defineApiErrorCatalog({
      notFound: {
        code: 'PROJECT_NOT_FOUND',
        message: 'The project was not found.',
        status: 404,
        severity: 'expected',
      },
      unavailable: { code: 'PROJECTS_UNAVAILABLE', message: 'Projects are unavailable.', status: 503 },
    });
    
    throw projectErrors.create('notFound', { data: { id: 42 } });

    is(error, kind?) compares codes, as jg-exception’s defineErrorCatalog does, so it also recognizes the error after it crossed a package boundary.

    Logging and reporting

    The filter logs, through Nest’s Logger, an error whose throw site set shouldLog or severity: 'critical', and any error that is none of an Exception, an HttpException, and a client error Express’s middleware built for clients, with the method, the redacted URL, and the status. A report option sends errors to an error tracker, except those with severity: 'expected', the statuses in ignoredStatuses (401 and 429 by default), and the codes in ignoredCodes (CORS_ORIGIN_NOT_ALLOWED, MAINTENANCE_MODE, IP_BLOCKED, UPLOAD_REJECTED, and TURNSTILE_FAILED by default). Provide the options as API_EXCEPTION_FILTER_OPTIONS, through any provider: useValue for fixed options, or useFactory with inject when the reporter needs the app’s own services, as a recipe shows. redactUrl removes secrets from URLs before either sees them.

    Validating input

    SchemaValidationPipe validates each parameter that declares a Standard Schema, such as a Zod schema in @Body({ schema }). Invalid input gets a 400 with VALIDATION_FAILED and up to 32 { path, message } issues as its data, and a valid parameter becomes the schema’s output, without __proto__ keys.

    CORS

    ts
    app.enableCors(createCorsOptions({ origins: ['https://app.example.com'] }));

    It allows the listed origins exactly, their www. variants, and requests without an Origin header, which servers and command-line clients send, unless allowOriginless is false. Any other origin gets a 403 with CORS_ORIGIN_NOT_ALLOWED, through the filter, and isn’t reported.

    Maintenance mode and IP blocklists

    MaintenanceModeGuard refuses requests with a 503, MAINTENANCE_MODE, while getState says maintenance is on. The error’s data is the state’s data, as it is, such as { maintenanceMode: { content, updatedAt } } for a client that shows the notice, or else { message } when the state has only a message. getState receives the request’s ExecutionContext, so one guard can keep some routes up, such as an admin sign-in, by reading their metadata with a Reflector, as a recipe shows. IpBlocklistGuard refuses requests from blocked addresses with a 403, IP_BLOCKED, without echoing the address. Each reads its options from its own token, and the app fails to start without them:

    ts
    import { Module } from '@nestjs/common';
    import {
      IP_BLOCKLIST_GUARD_OPTIONS,
      IpBlocklistGuard,
      MAINTENANCE_MODE_GUARD_OPTIONS,
      MaintenanceModeGuard,
    } from 'jg-nestjs';
    
    @Module({
      providers: [
        {
          provide: MAINTENANCE_MODE_GUARD_OPTIONS,
          useValue: { getState: () => ({ enabled: process.env['MAINTENANCE_MODE'] === 'true' }) },
        },
        {
          provide: IP_BLOCKLIST_GUARD_OPTIONS,
          useValue: { isBlocked: (ip: string) => ipBlocklist.has(ip) },
        },
      ],
    })
    export class AppModule {}

    IpBlocklistGuard checks Express’s request.ip, which follows configureHttpApp’s trustProxyHops, or what a getIp option returns, after normalizeIp: trimmed, lowercased, and ::ffff:203.0.113.7 as 203.0.113.7. Normalize addresses the same way when adding them to the list. A request without an address goes through. Both guards fail closed: an error from getState or isBlocked refuses the request, which the filter answers with a 500 and reports. Other contexts, such as microservices, pass.

    Run the cheap refusals first, so a flood or a blocked client never reaches authentication: the rate limiter, then IpBlocklistGuard, then MaintenanceModeGuard, then authentication. Guards in one @UseGuards(ThrottlerGuard, IpBlocklistGuard, MaintenanceModeGuard, AuthGuard) run in that order, and so do APP_GUARD providers, in the order they’re listed. A route that must stay up during maintenance, such as a health check, leaves MaintenanceModeGuard out.

    Uploads

    createUploadInterceptor receives one file into memory, as Nest’s FileInterceptor does with @UploadedFile(), under limits. Call it once at module scope: each call has its own slots, shared by every route that uses the class.

    ts
    import { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
    import { createUploadInterceptor } from 'jg-nestjs';
    
    const AudioUpload = createUploadInterceptor({
      field: 'audio',
      maxBytes: 25_000_000,
      maxConcurrent: 2,
      uploadTimeoutSeconds: 120,
    });
    
    @Controller('transcriptions')
    export class TranscriptionsController {
      @Post()
      @UseInterceptors(AudioUpload)
      public create(@UploadedFile() file: { buffer: Buffer; mimetype: string }) {
        return transcribe(file.buffer, file.mimetype);
      }
    }

    The file may hold exactly maxBytes, and the request may send no other part. A request takes a slot before its upload starts and gives it back when the handler ends, so maxConcurrent also bounds the work after the upload; a request beyond the slots gets a 503 with UPLOAD_CAPACITY_FULL, which is reported. A file over the limit gets a 413, and another field or a malformed body a 400, with UPLOAD_REJECTED, which isn’t. An upload still arriving after uploadTimeoutSeconds has its connection closed, and an abandoned one gives its slot back at once. A limit that isn’t a positive integer, or a timeout of 0 or more than 2_147_483 seconds, the longest a timer waits, throws INVALID_UPLOAD_OPTIONS at once, so a limit read from a missing variable never turns into no limit.

    Human verification with Turnstile

    TurnstileGuard, from jg-nestjs/turnstile, lets a request through only when the Cloudflare Turnstile token in its x-turnstile-token header verifies with siteverify, on one of the allowed hostnames, and for the action a route sets with @TurnstileAction:

    ts
    import { Body, Controller, Module, Post, UseGuards } from '@nestjs/common';
    import { TURNSTILE_GUARD_OPTIONS, TurnstileAction, TurnstileGuard } from 'jg-nestjs/turnstile';
    
    @Controller('contact')
    class ContactController {
      @Post()
      @UseGuards(TurnstileGuard)
      @TurnstileAction('contact')
      public send(@Body() message: unknown) {
        return sendContactMessage(message);
      }
    }
    
    @Module({
      controllers: [ContactController],
      providers: [
        {
          provide: TURNSTILE_GUARD_OPTIONS,
          useValue: { secretKey: turnstileSecretKey, allowedHostnames: ['www.example.com'] },
        },
        TurnstileGuard,
      ],
    })
    export class ContactModule {}

    A missing, invalid, expired, or reused token, or one solved on another hostname or for another action, gets a 403 with TURNSTILE_FAILED, which isn’t reported. When siteverify refused the token, the error’s cause holds its error-codes as data.errorCodes, for an app that logs or reports these failures. When siteverify can’t be reached, fails, or refuses the secret key, the request gets a 503 with TURNSTILE_UNAVAILABLE, which is reported with the reason as its cause. Neither tells the client what Cloudflare answered. Siteverify is called through jg-fetch, which retries a network error, a timeout, or a 5xx with the same idempotency key, so a token is verified once. Each token verifies once, so the page resets its widget after every request.

    Bootstrapping an app

    configureHttpApp sets up an Express-based app before it listens, always in this order: JSON and URL-encoded body parsers with bodyLimit, the security middleware, the trusted proxy hops, the request log, versioning, and shutdown hooks on SIGINT and SIGTERM:

    ts
    import { NestFactory } from '@nestjs/core';
    import type { NestExpressApplication } from '@nestjs/platform-express';
    import { raw } from 'express';
    import helmet from 'helmet';
    import { configureHttpApp, listenHttpApp } from 'jg-nestjs';
    
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    // a webhook that checks a signature needs the exact bytes, so its parser comes first
    app.use('/billing/webhooks', raw({ type: 'application/json', limit: '1mb' }));
    configureHttpApp(app, { bodyLimit: '1mb', securityMiddleware: helmet(), trustProxyHops: 1 });
    await listenHttpApp(app, { port: 3000 });

    listenHttpApp closes the app when it can’t listen, such as when the port is taken, so the modules’ shutdown hooks release what they opened before the error reaches the caller, and it logs a failure to close. Import PingModule for GET /ping, which answers 204 with no body whatever version the request asks for, for a load balancer’s health check.

    The request log writes METHOD url status Nms through Nest’s Logger once each response finishes, at error for a 5xx, warn for a 4xx, and log otherwise, with the client’s address, user agent, referer, and response size as structured fields. Its redactUrl option cleans the URL and the referer first, and createRequestLoggingMiddleware gives the same middleware on its own. The prefix and the levels Nest prints belong to Nest’s own logger: NestFactory.create(AppModule, { logger: new ConsoleLogger({ prefix: 'API', logLevels: ['fatal', 'error', 'warn', 'log'] }) }).

    Errors

    Code When
    VALIDATION_FAILED A parameter didn’t match its schema
    HTTP_EXCEPTION A handler, guard, or Nest itself threw an HttpException, such as a 404, or Express’s middleware refused the request with a client error, such as a body over the limit
    INTERNAL_ERROR An error the filter doesn’t recognize, such as a failed database call, reached it
    CORS_ORIGIN_NOT_ALLOWED A browser called from an origin the API doesn’t allow
    MAINTENANCE_MODE MaintenanceModeGuard refused a request while maintenance is on, with a 503
    IP_BLOCKED IpBlocklistGuard refused a request from a blocked address, with a 403
    UPLOAD_CAPACITY_FULL createUploadInterceptor’s slots were all taken, with a 503
    UPLOAD_REJECTED An upload was too large, with a 413, or sent another part or a malformed body, with a 400
    INVALID_UPLOAD_OPTIONS createUploadInterceptor was given a limit that isn’t a positive integer, or a timeout of 0 or more than 2_147_483 seconds, thrown at once
    TURNSTILE_FAILED TurnstileGuard refused a token that didn’t verify, with a 403
    TURNSTILE_UNAVAILABLE TurnstileGuard couldn’t verify a token, with a 503

    ERROR_MESSAGES holds each code’s message.

    Generated from TSDoc

    API reference

    Every export of [email protected], 38 in all, with its signature, its errors, and an example.

    jg-nestjs

    Functionsjg-nestjs

    configureHttpApp
    function

    Configures an Express-based Nest app before it listens, in this order: JSON and URL-encoded body parsers with bodyLimit, the security middleware, the trusted proxy hops, the request log, versioning, and shutdown hooks. A route that needs the raw body, such as a webhook that checks a signature, registers its own parser with app.use before this call, and the JSON parser then leaves its body alone.

    Signature
    configureHttpApp(app: NestExpressApplication, options: IHttpAppOptions): void

    Parameters

    appNestExpressApplication

    The app, from NestFactory.create<NestExpressApplication>.

    optionsIHttpAppOptions

    The body limit, and the optional security middleware, proxy hops, request log, versioning, and shutdown signals.

    Example
    import { VersioningType } from '@nestjs/common';
    import type { NestExpressApplication } from '@nestjs/platform-express';
    import { configureHttpApp } from 'jg-nestjs';
    
    declare const app: NestExpressApplication;
    
    configureHttpApp(app, {
      bodyLimit: '1mb',
      trustProxyHops: 1,
      versioning: { type: VersioningType.URI },
    });
    createCorsOptions
    function

    Creates the CORS options for app.enableCors, allowing only the listed origins, matched exactly, and by default their www. variants and requests without an Origin header. Any other origin is refused with a 403 ApiException, code CORS_ORIGIN_NOT_ALLOWED, which ApiExceptionFilter answers and doesn't report. An origin that isn't a URL throws when the options are created.

    Signature
    createCorsOptions(input: ICorsOptionsInput): CorsOptions

    Parameters

    inputICorsOptionsInput

    The allowed origins, and whether to allow requests without an origin, www. variants, and credentials.

    Returns

    CorsOptions

    The options.

    Example
    import type { INestApplication } from '@nestjs/common';
    import { createCorsOptions } from 'jg-nestjs';
    
    declare const app: INestApplication;
    
    app.enableCors(createCorsOptions({ origins: ['https://app.example.com'] }));
    createRequestLoggingMiddleware
    function

    Creates a middleware that logs each request once its response finishes, through Nest's Logger: METHOD url status Nms, at error for a 5xx, warn for a 4xx, and log otherwise, with the client's address, user agent, referer, and response size as structured fields when they're known. The URL and the referer go through redactUrl first. The prefix and the levels Nest prints are set on Nest's own ConsoleLogger.

    Signature
    createRequestLoggingMiddleware(
      options?: IRequestLoggingOptions,
    ): (request: IncomingMessage, response: ServerResponse, next: () => void) => void

    Parameters

    options?IRequestLoggingOptions

    The Logger context, and how to redact URLs.

    Defaults to {}.

    Returns

    (request: IncomingMessage, response: ServerResponse, next: () => void) => void

    The middleware, for app.use.

    Example
    import type { INestApplication } from '@nestjs/common';
    import { createRequestLoggingMiddleware } from 'jg-nestjs';
    
    declare const app: INestApplication;
    
    app.use(
      createRequestLoggingMiddleware({
        redactUrl: (url) => url.replace(/token=[^&]+/, 'token=[redacted]'),
      }),
    );
    createUploadInterceptor
    function

    Creates an interceptor that receives one file from a multipart request into memory, as Nest's FileInterceptor does with @UploadedFile(), under limits: the file holds at most maxBytes, no other part is accepted, at most maxConcurrent requests hold a slot at once, and an upload that takes longer than uploadTimeoutSeconds has its connection closed. A slot is taken before the upload starts and given back when the handler ends or the upload fails.

    Each call creates a class with its own slots, shared by every instance Nest makes of it, so call it once at module scope and use the class wherever those slots apply. A request beyond the slots gets a 503 with UPLOAD_CAPACITY_FULL, which is reported. A file over the limit gets a 413 and a malformed request a 400, with UPLOAD_REJECTED, which isn't. Options that aren't positive integers, or a timeout of 0 or more than MAX_UPLOAD_TIMEOUT_SECONDS, throw at once, so a limit read from a missing variable never turns into no limit.

    Signature
    createUploadInterceptor(
      options: IUploadInterceptorOptions,
    ): Type<NestInterceptor<any, any>>

    Parameters

    optionsIUploadInterceptorOptions

    The file's field, its byte limit, the slots, and the upload timeout.

    Returns

    Type<NestInterceptor<any, any>>

    The interceptor's class.

    Throws

    • INVALID_UPLOAD_OPTIONSThe upload options are invalid.
    Example
    import { Controller, Post, UploadedFile, UseInterceptors } from '@nestjs/common';
    import { createUploadInterceptor } from 'jg-nestjs';
    
    const AudioUpload = createUploadInterceptor({
      field: 'audio',
      maxBytes: 25_000_000,
      maxConcurrent: 2,
      uploadTimeoutSeconds: 120,
    });
    
    @Controller('transcriptions')
    export class TranscriptionsController {
      @Post()
      @UseInterceptors(AudioUpload)
      public create(@UploadedFile() file: { buffer: Buffer; mimetype: string }): number {
        return file.buffer.byteLength;
      }
    }
    defineApiErrorCatalog
    function

    Defines the errors a module answers with in one place, by kind, as jg-exception's defineErrorCatalog does, with each kind's response status: create builds the kind's ApiException, and is tells whether an error is one of the catalog's, or of one kind, comparing codes.

    Signature
    defineApiErrorCatalog<TKind extends string>(
      entries: Record<TKind, IApiErrorCatalogEntry>,
    ): IApiErrorCatalog<TKind>

    Parameters

    entriesRecord<TKind, IApiErrorCatalogEntry>

    Each kind's code, message, status, and severity.

    Returns

    IApiErrorCatalog<TKind>

    The catalog.

    Example
    import { defineApiErrorCatalog } from 'jg-nestjs';
    
    const projectErrors = defineApiErrorCatalog({
      notFound: { code: 'PROJECT_NOT_FOUND', message: 'The project was not found.', status: 404, severity: 'expected' },
      nameTaken: { code: 'PROJECT_NAME_TAKEN', message: 'The project name is taken.', status: 409, severity: 'expected' },
    });
    const error = projectErrors.create('notFound', { data: { id: 42 } });
    error.status; // => 404
    projectErrors.is(error, 'notFound'); // => true
    listenHttpApp
    function

    Starts an app listening, and closes it when it can't, such as when the port is taken, so its shutdown hooks release what the modules opened, such as database pools, before the error reaches the caller. A failure to close is logged, and the listen error is rethrown either way.

    Signature
    listenHttpApp(
      app: INestApplication,
      options: IListenHttpAppOptions,
    ): Promise<void>

    Parameters

    appINestApplication

    The app, configured and ready to listen.

    optionsIListenHttpAppOptions

    The port, and the host to bind, which defaults to every interface.

    Returns

    Promise<void>

    A promise that resolves once the app is listening.

    Throws

    • ErrorWhat `app.listen` rejects with, such as EADDRINUSE for a port in use.
    Example
    import { NestFactory } from '@nestjs/core';
    import type { NestExpressApplication } from '@nestjs/platform-express';
    import { configureHttpApp, listenHttpApp } from 'jg-nestjs';
    
    declare const AppModule: new () => object;
    
    const app = await NestFactory.create<NestExpressApplication>(AppModule);
    configureHttpApp(app, { bodyLimit: '1mb' });
    await listenHttpApp(app, { port: 3000, host: '127.0.0.1' });
    normalizeIp
    function

    Normalizes an IP address the way IpBlocklistGuard checks it: trimmed, lowercased, and an IPv4 address mapped into IPv6, as ::ffff:203.0.113.7, as plain IPv4. Normalize addresses the same way before adding them to the blocklist.

    Signature
    normalizeIp(ip: string): string

    Parameters

    ipstring

    The address.

    Returns

    string

    The normalized address.

    Example
    import { normalizeIp } from 'jg-nestjs';
    
    normalizeIp(' ::FFFF:203.0.113.7 '); // '203.0.113.7'
    normalizeIp('2001:DB8::1'); // '2001:db8::1'

    Classesjg-nestjs

    ApiException
    class

    An Exception that sets the HTTP status of the response ApiExceptionFilter sends: its code, message, and data go to the client in the jg-api-response envelope, so they must be safe to show. The status is an integer from 400 to 599, and 500 when it's missing or anything else.

    Members

    • codeproperty
      string
    • dataproperty
      IJsonValue | undefined
    • severityproperty
      "expected" | "critical"
    • shouldLogproperty
      boolean
    • toJSONmethod
      toJSON(): IExceptionJson

      Converts the exception to a plain object, which JSON.stringify calls.

    • toStringmethod
      toString(): string

      Describes the exception in one line, with its code.

    • statusproperty
      number

      the response's status, from 400 to 599

    • constructorconstructor
      new ApiException(message: string, options: IApiExceptionOptions)

      Creates an API exception.

    Example
    import { ApiException } from 'jg-nestjs';
    
    throw new ApiException('The project was not found.', {
      code: 'PROJECT_NOT_FOUND',
      status: 404,
      data: { id: 42 },
      severity: 'expected',
    });
    ApiExceptionFilter
    class

    Answers every error an HTTP request throws, from a handler, guard, pipe, or middleware, with the jg-api-response envelope. An ApiException sets the status; an Exception sends its code, message, and data; an HttpException sends HTTP_EXCEPTION with its own message, as does a client error Express's middleware built for clients, such as a body over the limit, with its own 4xx; and anything else gets a 500 with INTERNAL_ERROR and a generic message, while the error itself goes only to the logs and the reporter. It logs an error that its throw site marked shouldLog or critical, or that is none of those anticipated kinds, and reports every error except an expected one or one whose status or code is ignored. Errors outside HTTP are rethrown. Its options come from API_EXCEPTION_FILTER_OPTIONS through any provider, such as useFactory with injected services.

    Members

    • constructorconstructor
      new ApiExceptionFilter(__adapterHost: HttpAdapterHost, options?: IApiExceptionFilterOptions)

      Creates the filter. Nest injects its arguments.

    • catchmethod
      catch(error: unknown, host: ArgumentsHost): void

      Answers an error with the envelope, after logging and reporting it.

    Example
    import { Module } from '@nestjs/common';
    import { APP_FILTER } from '@nestjs/core';
    import { API_EXCEPTION_FILTER_OPTIONS, ApiExceptionFilter, type IApiExceptionFilterOptions } from 'jg-nestjs';
    
    const filterOptions: IApiExceptionFilterOptions = {
      redactUrl: (url) => url.replace(/token=[^&]+/, 'token=[redacted]'),
    };
    
    @Module({
      providers: [
        { provide: API_EXCEPTION_FILTER_OPTIONS, useValue: filterOptions },
        { provide: APP_FILTER, useClass: ApiExceptionFilter },
      ],
    })
    export class AppModule {}
    ApiResponseInterceptor
    class

    Wraps what each HTTP handler returns in the jg-api-response envelope, { success: true, data, error: null }, which ApiExceptionFilter's error envelope matches. Other contexts, such as microservices, pass through untouched. A handler that answers 204 sends no body, envelope included.

    Members

    • constructorconstructor
      new ApiResponseInterceptor()
    • interceptmethod
      intercept(context: ExecutionContext, next: CallHandler): Observable<unknown>

      Wraps an HTTP handler's result in the envelope.

    Example
    import { Module } from '@nestjs/common';
    import { APP_INTERCEPTOR } from '@nestjs/core';
    import { ApiResponseInterceptor } from 'jg-nestjs';
    
    @Module({
      providers: [{ provide: APP_INTERCEPTOR, useClass: ApiResponseInterceptor }],
    })
    export class AppModule {}
    IpBlocklistGuard
    class

    Refuses HTTP requests from blocked IP addresses with a 403, IP_BLOCKED, which carries no data and which the filter doesn't report. It reads the client's address with getIp, Express's request.ip by default, normalizes it with normalizeIp, and lets a request without one through. It fails closed: an error from isBlocked refuses the request. It never echoes the address or changes the request. Other contexts, such as microservices, pass. Its options come from IP_BLOCKLIST_GUARD_OPTIONS, and the app fails to start without them.

    Members

    • constructorconstructor
      new IpBlocklistGuard(__options: IIpBlocklistGuardOptions)

      Creates the guard. Nest injects its options.

    • canActivatemethod
      canActivate(context: ExecutionContext): Promise<boolean>

      Lets an HTTP request through unless its client's address is blocked.

    Example
    import { Module } from '@nestjs/common';
    import { APP_GUARD } from '@nestjs/core';
    import { IP_BLOCKLIST_GUARD_OPTIONS, IpBlocklistGuard } from 'jg-nestjs';
    
    const BLOCKED_IPS = new Set(['203.0.113.7']);
    
    @Module({
      providers: [
        { provide: IP_BLOCKLIST_GUARD_OPTIONS, useValue: { isBlocked: (ip: string) => BLOCKED_IPS.has(ip) } },
        { provide: APP_GUARD, useClass: IpBlocklistGuard },
      ],
    })
    export class AppModule {}
    MaintenanceModeGuard
    class

    Refuses HTTP requests with a 503 while the API is down for maintenance, reading the state on every request, given its context, so turning it on or off needs no restart and a route can be exempted by its metadata. The error, MAINTENANCE_MODE, carries the state's data as it is, or else its message as { message }, and the filter doesn't report it. It fails closed: an error reading the state refuses the request. Other contexts, such as microservices, pass. Its options come from MAINTENANCE_MODE_GUARD_OPTIONS, and the app fails to start without them.

    Members

    • constructorconstructor
      new MaintenanceModeGuard(__options: IMaintenanceModeGuardOptions)

      Creates the guard. Nest injects its options.

    • canActivatemethod
      canActivate(context: ExecutionContext): Promise<boolean>

      Lets an HTTP request through unless the API is down for maintenance.

    Example
    import { Module } from '@nestjs/common';
    import { APP_GUARD } from '@nestjs/core';
    import { MAINTENANCE_MODE_GUARD_OPTIONS, MaintenanceModeGuard } from 'jg-nestjs';
    
    @Module({
      providers: [
        {
          provide: MAINTENANCE_MODE_GUARD_OPTIONS,
          useValue: { getState: () => ({ enabled: process.env['MAINTENANCE_MODE'] === 'true' }) },
        },
        { provide: APP_GUARD, useClass: MaintenanceModeGuard },
      ],
    })
    export class AppModule {}
    PingModule
    class

    Adds GET /ping, which answers 204 with no body whatever version the request asks for, for a load balancer's or an uptime monitor's check. It runs the app's global guards like any route, so a check that must pass during maintenance needs the route exempted.

    Members

    • constructorconstructor
      new PingModule()
    Example
    import { Module } from '@nestjs/common';
    import { PingModule } from 'jg-nestjs';
    
    @Module({ imports: [PingModule] })
    export class AppModule {}
    SchemaValidationPipe
    class

    Validates each parameter that declares a Standard Schema, such as a Zod schema in @Body({ schema }), and answers invalid input with a 400 ApiException: code VALIDATION_FAILED, with up to 32 { path, message } issues as its data. A valid parameter becomes the schema's output, and keys such as __proto__ are stripped before validation.

    Members

    • constructorconstructor
      new SchemaValidationPipe()
    • transformmethod
      transform(value: unknown, metadata: ArgumentMetadata): Promise<unknown>

      Validates a parameter against the schema it declares, if any.

    Example
    import { Body, Controller, Module, Post } from '@nestjs/common';
    import { APP_PIPE } from '@nestjs/core';
    import { SchemaValidationPipe } from 'jg-nestjs';
    import { z } from 'zod';
    
    const CreateProjectSchema = z.strictObject({ name: z.string().min(1).max(64) });
    
    @Controller('projects')
    class ProjectsController {
      @Post()
      create(@Body({ schema: CreateProjectSchema }) body: z.infer<typeof CreateProjectSchema>) {
        return { name: body.name };
      }
    }
    
    @Module({
      controllers: [ProjectsController],
      providers: [{ provide: APP_PIPE, useClass: SchemaValidationPipe }],
    })
    export class AppModule {}

    Constantsjg-nestjs

    API_EXCEPTION_FILTER_OPTIONS
    const

    the token ApiExceptionFilter reads its options from, through any provider, such as useValue, or useFactory to build them from injected services

    Declaration
    const API_EXCEPTION_FILTER_OPTIONS: typeof API_EXCEPTION_FILTER_OPTIONS
    ERROR_MESSAGES
    const

    The message each error answers with. An HTTP_EXCEPTION answers with the HttpException's or the exposed client error's own message instead, and its entry describes it. INTERNAL_ERROR's is all a client sees of an unexpected error.

    Declaration
    const ERROR_MESSAGES: Record<keyof typeof ERRORS, string>
    ERRORS
    const

    the codes of every error the package answers with, and of its own misconfiguration

    Declaration
    const ERRORS: { VALIDATION_FAILED: "VALIDATION_FAILED"; HTTP_EXCEPTION: "HTTP_EXCEPTION"; INTERNAL_ERROR: "INTERNAL_ERROR"; CORS_ORIGIN_NOT_ALLOWED: "CORS_ORIGIN_NOT_ALLOWED"; MAINTENANCE_MODE: "MAINTENANCE_MODE"; IP_BLOCKED: "IP_BLOCKED"; UPLOAD_CAPACITY_FULL: "UPLOAD_CAPACITY_FULL"; UPLOAD_REJECTED: "UPLOAD_REJECTED"; INVALID_UPLOAD_OPTIONS: "INVALID_UPLOAD_OPTIONS"; TURNSTILE_FAILED: "TURNSTILE_FAILED"; TURNSTILE_UNAVAILABLE: "TURNSTILE_UNAVAILABLE" }
    IP_BLOCKLIST_GUARD_OPTIONS
    const

    the token IpBlocklistGuard reads its options from, provided with useValue or useFactory

    Declaration
    const IP_BLOCKLIST_GUARD_OPTIONS: typeof IP_BLOCKLIST_GUARD_OPTIONS
    MAINTENANCE_MODE_GUARD_OPTIONS
    const

    the token MaintenanceModeGuard reads its options from, provided with useValue or useFactory

    Declaration
    const MAINTENANCE_MODE_GUARD_OPTIONS: typeof MAINTENANCE_MODE_GUARD_OPTIONS

    Typesjg-nestjs

    IApiErrorCatalog
    type

    what defineApiErrorCatalog returns: a catalog that creates ApiExceptions

    Declaration
    type IApiErrorCatalog<TKind extends string> = {
        create: (kind: TKind, options?: IErrorCatalogOptions) => ApiException;
        is: (error: unknown, kind?: TKind) => error is Exception;
    };

    Members

    • createproperty
      (kind: TKind, options?: IErrorCatalogOptions) => ApiException

      creates the kind's ApiException, with its code, message, severity, and status

    • isproperty
      (error: unknown, kind?: TKind) => error is Exception

      whether an error is an Exception with one of the catalog's codes, or with the kind's code

    IApiErrorCatalogEntry
    type

    one kind of an API error catalog: an error catalog entry and the response's status

    Declaration
    type IApiErrorCatalogEntry = IErrorCatalogEntry & {
        status: number;
    };
    IApiExceptionFilterOptions
    type

    how ApiExceptionFilter reports and logs errors, provided as API_EXCEPTION_FILTER_OPTIONS

    Declaration
    type IApiExceptionFilterOptions = {
        report?: ((report: IErrorReport) => void | Promise<void>) | undefined;
        resolveStatus?: ((error: unknown) => number | undefined) | undefined;
        ignoredStatuses?: readonly number[] | undefined;
        ignoredCodes?: readonly string[] | undefined;
        redactUrl?: ((url: string) => string) | undefined;
    };

    Members

    • reportproperty
      (report: IErrorReport) => void | Promise<void>

      sends an error to an error tracker. It runs without delaying the response, and a throw or a rejection is logged

    • resolveStatusproperty
      (error: unknown) => number | undefined

      gives the status of an error that is none of an ApiException, an HttpException, and an exposed client error, such as one from a library. A value that isn't an integer from 400 to 599 is ignored

    • ignoredStatusesproperty
      readonly number[]

      the statuses that are never reported. Defaults to 401 and 429

    • ignoredCodesproperty
      readonly string[]

      the error codes that are never reported. Defaults to CORS_ORIGIN_NOT_ALLOWED, MAINTENANCE_MODE, IP_BLOCKED, UPLOAD_REJECTED, and TURNSTILE_FAILED

    • redactUrlproperty
      (url: string) => string

      removes secrets from a URL before it's logged or reported, such as a token in the query. Defaults to leaving it as it is

    IApiExceptionOptions
    type

    the options an ApiException is created with: an Exception's, and the HTTP status to answer with

    Declaration
    type IApiExceptionOptions = IExceptionOptions & {
        status?: number | undefined;
    };
    ICorsOptionsInput
    type

    what createCorsOptions takes

    Declaration
    type ICorsOptionsInput = {
        origins: readonly string[];
        allowOriginless?: boolean | undefined;
        includeWwwVariants?: boolean | undefined;
        credentials?: boolean | undefined;
    };

    Members

    • originsproperty
      readonly string[]

      the browser origins the API serves, such as https://app.example.com

    • allowOriginlessproperty
      boolean

      whether a request without an Origin header, such as one from a server or a command-line client, is allowed. Defaults to true

    • includeWwwVariantsproperty
      boolean

      whether each origin also allows its www. variant, or the one without it, with the same scheme and port. Defaults to true

    • credentialsproperty
      boolean

      whether browsers may send cookies and other credentials. Defaults to false

    IErrorReport
    type

    what ApiExceptionFilter hands its reporter about one error

    Declaration
    type IErrorReport = {
        error: unknown;
        status: number;
        severity: IExceptionSeverity | undefined;
        request: IncomingMessage;
        url: string;
    };

    Members

    • errorproperty
      unknown

      the error a handler, guard, pipe, or middleware threw

    • statusproperty
      number

      the status the response got

    • severityproperty
      IExceptionSeverity | undefined

      the severity the throw site gave an Exception, if any

    • requestproperty
      IncomingMessage

      the request that failed

    • urlproperty
      string

      the request's URL, already through redactUrl

    IHttpAppOptions
    type

    what configureHttpApp takes

    Declaration
    type IHttpAppOptions = {
        bodyLimit: string | number;
        securityMiddleware?: ((request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void) | undefined;
        trustProxyHops?: number | undefined;
        requestLogging?: IRequestLoggingOptions | false | undefined;
        versioning?: VersioningOptions | undefined;
        shutdownSignals?: readonly string[] | undefined;
    };

    Members

    • bodyLimitproperty
      string | number

      the most a JSON or URL-encoded body may hold, such as '1mb', or a number of bytes. A larger body is refused with a 413, which ApiExceptionFilter answers as HTTP_EXCEPTION

    • securityMiddlewareproperty
      (request: IncomingMessage, response: ServerResponse, next: (error?: unknown) => void) => void

      middleware that runs before the request log, such as helmet()

    • trustProxyHopsproperty
      number

      how many proxies in front of the app to trust for the client's address, such as 1 behind one load balancer. Only a positive integer is applied

    • requestLoggingproperty
      IRequestLoggingOptions | false

      the request log's options, or false for none. Defaults to logging every request under the HTTP context

    • versioningproperty
      VersioningOptions

      how the API's routes are versioned, such as { type: VersioningType.URI }

    • shutdownSignalsproperty
      readonly string[]

      the signals that close the app gracefully, running its shutdown hooks. Defaults to SIGINT and SIGTERM

    IIpBlocklistGuardOptions
    type

    what IpBlocklistGuard takes, through IP_BLOCKLIST_GUARD_OPTIONS

    Declaration
    type IIpBlocklistGuardOptions = {
        isBlocked: (ip: string) => boolean | Promise<boolean>;
        getIp?: ((request: IIpBlocklistRequest) => string | undefined) | undefined;
    };

    Members

    • isBlockedproperty
      (ip: string) => boolean | Promise<boolean>

      resolves to whether the normalized address is blocked, such as with jg-redis's blocklist. An error it throws refuses the request, which the filter answers with a 500 and reports

    • getIpproperty
      (request: IIpBlocklistRequest) => string | undefined

      reads the client's address from the request. Defaults to Express's request.ip, which follows configureHttpApp's trustProxyHops

    IIpBlocklistRequest
    type

    the request IpBlocklistGuard reads the client's address from, with Express's ip

    Declaration
    type IIpBlocklistRequest = IncomingMessage & {
        ip?: string | undefined;
    };
    IListenHttpAppOptions
    type

    what listenHttpApp takes

    Declaration
    type IListenHttpAppOptions = {
        port: number;
        host?: string | undefined;
    };

    Members

    • portproperty
      number

      the port to listen on, or 0 for any free port

    • hostproperty
      string

      the address to bind, such as '127.0.0.1' to accept only local connections. Defaults to every interface

    IMaintenanceModeGuardOptions
    type

    what MaintenanceModeGuard takes, through MAINTENANCE_MODE_GUARD_OPTIONS

    Declaration
    type IMaintenanceModeGuardOptions = {
        getState: (context: ExecutionContext) => IMaintenanceModeState | Promise<IMaintenanceModeState>;
    };

    Members

    • getStateproperty
      (context: ExecutionContext) => IMaintenanceModeState | Promise<IMaintenanceModeState>

      reads the current state on every request, such as from an environment flag or a stored record, given the request's context, so it can exempt a route by its metadata. An error it throws refuses the request, which the filter answers with a 500 and reports

    IMaintenanceModeState
    type

    whether the API is down for maintenance, and what to tell clients meanwhile

    Declaration
    type IMaintenanceModeState = {
        enabled: boolean;
        message?: string | undefined;
        data?: IJsonValue | undefined;
    };

    Members

    • enabledproperty
      boolean

      whether requests are refused

    • messageproperty
      string

      a note for clients, such as when the service is expected back, sent as the error's data, { message }, when there's no data

    • dataproperty
      IJsonValue

      what the client reads, such as { maintenanceMode: { content, updatedAt } }, sent as the error's data as it is, in place of the message

    IRequestLoggingOptions
    type

    what createRequestLoggingMiddleware takes

    Declaration
    type IRequestLoggingOptions = {
        context?: string | undefined;
        redactUrl?: ((url: string) => string) | undefined;
    };

    Members

    • contextproperty
      string

      the Logger context the request log is written under. Defaults to HTTP

    • redactUrlproperty
      (url: string) => string

      removes secrets from a URL or a referer before it's logged, such as a token in the query. Defaults to leaving it as it is

    IUploadInterceptorOptions
    type

    what createUploadInterceptor takes

    Declaration
    type IUploadInterceptorOptions = {
        field: string;
        maxBytes: number;
        maxConcurrent: number;
        uploadTimeoutSeconds: number;
    };

    Members

    • fieldproperty
      string

      the multipart field that holds the file, the only part a request may send

    • maxBytesproperty
      number

      the most bytes the file may hold

    • maxConcurrentproperty
      number

      the most requests that may hold a slot at once, from the upload's start until the handler ends

    • uploadTimeoutSecondsproperty
      number

      the seconds an upload may take before its connection is closed

    jg-nestjs/turnstile

    Classesjg-nestjs/turnstile

    TurnstileGuard
    class

    Lets an HTTP request through only when the Cloudflare Turnstile token in its x-turnstile-token header verifies: siteverify says it's valid, it was solved on one of the allowed hostnames, and, when the route sets one with @TurnstileAction, for that action. Each token can be verified once, so the client renders a new widget for each request.

    A missing, invalid, expired, or reused token, or one from another hostname or action, gets a 403 with TURNSTILE_FAILED, which isn't reported; when siteverify refused the token, its error codes are in the cause's data. When siteverify can't be reached, answers with an error, or refuses the secret, the request gets a 503 with TURNSTILE_UNAVAILABLE, which is reported with the reason as its cause. Neither tells the client what Cloudflare answered. Siteverify is called through jg-fetch's request, which retries the POST on a network error, a timeout, or a 5xx, with the same idempotency key, so Cloudflare verifies the token once. Other contexts, such as microservices, pass. Its options come from TURNSTILE_GUARD_OPTIONS, and the app fails to start without them.

    Members

    • constructorconstructor
      new TurnstileGuard(__options: ITurnstileGuardOptions, __reflector: Reflector)

      Creates the guard. Nest injects its arguments.

    • canActivatemethod
      canActivate(context: ExecutionContext): Promise<boolean>

      Lets an HTTP request through when its Turnstile token verifies.

    Example
    import { Module } from '@nestjs/common';
    import { TURNSTILE_GUARD_OPTIONS, TurnstileGuard } from 'jg-nestjs/turnstile';
    
    @Module({
      providers: [
        {
          provide: TURNSTILE_GUARD_OPTIONS,
          useValue: {
            secretKey: process.env['TURNSTILE_SECRET_KEY'] ?? '',
            allowedHostnames: ['app.example.com'],
          },
        },
        TurnstileGuard,
      ],
      exports: [TurnstileGuard],
    })
    export class HumanVerificationModule {}

    Constantsjg-nestjs/turnstile

    TURNSTILE_GUARD_OPTIONS
    const

    the token TurnstileGuard reads its options from, provided with useValue or useFactory

    Declaration
    const TURNSTILE_GUARD_OPTIONS: typeof TURNSTILE_GUARD_OPTIONS
    TURNSTILE_TOKEN_HEADER
    const

    the request header the client sends the widget's token in

    Declaration
    const TURNSTILE_TOKEN_HEADER: "x-turnstile-token"
    TurnstileAction
    const

    Sets the action a route's Turnstile widget must have been rendered with, such as 'contact', so a token solved for another form, such as sign-up, is refused there. On a controller, it applies to every route, and a route's own overrides it.

    Declaration
    const TurnstileAction: ReflectableDecorator<string, string>
    Example
    import { Body, Controller, Post, UseGuards } from '@nestjs/common';
    import { TurnstileAction, TurnstileGuard } from 'jg-nestjs/turnstile';
    
    @Controller('contact')
    export class ContactController {
      @Post()
      @UseGuards(TurnstileGuard)
      @TurnstileAction('contact')
      public send(@Body() message: unknown): unknown {
        return message;
      }
    }

    Typesjg-nestjs/turnstile

    ITurnstileGuardOptions
    type

    what TurnstileGuard takes, through TURNSTILE_GUARD_OPTIONS

    Declaration
    type ITurnstileGuardOptions = {
        secretKey: string;
        allowedHostnames: readonly string[];
    };

    Members

    • secretKeyproperty
      string

      the widget's secret key, from Cloudflare's dashboard

    • allowedHostnamesproperty
      readonly string[]

      the hostnames the challenge may be solved on, such as 'app.example.com'. A verification from any other, or without one, is refused