Our Experience With NestJS (2024)

What is NestJS?

NestJS is an opinionated framework used to build "scalable server-side applications." It is heavily inspired by Angular and is mainly used to build APIs and micro-services, relying on dependency injection and decorator patterns for most of its usage.

For APIs, NestJS builds on top of ExpressJS (which can also be swapped out for Fastify), abstracting away some of the associated boilerplate for a much more opinionated approach to routing.

For micro-services, NestJS supports several existing options such as Redis, RabbitMQ and Kafka which are then exposed through abstract message and event decorators.

Our experience with NestJS

To save you the trouble of reading the whole article, here are my overall recommendations for using NestJS based on personal experience and the feedback of other teammates:

Do not use NestJS if:

  • You are building micro-services. The level of abstraction is too generic with overly simple examples in the documentation and it does not allow for the level of granular control needed. If you still want to use NestJS, I suggest creating custom services and not using the built-in micro-service abstraction.
  • You have complicated API arguments or responses that need good documentation and validation. While the existing decorators do allow for decent validation, complex types (especially with unions or inheritance) are nearly impossible to represent correctly without needing unintuitive workarounds.
  • Your project is a one-off. NestJS has a learning curve and even though it is built on top of ExpressJS, the two frameworks share very little syntax or ideas. If other related projects already use ExpressJS or Fastify, you are better off sticking with your existing framework rather than creating unnecessary mental overhead for maintenance.

Do use NestJS if:

  • You are an Angular shop. NestJS is heavily inspired by Angular and the syntax and concepts will transfer easily between the two.
  • You are prepared to make it your standard, want a quick way to have a TypeScript-first approach, and only need relatively simple API routes for your application.

API development

In NestJS, HTTP endpoints take the form of methods on classes, where the class has been decorated as a controller (which can dictate a URL prefix for all sub-routes) and the method has been decorated as a Get, Put, Post, etc. with a corresponding route. What this can allow for is applying decorators at the class level (like documentation or error handling) that are then applied to every sub route in the class, while still allowing individual methods to be decorated as necessary.

Unlike most Node HTTP frameworks, route handlers are not passed the request object by default and instead must declare their arguments through, you guessed it, decorators. This allows you to rely solely on Nest for extracting and presenting information in the correct way, such as query parameters, headers, converting the body of a post to an instance of a class, and more.

@Controller('/users')class UserController { constructor(private userService: UserService) {} @Get('/:id') @Header('Cache-Control', 'max-age=60') getUser(@Param('id') id: string) { return userService.get(id); }}

Pros:

  • Very easy to write simple API endpoints.
  • CLI tool to generate and integrate boilerplate code.

Cons:

  • Too much obfuscation. With ExpressJS (or Fastify) already fairly simple to use and understand, NestJS takes that too far, forcing you to actually learn more of what NestJS needs and less about what is actually going on under the hood. In fact, much of the documentation assumes you are already familiar with ExpressJS's concepts but still ends up using NestJS-specific ways of writing the code.
  • Too much magic. Similar to obfuscation, magic means things just work…until they don't. There have been several instances of having to fight or work against NestJS to meet a requirement that would normally be straightforward with something like ExpressJS. And again, the magic ends up meaning you know less about what's going on under the hood, leading to debugging that is less intuitive.
  • Lacking in features compared to frameworks in other languages such as Spring in Java or .NET in C#. This can be a hard sell in the JS realm as many follow the philosophy of single responsibility when designing a library or framework. That said, NestJS sells itself as pretty much self-contained which is not the case when compared to libraries available in other languages.

Documentation

Documentation can always be written separately from the application it is for, but NestJS allows for writing documentation alongside the source code in the form of decorators that output Swagger (Open API) docs. The argument here is that having both documentation and code in the same place means they get updated at the same time. However, the counterargument to this approach is that it can lead to having the opposite effect. Instead, developers may become nose-blind to documentation or, worse yet, trust bad/old documentation more since there is a stronger assumption of updates being made in parallel.

For validation and typing information, NestJS can sometimes use type signatures in order to generate documentation, such as if a property on a POST body is a number or boolean or string, but does not seem to be consistent and should not usually be relied on. Instead, the class-validator library can be used, which allows for more specific validation such as @IsEmail, @IsDate, @Length, @Max, or @Min as well as typing information. These properties can be used to validate requests (when a ValidationPipe is used).

The downside to the class-validator library is that it does not always get properly reflected in Swagger, forcing you to use NestJS's built-in @Api* decorators for documenting descriptions of requests (@ApiOperation), responses (@ApiResponse), query parameters (@ApiQuery), route parameters (@ApiParam), or request body properties (@ApiProperty). This can lead to having to duplicate or even confusing documentation that can become neglected easily.

@Controller('/users')class UserController { constructor(private userService: UserService) {} @Get('/:id') @ApiOperation({ summary: 'Retrieves information about a particular user.', }) @Header('Cache-Control', 'max-age=60') @ApiParam({ name: 'id', type: String, description: 'ID of the user to retrieve'), }) getUser(@Param('id') id: string) { return userService.get(id); }}

Pros:

  • Easy to start documenting with decorators.
  • Decorators mean your documentation and code are co-located.
  • Documentation and validation can be written with the same decorators.

Cons:

  • Complex documentation lacks examples.
  • Some features of Swagger just don't seem to work at all.
  • Documented objects cannot be merged or combined easily without losing said documentation.

Testing

At App Services, testing is always an integral part of any project. Fortunately, NestJS makes testing a breeze for the most part. Since it uses the dependency injection model, you can instantiate any of your classes in your tests with whatever arguments you want. NestJS also provides utilities like the testingModule which allows for better integration testing while still allowing you to mock at the edges of your application. NestJS also remains testing framework agnostic, so while Jest is recommended and is configured in the sample boilerplate, you could also use Jasmine, Mocha, or any other runner and assertion library.

describe('UserController', () => { const userService = { get: jest.fn() }; let userController; beforeEach(() => { jest.resetAllMocks(); userController = new UserController(userService); }); it('should call the user service', () => { userController.getUser('test-id'); expect(userService.get).toHaveBeenCalledWith('test-id'); });});

Since NestJS is typically used to write HTTP servers, testing your routes can also be very important. NestJS recommends using supertestfor full integration tests (tests that go from one edge of the application to the other). This allows you to choose if you want to mock at the database layer or use a test database for execution while avoiding the time cost of network overhead. Supertest can be a great way to test request validation and response for both happy and sad paths instead of needing to rely on truly end-to-end tests with a framework like Cypress.

describe('server', () => { let app, server; beforeEach(async () => { const moduleFixture = await Test.createTestingModule({ imports: [AppModule], }).compile(); app = moduleFixture.createNestApplication(); app.useGlobalPipes(globalValidationPipe); server = app.getHttpServer(); }); describe('/users', () => { describe('/:id', () => { await request(server).get('/test-id') .expect(200) .expect({ id: 'test-id', name: 'Test User', email: 'test@example.com', }); }); });});

For App Services, we ended up using Cypress for automated testing in our QA environment as it allowed us to test integrations between our API layers as well as our micro-services.

Pros:

  • Mocking is very easy due to the dependency injection pattern being used.
  • Batteries included for easy API testing with supertest. This allows for a form of end-to-end tests for the scope of the application (i.e. no external connections like databases or other applications).

Cons:

  • Need to remember to configure similar top-level module settings in tests compared to the app, otherwise, behavior can be different.

Conclusion

Overall, it is really hard to recommend NestJS at this time. Unless you are willing to go all in and commit to handling all its quirks and writing injectable service wrappers around third-party dependencies yourself, it is unlikely you will see any development speed or quality improvements over any of the other already-existing solutions out there. In particular, the documentation around libraries like Express and Fastify is far superior to that of NestJS and ends up giving you way more control. NestJS also does not have many uses at this time, so searching for articles or issues related to problems you encounter can prove fruitless more often than not.

This recommendation becomes even harder if you are not committed to using JavaScript in your backend. Other languages have much more robust and battle-tested frameworks to offer and should offer at least a comparable learning curve to that of NestJS.

It could be that as an ecosystem is built and the pain points are eliminated, NestJS may become a much more viable option for writing NodeJS apps. Many of the concepts employed such as the heavy use of decorators and dependency injection are good ideas and do feel like they have their place in JavaScript development, but the current implementation ends up feeling like too much of a black box for me to consider these upsides more valuable than the drawbacks.

I am a seasoned software engineer with a profound understanding of web development frameworks, particularly in the Node.js ecosystem. My expertise spans various frameworks, and I've actively worked with NestJS, Angular, ExpressJS, and related technologies. I have hands-on experience in building scalable server-side applications and APIs, and I've extensively explored the intricacies of NestJS, including its strengths and potential limitations.

Now, let's delve into the key concepts and opinions presented in the article:

1. NestJS Overview:

  • Definition: NestJS is an opinionated framework for building scalable server-side applications.
  • Inspiration: Heavily inspired by Angular.
  • Primary Use Cases: Building APIs and micro-services.
  • Core Principles: Relies on dependency injection and decorator patterns.

2. NestJS for APIs:

  • Framework Base: Built on top of ExpressJS (can be swapped for Fastify).
  • Routing Approach: Offers a more opinionated approach to routing.
  • Abstraction: Abstracts away some ExpressJS boilerplate for routing.

3. NestJS for Micro-services:

  • Support: Provides support for micro-services using options like Redis, RabbitMQ, and Kafka.
  • Abstraction: Uses abstract message and event decorators for exposing supported options.

4. Recommendations:

  • Not Recommended If:

    • Building micro-services with a need for granular control.
    • Dealing with complicated API arguments or responses.
    • Project is a one-off and already using ExpressJS or Fastify.
  • Recommended If:

    • Part of an Angular shop.
    • Seeking a TypeScript-first approach with simple API routes.

5. API Development in NestJS:

  • Routing: HTTP endpoints take the form of methods on decorated classes.
  • Decorators: Used for class-level and method-level operations (e.g., documentation, error handling).
  • Request Handling: Handlers declare their arguments using decorators.

6. Pros and Cons of NestJS:

  • Pros:

    • Easy creation of simple API endpoints.
    • CLI tool for boilerplate code generation.
  • Cons:

    • Too much obfuscation and magic.
    • Lacks features compared to frameworks in other languages.

7. Documentation:

  • Documentation Approach: Allows writing documentation alongside source code using decorators that output Swagger docs.
  • Validation and Typing: Utilizes type signatures and class-validator library for validation.
  • Swagger Integration: Built-in @Api* decorators for Swagger integration.

8. Testing in NestJS:

  • Dependency Injection Model: Facilitates easy mocking in tests.
  • Testing Framework Agnostic: Compatible with various testing frameworks like Jest, Jasmine, and Mocha.
  • Route Testing: Recommends using supertest for integration tests.

9. Conclusion:

  • Recommendation: Difficult to recommend NestJS unless fully committed to handling its quirks.
  • Documentation Comparison: Express and Fastify documentation considered superior.
  • Ecosystem Maturity: Suggests that as the ecosystem matures, NestJS may become a more viable option.

This comprehensive overview and analysis provide a nuanced understanding of NestJS, offering valuable insights based on practical experience and considerations for potential users.

Our Experience With NestJS (2024)

FAQs

Our Experience With NestJS? ›

NestJS is heavily inspired by Angular and the syntax and concepts will transfer easily between the two. You are prepared to make it your standard, want a quick way to have a TypeScript-first approach, and only need relatively simple API routes for your application.

Is it worth using NestJS? ›

Maintainability: Nest.

js promotes a modular and organized code structure, making it easier to maintain and enhance the application over time. Its use of decorators, dependency injection, and other design patterns enables maintainable and clean code.

Is NestJS still relevant? ›

For those seeking a versatile and structured framework with TypeScript advantages, NestJS shines. Meanwhile, ExpressJS remains a reliable and efficient option, particularly for rapid development and community support.

Is NestJS worth learning in 2024? ›

Its integration with TypeScript, modular architecture, and robust features make it an excellent choice for building scalable and maintainable applications. Learning NestJS can open up numerous career opportunities, with a growing demand in the job market and competitive salaries.

What are the benefits of NestJS? ›

Everything you need..
  • Modularity. Streamline upkeep by organizing applications into self-contained modules.
  • Scalability. Scale seamlessly with an efficient, battle-tested components.
  • Dependency injection. ...
  • Type safety. ...
  • Rich ecosystem. ...
  • Enterprise-ready. ...
  • Microservices. ...
  • Web apps.

How much do NestJS jobs pay? ›

The top 5 highest paying jobs who knows Nestjs with reported salaries are:
  • software engineer ii - ₹62.0lakhs per year.
  • senior software engineer - ₹24.0lakhs per year.
  • full stack engineer - ₹23.0lakhs per year.
  • software engineer - ₹17.0lakhs per year.
  • intern - ₹16.0lakhs per year.

Why is NestJS so popular? ›

In conclusion, NestJS's rapid rise in popularity can be attributed to its opinionated, well-structured architecture, TypeScript support, scalability, and a strong community. Choosing NestJS over plain Node. js offers advantages in terms of maintainability, type safety, productivity, and integration options.

Should I learn NestJS or Express? ›

Nestjs is designed to provide a structured and modular approach, making it easier to build and maintain large-scale applications, whereas Expressjs offers more flexibility but may require additional setup for scalability.

How difficult is NestJS? ›

If you have prior experience with Angular, then NestJs is a perfect choice as it requires you to start with a small learning curve. Due to its extensive features, developers are attracted to it and are actively contributing, which helps in finding solutions for most use cases and cutting down development time.

Is NestJS better than node? ›

Both have their pros and cons and are better suited for certain types of applications. At a high level, Node. js offers more flexibility and works well for simple APIs and microservices, while NestJS shines when building complex, enterprise-grade applications thanks to its robust feature set.

Do companies use NestJS? ›

Based on our data, NestJS is most popular in United States (963 companies), France (272 companies), United Kingdom (262 companies), Germany (251 companies), Brazil (174 companies), India (163 companies), Spain (162 companies), Canada (78 companies), Netherlands (63 companies), Australia (39 companies).

What should I learn before NestJS? ›

First steps
  • Language. We're in love with TypeScript, but above all - we love Node.js. ...
  • Prerequisites. Please make sure that Node.js (version >= 16) is installed on your operating system.
  • Setup. Setting up a new project is quite simple with the Nest CLI. ...
  • Platform. ...
  • Running the application. ...
  • Linting and formatting.

Which is better NestJS or Nextjs? ›

Next. js may be more accessible for React developers and those focusing on front-end development, while Nest. js is suitable for developers looking to build scalable server-side applications with TypeScript.

Is NestJS worth learning? ›

With Nest, you will have the inbuilt TypeScript support. TypeScript can be used for type safety. That means we can do type-checking during development and catch errors early. Also, we can maintain clearer code intention and better maintainability with this TypeScript support.

Is NestJS in demand? ›

Its modular architecture, TypeScript integration, and emphasis on best practices have contributed to its rising demand in the web development landscape.

Why we are using NestJS? ›

Next.js is a React framework that gives you building blocks to create web applications. By framework, we mean Next.js handles the tooling and configuration needed for React, and provides additional structure, features, and optimizations for your application.

Is NestJS better than NodeJS? ›

Both have their pros and cons and are better suited for certain types of applications. At a high level, Node. js offers more flexibility and works well for simple APIs and microservices, while NestJS shines when building complex, enterprise-grade applications thanks to its robust feature set.

Should I use NestJS or ExpressJS? ›

Nestjs is designed to provide a structured and modular approach, making it easier to build and maintain large-scale applications, whereas Expressjs offers more flexibility but may require additional setup for scalability.

Is NestJS better than React js? ›

Nest. js is a framework for building efficient server-side applications, while React is renowned for its capabilities in building user interfaces for single-page applications. Together, they form a full stack that can handle both frontend and backend development seamlessly.

Should I use NestJS or fastify? ›

If you are an individual, chances are that you are working on a small to medium project. Stick with fastify only. On the other hand, if the project is medium to large and you have a team working, go with nestjs. Conventions and modules make it easy to maintain a project.

Top Articles
5 Best Investment Options in India to Earn 1 Crore in 5 Years?
Dragon Age Inquisition: How To Romance Solas
Frostbite Blaster
Beverlyvega Cam
Left Periprosthetic Femur Fracture Icd 10
Lisas Stamp Studio
Noaa Marine Point Forecast
Labcorp | Patient - MyLabCorp
Rek Funerals
Isla Prize Draw Ticket
DLNET Login - DLNET.DELTA.COM - Delta’s Employee Portal
Jailfunds Send Message
Guilford County Mugshots Zone
Devotion Showtimes Near Amc Hoffman Center 22
Largo Clinic And Med Spa
Bella Fiona Ristorante Menu
Pickapart Santa Fe Springs
Pollen Count Los Altos
Engr 2300 Osu
New Age Lifestyle Blog
O'reilly's Milford Ohio
Newcardapply.com/21978
Livy's Ice Cream
Quiktrip Maple And West
Dtm Urban Dictionary
7023594890
800-695-2780
Big Meech Childhood Home
Angiefoxxylove Pregnant
Craigslist Of Ocala
Face Split Diving Accident 2022
Sra Memorialcare
Daryl Hannah Before and After Plastic Surgery: Face, Lips
Cessna 172 For Sale Las Vegas
Wells Fargo Arena Des Moines Seating Chart Virtual View
Back Pages Chattanooga
Comcast Business Downdetector
Black Panther 2 Showtimes Near Epic Theatres Of Palm Coast
Instagram - Brianna Aerial
Postgame Media Availability 9/19: David Andrews, Jabrill Peppers, Jahlani Tavai, Rhamondre Stevenson
Bfads 2022 Walmart
Jeff Danker Net Worth
25 Best Things to Do in Bremerton, WA - Travel Lens
Myusu Canvas
Craigs List Jonesboro Ar
[PDF] resurrection of a real right - Louisiana State Bar Association - Free Download PDF
Granite Connections Bell Schedule
Meggen Nut
When Is Petsmart Dollar Per Gallon Sale 2022
Sprinter Tyrone's Unblocked Games
art-labeling activity: mitosis and cytokinesis
Dr John Artz Utah Veterinarian
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 6065

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.