NestJS interview questions
10 questions with answers. 56 open jobs in India ask for NestJS.
What's the difference between Interceptor vs Middleware vs Filter in Nest.js?
As you already implied with your question, all three are very similar concepts and in a lot of cases it is hard to decide and comes down to your preferences. But I can give an overview of the differences:
Interceptors
Interceptors have access to response/request before and after the route handler is called.
Registration
- Directly in the controller class with
@UseInterceptors()controller- or method-scoped - Globally with
app.useGlobalInterceptors()inmain.ts
Examples
- LoggingInterceptor: Request before route handler and afterwards its result. Meassure time it takes.
- ResultMapping: Transform
nullto[]or wrap result in a response object:users->{users: users}
Conclusion
I like that the registration is closer to the route handlers compared to middleware. But there are some limitations, for example, you cannot set the response code or alter the response with Interceptors when you send the
responsewith the library-specific@Res()object in your route handler, see docs.Middleware
Middleware is called only before the route handler is called. You have access to the response object, but you don't have the result of the route handler. They are basically express middleware functions.
Registration
- In the module, very flexible way of choosing relevant routes (with wildcards, by method,...)
- Globally with
app.use()inmain.ts
Examples
- FrontendMiddleware: redirect all routes except API to
index.html, see this thread - You can use any express middleware that is out there. There are lots of libraries, e.g.
body-parserormorgan
Conclusion
The registration of middleware is very flexible, for example: apply to all routes but one etc. But since they are registered in the module, you might not realize it applies to your controller when you're looking at its methods. It's also great that you can make use of all the express middleware libraries that are out there.
Exception Filters
Exception Filters are called after the route handler and after the interceptors. They are the last place to make changes before a response goes out.
Registration
- Directly in the controller class with
@UseFilters()controller- or method-scoped - Globally
app.useGlobalFilters()in yourmain.ts
Examples
- UnauthorizedFilter: Map to an easy to understand message for the user
- NotFoundFilter: Map all routes that are not found (not part of your api) to your
index.html.
Conclusion
The basic use case for exception filters are giving understandable error messages (hiding technical details). But there are also other creative ways of usage: When you serve a single page application, then typically all routes should redirect to
So the execution order is:index.htmlexcept the routes of your API. Here, you can redirect on aNotFoundException. Some might find this clever others hacky. Your choice. ;-)Middleware -> Interceptors -> Route Handler -> Interceptors -> Exception Filter (if exception is thrown)
With all three of them, you can inject other dependencies (like services,...) in their constructor.
From Stack Overflow: asked by Bill, answered by Kim Kern (CC BY-SA 4.0)
- Directly in the controller class with
What's the difference between tsc (TypeScript compiler) and ts-node?
The main difference is that
tsctranspile all the file according to your tsconfig.Instead,
ts-nodewill start from the entry file and transpile the file step by step through the tree based on the import/export.From Stack Overflow: asked by gremo, answered by Adrien De Peretti (CC BY-SA 4.0)
nestjs vs plain express performance
UPDATE - 17.03.2020
We are now running benchmarks for every new PR. One of the latest benchmarks can be found here: https://github.com/nestjs/nest/runs/11029354661
Req/sec Trans/sec Nest-Express 15370 3.17MB Nest-Fastify 30001 4.38MB Express 17208 3.53MB Fastify 33578 4.87MBThat means Nest +
FastifyAdapteris now almost 2 times faster than express.UPDATE - 22.09.2018
Benchmarks directory has been added to the repository: https://github.com/nestjs/nest/blob/master/benchmarks/all_output.txt (you can run benchmarks on your machine as well).
UPDATE - 24.06.2018
Nest
v5.0.0supports fastify. Fastify + Nest integration is even more performant than plain(!) express.The following list shows what Nest is doing in comparison to plain express route handler:
- it surrounds your route handler body with try..catch blocks
- it makes every route handler
async - it creates a global express router
- it creates a separated router for each controller
- it binds error-handling middleware
- it binds
body-parsermiddleware (bothjsonand extendedurlencoded)
All of the mentioned things reflect a real-world example (probably 99.9% express apps have to do this as well, it's unavoidable). It means that if you want to compare Express and Nest performance, you should at least cover above points. The comparison with the example below:
app.get('/', (req, res, next) => res.status(200).send('Hello world'));Is unfair in this case, because it's not enough. When I cover these points, this is what I received (express 4.16.2):
Running 10s test @ http://localhost:3000 1024 connections Stat Avg Stdev Max Latency (ms) 225.67 109.97 762 Req/Sec 4560 1034.78 5335 Bytes/Sec 990 kB 226 kB 1.18 MB 46k requests in 10s, 9.8 MB readAdditionally, Nest has to:
- recognize whether a result is a Promise/Observable/plain value
- based on the result type, use
send()orjson()(+1 condition) - add 3 conditions (
ifstatements) to check pipes, interceptors and guards
There's an output for Nest (4.5.8):
Running 10s test @ http://localhost:3000 1024 connections Stat Avg Stdev Max Latency (ms) 297.79 55.5 593 Req/Sec 3433.2 367.84 3649 Bytes/Sec 740 kB 81.9 kB 819 kB 34k requests in 10s, 7.41 MB readThis implies that Nest performance is around 79% express (-21%). This is due to the reasons set out above, and moreover, because Nest is compatible with Node 6.11.x which means that it can't use async/await under the hood - it has to use generators.
Which conclusion is to be drawn based on those stats? None, because we aren't used to creating applications that only returns plain strings without any asynchronous stuff. The comparisons with
Hello worldmeans nothing, it's only a titbit :)PS. I used
autocannonlibrary https://github.com/mcollina/autocannonautocannon -c 1024 -t30 http://localhost:3000From Stack Overflow: asked by Shadowfax, answered by Kamil Myśliwiec (CC BY-SA 4.0)
Why do we need DTOs and interfaces both in NestJS?
According to the Nestjs docs:
But first (if you use TypeScript), we need to determine the DTO (Data Transfer Object) schema. A DTO is an object that defines how the data will be sent over the network. We could determine the DTO schema by using TypeScript interfaces, or by simple classes. Interestingly, we recommend using classes here. Why? Classes are part of the JavaScript ES6 standard, and therefore they are preserved as real entities in the compiled JavaScript. On the other hand, since TypeScript interfaces are removed during the transpilation, Nest can't refer to them at runtime. This is important because features such as Pipes enable additional possibilities when they have access to the metatype of the variable at runtime.
From Stack Overflow: asked by Ajitabh, answered by user5997038 (CC BY-SA 4.0)
Is there a recommended way to update NestJS?
You can use the Nest CLI to update the dependencies:
$ npm install -g @nestjs/cli $ nest updateYou can also
$ nest uAs Mick mentioned in his comment, you might have to add
--forceargument.nest update --forceUpdate - July 7 2022
Since v9.0.0 release, the command
updatewas removed. To upgrade your dependencies, you can use dedicated tools like ncu, npm update, yarn upgrade-interactive, etc.From Stack Overflow: asked by Robel Robel Lingstuyl, answered by Matt Walterspieler (CC BY-SA 4.0)
Is it possible to set default values for a DTO?
You can set default directly in your DTO class:
export class MyQuery { readonly myQueryItem = 'mydefault'; }You have to instantiate the class so that the default value is used. For that you can for example use the
ValidationPipewith the optiontransform: true. If the value is set by your query params it will be overriden.@Get() @UsePipes(new ValidationPipe({ transform: true })) getHello(@Query() query: MyQuery) { return query; }Why does this work?
1) Pipes are applied to all your decorators, e.g.
@Body(),@Param(),@Query()and can transform the values (e.g.ParseIntPipe) or perform checks (e.g.ValidationPipe).2) The
ValidationPipeinternally usesclass-validatorandclass-transformerfor validation. To be able to perform validation on your input (plain javascript objects) it first has to transform them to your annotated dto class meaning it creates an instance of your class. With the settingtransform: trueit will automatically create an instance of your dto class.Example (basically how it works):
class Person { firstname: string; lastname?: string = 'May'; constructor(person) { Object.assign(this, person); } } // You can use Person as a type for a plain object -> no default value const personInput: Person = { firstname: 'Yuna' }; // When an actual instance of the class is created, it uses the default value const personInstance: Person = new Person(personInput);From Stack Overflow: asked by papillon, answered by Kim Kern (CC BY-SA 4.0)
Inject nestjs service from another module
You have to export the
ItemsServicein the module that provides it:@Module({ controllers: [ItemsController], providers: [ItemsService], exports: [ItemsService] ^^^^^^^^^^^^^^^^^^^^^^^ }) export class ItemsModule {}and then import the exporting module in the module that uses the service:
@Module({ controllers: [PlayersController], providers: [PlayersService], imports: [ItemsModule] ^^^^^^^^^^^^^^^^^^^^^^ }) export class PlayersModule {}⚠️ Don't add the same provider to multiple modules. Export the provider, import the module. ⚠️
From Stack Overflow: asked by Fairydhwen, answered by Kim Kern (CC BY-SA 4.0)
How to use query parameters in Nest.js?
Query parameters
You have to remove
:paramsfor it to work as expected:@Get('findByFilter') async findByFilter(@Query() query): Promise<Article[]> { // ... }Path parameters
The
:paramsyntax is for path parameters and matches any string on a path:@Get('products/:id') getProduct(@Param('id') id) {matches the routes
localhost:3000/products/1 localhost:3000/products/2abc // ...Route wildcards
To match multiple endpoints to the same method you can use route wildcards:
@Get('other|te*st')will match
localhost:3000/other localhost:3000/test localhost:3000/te123st // ...From Stack Overflow: asked by Eve-Sama, answered by Kim Kern (CC BY-SA 4.0)
NestJS - How to use .env variables in main app module file for database connection
1. Keeping using ConfigModule
You need to set
NODE_ENVin npm scripts so that it can be used to load an env file based on the env."scripts": { "start:local": "NODE_ENV=local npm run start" "start:dev": "NODE_ENV=dev npm run start" }Now you can just use the
ConfigModule:@Module({ imports: [ ConfigModule.forRoot({ envFilePath: `${process.env.NODE_ENV}.env` }), MongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' }) ... })2. Using
dotenvnpm install dotenvAdd some scripts to your
package.jsonto set what env you are in."scripts": { ... "start:local": "NODE_ENV=local npm run start" "start:dev": "NODE_ENV=dev npm run start" }Import
dotenvinmain.tsfile. Make sure you do it at the top of the file.require('dotenv').config({ path: `../${process.env.NODE_ENV}.env` });3. Using
env-cmdYou can use
env-cmdnpm package.npm install env-cmdAnd add some commands for different envs in
package.json, for example:"scripts": { ... "start:local": "env-cmd -f local.env npm run start" "start:dev": "env-cmd -f dev.env npm run start" } ...Now you can use the env variables, for example:
MongooseModule.forRoot(`mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@myhost.net?retryWrites=true&w=majority&db=dbname`, { useNewUrlParser: true, dbName: 'dbname' })process.env.MONGO_CONNECTION_STRINGUpdate:
To overcome the env set command problem in different platforms, you can install
cross-envpackage.npm install -D cross-envAnd update the scripts:
"scripts": { "start:local": "cross-env NODE_ENV=local npm run start" "start:dev": "cross-env NODE_ENV=dev npm run start" }From Stack Overflow: asked by Mohit Bhardwaj, answered by andsilver (CC BY-SA 4.0)
Class-validator - validate array of objects
Add
@Type(() => AuthParam)to your array and it should be working.Typedecorator is required for nested objects(arrays). Your code becomesimport { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator'; import { AuthParam } from './authParam.model'; import { Type } from 'class-transformer'; export class SignInModel { @IsArray() @ValidateNested({ each: true }) @ArrayMinSize(2) @ArrayMaxSize(2) @Type(() => AuthParam) authParameters: AuthParam[]; }Be careful if you are using any exception filter to modify the error reponse. Make sure you understand the structure of the class-validator errors.
From Stack Overflow: asked by bensiu, answered by Yousef khan (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA10 questions