All topics

NestJS interview questions

10 questions with answers. 56 open jobs in India ask for NestJS.

  1. 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() in main.ts

    Examples

    • LoggingInterceptor: Request before route handler and afterwards its result. Meassure time it takes.
    • ResultMapping: Transform null to [] 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 response with 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() in main.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-parser or morgan

    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 your main.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 index.html except the routes of your API. Here, you can redirect on a NotFoundException. Some might find this clever others hacky. Your choice. ;-)

    So the execution order is:

    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)

  2. What's the difference between tsc (TypeScript compiler) and ts-node?

    The main difference is that tsc transpile all the file according to your tsconfig.

    Instead, ts-node will 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)

  3. 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.87MB      
    

    That means Nest + FastifyAdapter is 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.0 supports 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-parser middleware (both json and extended urlencoded)

    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 read
    

    Additionally, Nest has to:

    • recognize whether a result is a Promise/Observable/plain value
    • based on the result type, use send() or json() (+1 condition)
    • add 3 conditions (if statements) 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 read
    

    This 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 world means nothing, it's only a titbit :)

    PS. I used autocannon library https://github.com/mcollina/autocannon

    autocannon -c 1024 -t30 http://localhost:3000

    From Stack Overflow: asked by Shadowfax, answered by Kamil Myśliwiec (CC BY-SA 4.0)

  4. 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)

  5. Is there a recommended way to update NestJS?

    You can use the Nest CLI to update the dependencies:

    $ npm install -g @nestjs/cli
    $ nest update
    

    You can also $ nest u

    As Mick mentioned in his comment, you might have to add --force argument.

    nest update --force
    

    Update - July 7 2022

    Since v9.0.0 release, the command update was 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)

  6. 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 ValidationPipe with the option transform: 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 ValidationPipe internally uses class-validator and class-transformer for 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 setting transform: true it 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)

  7. Inject nestjs service from another module

    You have to export the ItemsService in 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)

  8. How to use query parameters in Nest.js?

    Query parameters

    You have to remove :params for it to work as expected:

    @Get('findByFilter')
    async findByFilter(@Query() query): Promise<Article[]> {
      // ...
    }
    

    Path parameters

    The :param syntax 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)

  9. NestJS - How to use .env variables in main app module file for database connection

    1. Keeping using ConfigModule

    You need to set NODE_ENV in 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 dotenv

    npm install dotenv
    

    Add some scripts to your package.json to set what env you are in.

    "scripts": {
      ...
      "start:local": "NODE_ENV=local npm run start"
      "start:dev": "NODE_ENV=dev npm run start"
    }
    

    Import dotenv in main.ts file. Make sure you do it at the top of the file.

    require('dotenv').config({ path: `../${process.env.NODE_ENV}.env` });
    

    3. Using env-cmd

    You can use env-cmd npm package.

    npm install env-cmd
    

    And 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_STRING

    Update:

    To overcome the env set command problem in different platforms, you can install cross-env package.

    npm install -D cross-env
    

    And 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)

  10. Class-validator - validate array of objects

    Add @Type(() => AuthParam) to your array and it should be working. Type decorator is required for nested objects(arrays). Your code becomes

    import { 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.