skip to content

A NestJS 12 hybrid app's global ValidationPipe and auth guard work on HTTP routes but never run for its message handlers. Why, and what fixes it?

level: seniorimportance: should knowfreq 25%

answer

  1. connected, not inherited
  2. a fresh config per listener
  3. second argument of connectMicroservice
  4. register globals before connecting
  5. listen before startAllMicroservices

basics

~20 s

connectMicroservice() gives each connected listener its own empty config, so useGlobal*() enhancers and APP_GUARD or APP_PIPE providers stay HTTP-only. Pass { inheritAppConfig: true } as its second argument, after the useGlobal*() calls, to share them.

solid answer

~40 s

A hybrid app is one `NestFactory.create()` application with microservice listeners attached by `app.connectMicroservice()`. By default each connected listener gets a fresh config, so global pipes, guards, interceptors and filters, whether set with `useGlobal*()` or provided under `APP_PIPE`, `APP_GUARD`, `APP_INTERCEPTOR` or `APP_FILTER`, apply to HTTP routes only. Pass `{ inheritAppConfig: true }` as the second argument of `connectMicroservice()`, and call the `useGlobal*()` methods before it, because the listener registers its handlers at connect time. Then make the shared enhancers RPC-aware: `ValidationPipe` throws `BadRequestException`, which a message client receives as "Internal server error" unless something maps it to an RPC error, and a guard that reads `switchToHttp()` should branch on `context.getType()`. Finally, call `listen()` before `startAllMicroservices()` so no message arrives before the lifecycle hooks finish.

code

typescript · 14 lines
typescript
import { ArgumentsHost, Catch, HttpException, RpcExceptionFilter } from '@nestjs/common';
import { Observable, throwError } from 'rxjs';

// bind with @UseFilters(new HttpToRpcFilter()) on the message controllers
@Catch(HttpException)
export class HttpToRpcFilter implements RpcExceptionFilter<HttpException> {
  catch(exception: HttpException, host: ArgumentsHost): Observable<never> {
    return throwError(() => ({
      status: 'error',
      statusCode: exception.getStatus(),
      message: exception.message,
    }));
  }
}

go deeper

for a junior

Recall that a hybrid app is an HTTP app with microservice listeners attached by connectMicroservice(), and that it needs startAllMicroservices() to begin consuming.

for a middle

Explain why global enhancers are not inherited by default, what inheritAppConfig shares (useGlobal*() and the APP_* providers), and why useGlobal*() must come before connectMicroservice().

for a senior

Diagnose the silent gap, then make shared enhancers RPC-aware: guards that branch on getType(), HTTP exceptions mapped to RPC errors, and listen() before startAllMicroservices() so hooks finish first.

for a principal

Decide whether one hybrid process should keep serving both HTTP and messages: shared enhancers and one deploy are convenient, but splitting the listener into its own createMicroservice() service gives separate scaling and failure domains.

## What a hybrid application is A **hybrid application** is one Nest application that listens on more than one source, usually an HTTP server plus one or more microservice listeners. `NestFactory.createMicroservice()` supports a single server, so a hybrid app starts from `NestFactory.create()`, attaches each listener with `app.connectMicroservice()`, and starts them with `app.startAllMicroservices()`. In the order-service scenario, one process serves the public REST API and also handles `{ cmd: 'check_stock' }` messages and `'order_placed'` events from other services. ## Why the global enhancers stop at HTTP Global pipes, guards, interceptors and filters are stored in the application's **config**. When `connectMicroservice()` creates a listener, Nest gives it a fresh, empty config unless told otherwise. That default covers both ways of declaring globals: - the methods on the app: `useGlobalPipes()`, `useGlobalGuards()`, `useGlobalInterceptors()` and `useGlobalFilters()`; - providers registered under the `APP_PIPE`, `APP_GUARD`, `APP_INTERCEPTOR` and `APP_FILTER` tokens. So the HTTP routes are validated and protected, while the message handlers in the same application run with none of it. Nothing fails at boot: the gap shows only when a malformed or unauthenticated message gets through. The opt-in default is defensible. Enhancers written for HTTP tend to assume an HTTP request: a guard that reads an `Authorization` header, a filter that sets a status code, an interceptor that sets response headers. Applied blindly to messages, they misbehave. Sharing should be a decision made per listener, with each shared enhancer checked for RPC. ## The fix, and the ordering rule that comes with it Pass `{ inheritAppConfig: true }` as the **second** argument of `connectMicroservice()`. The connected listener then shares the HTTP application's config. In order, the bootstrap does four things: 1. Create the application with `NestFactory.create()`. 2. Register every `useGlobal*()` enhancer. 3. Call `connectMicroservice()` with `inheritAppConfig` for each listener. 4. Call `app.listen()`, then `app.startAllMicroservices()`. ```ts const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe({ whitelist: true })); app.useGlobalGuards(new ApiKeyGuard()); // after the useGlobal*() calls: handlers are registered right here app.connectMicroservice<MicroserviceOptions>( { transport: Transport.TCP, options: { port: 4000 } }, { inheritAppConfig: true }, ); await app.listen(3000); // module init and lifecycle hooks first await app.startAllMicroservices(); // then start consuming messages ``` The rule that trips people up: a connected microservice registers its message handlers as soon as `connectMicroservice()` is called. A `useGlobal*()` call made after that point does not reach those handlers, even with `inheritAppConfig` set. Enhancers declared as `APP_*` providers are module providers rather than method calls, so this ordering rule concerns the `useGlobal*()` calls. ## Make the shared enhancers RPC-aware Sharing an HTTP enhancer with message handlers is only half the job, because enhancers written for HTTP make HTTP assumptions: - **Guards.** When a guard returns `false` for a message handler, Nest throws `RpcException('Forbidden resource')`, so the caller's `send()` errors with `{ status: 'error', message: 'Forbidden resource' }`. A guard that reads `context.switchToHttp().getRequest()` gets the wrong object for a message; branch on `context.getType()`, which returns `'rpc'` there, and read the message with `context.switchToRpc().getData()`. - **Pipes.** `ValidationPipe` throws `BadRequestException`, an `HttpException`. The RPC layer does not understand HTTP exceptions, so a message client receives `{ status: 'error', message: 'Internal server error' }`. An `exceptionFactory` on the shared global pipe would change the HTTP responses as well, so convert instead: a filter bound to the message controllers with `@Catch(HttpException)` can rethrow the details as an RPC error. - **Filters.** HTTP exception filters write to a response object that a message does not have; RPC filters implement `RpcExceptionFilter` and return an Observable. ## The startup-order trap The order of the last two calls matters. With `await app.startAllMicroservices()` first, the listeners begin consuming before module initialisation finishes, so a handler can receive a message before `onModuleInit()` or `onApplicationBootstrap()` has completed, for example before a cache is warm. Call `app.listen()`, or `app.init()` for an app without HTTP, before `startAllMicroservices()` when handlers must wait for a fully initialised application. ## Checklist | Symptom | Cause | Fix | |---|---|---| | Global pipes or guards skip message handlers | connected listener has its own empty config | `{ inheritAppConfig: true }` | | One `useGlobal*()` enhancer still skips them | called after `connectMicroservice()` | move the call earlier | | Validation failures arrive as "Internal server error" | `BadRequestException` is an HTTP exception | map it to an RPC error | | Handlers run before hooks finish | `startAllMicroservices()` called first | `listen()` or `init()` first |

  • Why does the order of app.listen() and app.startAllMicroservices() matter in a NestJS hybrid app?
    If `startAllMicroservices()` runs first, the listeners start consuming before module initialisation is complete, so a handler can receive a message before `onModuleInit()` or `onApplicationBootstrap()` has finished, such as before a cache is warmed. Calling `app.listen()`, or `app.init()` when there is no HTTP server, first makes the handlers wait for a fully initialised application.
  • With inheritAppConfig set, what does a NestJS message client see when a shared guard returns false?
    Nest throws `RpcException('Forbidden resource')` for the message handler, and the base RPC exception filter turns it into `{ status: 'error', message: 'Forbidden resource' }`, which is what the caller's `send()` Observable errors with. There is no 403 status: status codes belong to HTTP, so the client has to read the error object.
  • How do you run a NestJS app that listens on TCP and Redis at the same time?
    `createMicroservice()` supports only one server, so build a hybrid app with `NestFactory.create()` and call `connectMicroservice()` once per transporter, then `startAllMicroservices()`. Each call takes its own options and its own `inheritAppConfig` setting, and a handler can be bound to one listener by passing the transport as the second argument of `@MessagePattern()`.

  • Global pipes and guards set on the HTTP app automatically cover message handlers.
  • APP_GUARD providers reach connected microservices even without inheritAppConfig.
  • A useGlobalGuards() call made after connectMicroservice() still applies with inheritAppConfig.
  • A BadRequestException from ValidationPipe reaches a message client as a 400.
  • startAllMicroservices() always waits for onApplicationBootstrap() to finish first.