Nest or plain Express
TrapNest doesn't replace Express. It runs on top of Express by default, and can run on Fastify instead.
Asked in interviews
AskedHow is Nest.js different from plain Express?@Inject().@Roles() protects nothing until a guard reads it.TrapNest doesn't replace Express. It runs on top of Express by default, and can run on Fastify instead.
Asked in interviews
AskedHow is Nest.js different from plain Express?@Module()@Controller('users')@Injectable()List the class in providers@Module(), method like @Get(), parameter like @Body()tsconfig.jsonexperimentalDecorators emitDecoratorMetadata createParamDecorator() SetMetadata()Reflector.createDecorator() applyDecorators() Trap@Roles() only stores metadata. It protects nothing until a guard reads it through the Reflector.
@Global()Still register it once, usually in the root moduleTrap@Global() hides which module depends on which, so use it sparingly.
@Param('id')@Query('page')@Body()@Param('id', ParseIntPipe)TrapPath and query values always arrive as strings, whatever type the parameter declares.
Asked in interviews
AskedWhat is the difference between @Param(), @Query(), and @Body()?@HttpCode(204)The default is 200, or 201 for POSTNotFoundException HttpException@Res({ passthrough: true })Trap@Res() without passthrough turns off Nest's response handling, so interceptors stop working on that route.
Asked in interviews
AskedHow do you return different HTTP status codes in Nest.js?app.enableVersioning() URI is the default type. The others are HEADER, MEDIA_TYPE and CUSTOM@Version('2')VERSION_NEUTRALAsked in interviews
AskedHow do you implement API versioning?@Sse('stream')Return an Observable of MessageEventStreamableFileKeeps interceptors working, unlike @Res()TrapA plain @Get() that returns an Observable doesn't stream. Nest sends only the last value.
Asked in interviews
AskedHow do you implement streaming responses?FileInterceptor('file') @UploadedFile()FilesInterceptor('files', 10)@UploadedFiles() limits: { fileSize }ParseFilePipeTrapBy default, Multer keeps files in memory with no size limit, so always set limits. Use diskStorage() for big files.
Asked in interviews
AskedHow do you implement file upload in Nest.js?providers: [UserService]@Inject('CONFIG')TipTypeScript emits constructor parameter types as metadata. Nest reads it and looks up each token.
Asked in interviews
AskedHow does dependency injection work in Nest.js?useClassuseValueSuch as constants or a test mockuseFactoryinject: [ConfigService]useExistinguseFactory async. Nest delays startup until it resolvesTipA class with async methods is still a synchronous provider, because Nest creates the class at once.
Scope.DEFAULTScope.REQUESTScope.TRANSIENT@Injectable({ scope })TrapRequest scope bubbles up. A controller that injects a request-scoped service is rebuilt on every request too.
Asked in interviews
AskedWhat are the different scopes available for providers?providers, or import the module that exports itimportsMove it to providers. Only modules go in imports@Inject() with a custom token@Inject(forwardRef(() => PostService))Add it on both sides. Modules wrap the import the same wayTrapWith forwardRef() the creation order is indeterminate, so neither constructor may call the other.
register()forRoot()forRootAsync()forFeature()TipA static method builds a DynamicModule from the options the importing module passes in.
Asked in interviews
AskedWhat are dynamic modules in Nest.js?TrapOnly the lowest-level filter that catches an error handles it. The error never reaches another filter.
Asked in interviews
AskedWhat is the execution order of Nest.js components?NestMiddlewareconfigure()consumer.apply(MyMiddleware) .forRoutes('users') .exclude()TipNest middleware works like Express middleware, so most Express packages work too.
TrapIf middleware neither ends the response nor calls next(), the request is left hanging.
canActivate()Returns a boolean, Promise or Observable@UseGuards(AuthGuard) APP_GUARDapp.useGlobalGuards() can't inject servicesTipfalse sends 403, through Forbidden. To send 401, throw your own exception.
Asked in interviews
AskedHow do guards work in Nest.js?next.handle()It returns an RxJS Observable of the resultmap()catchError()handle()finalize()It runs on success and on failureTrapA tap() with only a value callback skips requests that throw.
timeout(3000)The RxJS operator, in an interceptor408 on a timeoutRequestTimeoutException TrapA timeout ends the response, not the work. A pending query keeps running unless you cancel it.
Asked in interviews
AskedHow do you implement request timeouts?switchToHttp()switchToWs()switchToRpc()getHandler()getClass()TipOne guard can work across HTTP, WebSockets and microservices. getType() says which one is running.
Asked in interviews
AskedWhat is the purpose of ExecutionContext?@IsEmail()@Min(18)new ValidationPipe() A bad body gets 400whitelist: true400forbidNonWhitelisted: truetransform: trueIt also converts path and query stringsStandardSchemaValidationPipe TrapUse a class, not an interface. Interfaces vanish at compile time, and pipes need a real class at runtime.
ParseIntPipeParseBoolPipePipeTransformtransform() returns the value, or throws so the handler never runsplainToInstance() validate()TipValidationPipe already does this, so write your own only for a rule it can't express.
extends HttpException500 with "Internal server error", so internal details don't leak@Catch(HttpException) @Catch()@UseFilters()Trapapp. runs outside any module, so its filter can't inject anything. Register it as APP_FILTER instead.
JwtServiceAuthGuard('jwt') validate() fills req.user@nestjs/authentication Sessions, password hashing, access and refresh tokensTrapNever hard-code the JWT secret. Load it from configuration.
Asked in interviews
AskedHow do you implement authentication in Nest.js?@Roles(['admin'])getAllAndOverride() Handler first, then controller@nestjs/authorization TipRegister it as APP_GUARD after the authentication guard, so request.user is already set.
TrapA role check can't see the record a request touches. Check "only your own orders" in the service or a policy.
Asked in interviews
AskedHow do you implement role-based access control with guards in Nest.js?ThrottlerModule.forRoot() ThrottlerGuard@Throttle()@SkipThrottle()TipWithout the guard, nothing is limited. A client over the limit gets 429.
TrapThe built-in store counts in one process. With several instances, use a shared store such as Redis.
Asked in interviews
AskedHow do you implement rate limiting in Nest.js?app.use(helmet()) app.useSecurityHeaders() app.enableCsrfProtection() app.enableCors() TipAgainst cross-site scripting, encode output. Filters that strip tags are easy to bypass.
Asked in interviews
AskedWhat are some common security practices in Nest.js?TypeOrmModule.forRoot() TypeOrmModule.forRootAsync() TypeOrmModule.forFeature() @InjectRepository(User) TrapTurn synchronize off in production. It changes the schema on every start and can lose data. Use migrations.
Asked in interviews
AskedHow do you connect to a database in Nest.js?dataSource.transaction() createQueryRunner() Release it in finallyTrapAn injected repository runs on another connection, so its writes escape the transaction. Use the transaction's manager.
Asked in interviews
AskedHow do you implement database transactions?.env for all modulesConfigModule.forRoot() isGlobal: trueconfig.get('KEY') config.getOrThrow('KEY') validationSchema TrapWhen a key is in the real environment and in .env, the environment value wins.
Asked in interviews
AskedHow do you handle configuration in Nest.js?CacheModule.register() ttl is in millisecondsCacheInterceptor @CacheKey()@CacheTTL()@Inject(CACHE_MANAGER) TipCache caches only GET routes by default, and routes that inject @Res() can't use it.
TrapThe cache lives in one process by default. With several instances, use Redis through a Keyv adapter.
Asked in interviews
AskedHow do you implement caching in Nest.js?Test.createTestingModule() .compile(){ provide: Dep, useValue }getRepositoryToken(User) vi.fn()Vitest. CommonJS projects get jest.fn()Asked in interviews
AskedHow do you implement unit testing in Nest.js?createNestApplication() request(app.getHttpServer()) overrideProvider(Dep) overrideGuard(AuthGuard) useMocker()TrapUse resolve(), not get(), for request-scoped and transient providers.
Asked in interviews
AskedWhat are the testing utilities provided by Nest.js?app.enableShutdownHooks() TrapSignal handling is off by default. Without it, a container that gets SIGTERM stops without closing its connections.
Asked in interviews
AskedWhat is the lifecycle of a Nest.js application?new FastifyAdapter() app.listen(3000, '0.0.0.0')The default is localhost only@Req() or @Res() codeTrapIf most request time goes to the database, a faster HTTP layer changes little. Measure first.
Asked in interviews
AskedWhen would you switch Nest.js from the Express adapter to Fastify?N+1 queries, and size the connection poolapp.use(compression()) On busy sites, let Nginx do itTipMeasure with real traffic before you change anything, so you fix the slowest part first.
Asked in interviews
AskedWhat are the performance optimization techniques in Nest.js?DocumentBuilderSwaggerModule.setup() @ApiProperty()@ApiProperty() callsEnable the Swagger CLI plugin in nest-cli.jsonTrapTypeScript leaves no metadata for undecorated properties, so a DTO property needs @ApiProperty() to show up.
Asked in interviews
AskedHow do you generate API documentation in Nest.js?HealthCheckService.check() HttpHealthIndicator TypeOrmHealthIndicator HealthIndicatorService NestJS 12 removed the HealthIndicator base classTipAll up returns 200. One failure returns 503 and names the failing check.
TrapPoint the liveness probe at a light check, so a slow downstream service doesn't get a healthy instance restarted.
Asked in interviews
AskedHow do you implement health checks in Nest.js?@WebSocketGateway() @SubscribeMessage('msg') @WebSocketServer() this.server.emit() TipThe value a handler returns goes back to the sender as an acknowledgment.
TrapSeveral Socket.IO instances need the Redis adapter, plus sticky sessions or clients that skip HTTP polling.
Asked in interviews
AskedHow do you implement WebSocket communication?NestFactory.createMicroservice() Over TCP, Redis or Kafka. Handlers don't change@MessagePattern() The client calls send()@EventPattern()The client calls emit(), which publishes at onceTrapsend() returns a cold Observable, so nothing is sent until something subscribes.
Asked in interviews
AskedWhat are microservices in Nest.js?Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in