Learn NestJS Β· 1/14

Welcome to NestJS: Setup and First Impressions

7 min read

Welcome to NestJS: Setup and First Impressions πŸš€

Hey there, future NestJS pro! Welcome to your first step into the organized, scalable, and frankly delightful world of building server-side applications with NestJS. Think of this guide as your friendly co-pilot, here to help you navigate the initial setup and get a real feel for why so many developers are flocking to this framework. We'll skip the boring, super-technical jargon and focus on what you actually need to know to get up and running.

Ready? Let's dive in!


The "Why" Before the "How": Why Choose NestJS? πŸ€”

Before we get our hands dirty with code, let's talk about the "why." Why should you invest your precious time in learning NestJS when there are other options like Express.js just hanging around?

The Problem: Imagine you're building a complex application, say, a food delivery service. You've got user authentication, restaurant listings, order processing, real-time driver tracking, and a payment system. If you build this with a minimal framework, you're the one who has to decide the entire structure. It's like being given a huge box of LEGOs with no instructions. Sure, you have freedom, but you can also build a very wobbly house that might fall over when you add a second floor (or a new feature). This often leads to inconsistent codebases, especially when working in a team, making it a nightmare to maintain and scale.

The Solution: NestJS enters the scene like a master architect with a clear blueprint. It gives you a structured way to build your application, promoting best practices from the get-go. It's built on top of battle-tested tools like Express (or optionally Fastify) but adds a layer of organization inspired by Angular, a popular front-end framework.

So, what makes NestJS a great choice?

  • Structured by Default: It provides a clear and organized architecture out of the box. This means you spend less time figuring out where to put your code and more time writing it. For a large application, this is a lifesaver.
  • Scalability: The modular architecture of NestJS makes it incredibly easy to scale your applications. You can group related features into modules, making your codebase easier to manage as it grows.
  • TypeScript First: NestJS is written in TypeScript, a superset of JavaScript that adds static typing. This means you catch a whole class of errors during development, not in production when your users are trying to order their dinner. It also makes your code more readable and self-documenting.
  • Developer Experience: With features like a powerful Command Line Interface (CLI), detailed documentation, and built-in support for things like dependency injection, NestJS is designed to make your life as a developer easier and more productive.

🧠 Fun Fact: The creator of NestJS, Kamil MyΕ›liwiec, was heavily inspired by Angular's architecture. If you have any experience with Angular, you'll feel right at home with concepts like Modules, Providers, and Dependency Injection in NestJS.


Setting Up Your NestJS Environment (Node & CLI) πŸ› οΈ

Alright, enough talk! Let's get your machine ready to build some awesome NestJS applications.

Prerequisites:

Before you can start, you need to have Node.js installed on your system. NestJS runs on Node.js, so this is a must-have.

  • Check your Node.js version: Open your terminal or command prompt and run:
    bash
    node -v
    To ensure compatibility, it's recommended to use a Long-Term Support (LTS) version of Node.js. You can check for the latest LTS version on the official Node.js website.

Installing the NestJS CLI:

The NestJS Command Line Interface (CLI) is a powerful tool that helps you create, manage, and build your NestJS projects. It's the Swiss Army knife for NestJS developers.

To install it globally on your system, run the following command in your terminal:

bash
npm i -g @nestjs/cli

Once the installation is complete, you can verify it by running:

bash
nest --version

This should display the version of the NestJS CLI you just installed.

πŸ’‘ Pro Tip: The -g flag in the npm i -g @nestjs/cli command stands for "global," which means you can use the nest command from anywhere in your terminal.


Bootstrapping Your First Application: Hello World πŸ‘‹

Now for the moment you've been waiting for – creating your very first NestJS application! Thanks to the NestJS CLI, this is incredibly straightforward.

  1. Create a new project: Open your terminal, navigate to the directory where you want to create your project, and run the following command:

    bash
    nest new my-first-nest-app

    The CLI will ask you which package manager you'd like to use (npm, yarn, or pnpm). Choose the one you're most comfortable with. For this guide, we'll assume you've selected npm.

    The CLI will now work its magic, creating a new directory called my-first-nest-app and installing all the necessary dependencies. This might take a minute or two, so feel free to grab a quick cup of coffee β˜•.

  2. Navigate into your project directory:

    bash
    cd my-first-nest-app
  3. Start the development server:

    bash
    npm run start:dev

    This command starts your application with a development server that watches for file changes. This means that whenever you save a file, the application will automatically recompile and restart, which is super handy for development.

  4. See it in action: Open your web browser and navigate to http://localhost:3000. You should see a glorious "Hello World!" message.

Congratulations! You've just created and run your first NestJS application. That wasn't so bad, was it?


Understanding the Folder Structure: The Nest Way πŸ“‚

Now that you have a running application, let's take a peek under the hood and understand the basic folder structure that the NestJS CLI has created for you. At first, it might seem like a lot of files, but each has a specific and important purpose.

Here's a simplified view of the key files and directories in the src folder:

stylus
src
β”œβ”€β”€ app.controller.spec.ts
β”œβ”€β”€ app.controller.ts
β”œβ”€β”€ app.module.ts
β”œβ”€β”€ app.service.ts
└── main.ts

Let's break them down one by one:

  • main.ts: This is the entry point of your application. It's a small file whose primary job is to create a new NestJS application instance and start listening for incoming HTTP requests on a specific port. Think of it as the ignition key for your application's engine.

  • app.module.ts: This is the root module of your application. In NestJS, applications are organized into modules. A module is a class annotated with the @Module() decorator, and it's used to group related components, controllers, and services. For now, just know that this is where you'll register the different parts of your application.

  • app.controller.ts: Controllers are responsible for handling incoming requests and returning responses to the client. They are decorated with @Controller() and define different routes for your application. In our "Hello World" example, the AppController has a single route that responds to GET requests at the root URL (/).

  • app.service.ts: Services, also known as Providers, are responsible for the business logic of your application. They are designed to be reusable and can be injected into controllers or other services. In our example, the AppService has a simple method that returns the "Hello World!" string.

  • app.controller.spec.ts: This is a test file for your app.controller.ts. NestJS has first-class support for testing, and the CLI automatically generates these test files for you. We won't dive deep into testing right now, but it's good to know it's there from the start.

🏒 Real-World Analogy: Imagine you're building a large office building.

  • The main.ts is the main entrance and the security desk that opens the building for business.
  • The app.module.ts is the floor plan of the entire building, showing where all the different departments are located.
  • A controller is like a receptionist for a specific department. They greet visitors (incoming requests) and direct them to the right person.
  • A service is like an employee in that department who does the actual work (the business logic). The receptionist doesn't do the work themselves; they delegate it to the expert.

This separation of concerns is a core principle of NestJS and is what makes it so powerful for building large, maintainable applications.


And that's a wrap for our initial tour of NestJS! You've learned why NestJS is a fantastic choice, set up your development environment, created your first application, and got a handle on its fundamental structure.

In the upcoming guides, we'll start building on this foundation, exploring controllers, services, and modules in more detail. Stay curious, and happy coding!

πŸ“š Extra Reading & References

Challenge

Your task is to extend the functionality of a basic NestJS application by creating a new API endpoint that returns a user's profile information.

You will be working with the code for two files presented in a single editor: app.controller.ts and app.service.ts.

Requirements:

  1. In app.service.ts:

    • Create a new public method named getUserProfile.
    • This method should not accept any arguments.
    • It must return an object with the following key-value pairs:
  2. In app.controller.ts:

    • Create a new method that will handle incoming requests.
    • Use the appropriate decorator to ensure this method responds to GET requests for the route /users/profile.
    • Inside this method, call the getUserProfile method from the AppService instance.
    • Return the data received from the service method.

Expected result

The final code should correctly implement the new functionality across both the service and the controller as described below.

In app.service.ts:

The AppService class should contain a new public method getUserProfile. This method must return an object containing the user's id, name, and email.

typescript
import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getUserProfile(): { id: number; name: string; email: string } {
    return {
      id: 1,
      name: 'John Doe',
      email: '[email protected]',
    };
  }
}

In app.controller.ts:

The AppController class should have a new method decorated with @Get('/users/profile'). This method should call this.appService.getUserProfile() and return its value.

typescript
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('/users/profile')
  getUserProfile() {
    return this.appService.getUserProfile();
  }
}
typescript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.