The Easiest And Fastest Way To Get Started With NestJS

James Harrison - Founder of Vast Technology Inc.
James Harrison
5 min read
·
November 24, 2024

If you want to get started with NestJS—or if you're looking for a faster, more efficient way to bootstrap your projects—you’ve come to the right place. While this article won’t walk you through the traditional "getting started" steps in detail (the NestJS documentation does a great job of that), it will show you how to set up your project faster and with far less effort.

Whether you’re building a small API or a scalable monorepo, there are some cheat-codes that can save you hours of effort by handling the scaffolding, architecture, and setup work for you.

Together, we'll create a simple user management application as an example of how to rapidly build a RESTful API with NestJS.

The Usual Steps

If you follow the official documentation it will walk you through steps that include

  • Installing the Nest CLI
  • Creating a new project
  • Adding libraries
  • Creating controllers and routes
  • Defining payloads and validation

While the Nest CLI automates a some of the work, you'll still need to write a fair bit of code to get all this done. Instead, let's look at a way to do all of this without needing to use any CLI commands or write any code.

The NestJS Cheat-Code

While you won't find this in the official documentation, there is a free tool called Vast Studio which is built for rapid NestJS development.

Head over to the the Vast website to download the version for your operating system:

https://www.getvast.app

Once downloaded, open the app and create an account. The fastest way is to log in with your existing Github account.

Creating the Workspace

Once you've logged in to Vast Studio, click on the New Workspace button:

  1. Choose a name for your workspace. This will become the name of the folder on your computer and the name of the default application. I've called mine online-store
  2. Choose a location to store your codebase
  3. Click Create
  4. Wait for Vast Studio to finish creating the files and installing dependencies
Creating a NestJS workspace with Vast Studio

What we've just done is shortcut several steps in the process of getting started with NestJS, including:

  1. Creating a blank NestJS workspace
  2. Converting it to a monorepo structure for better management of libraries
  3. Installing and configuring some additional modules that are commonly needed, including Configuration, Validation and OpenAPI (Swagger)
  4. Installing all NPM dependencies

At this point, you could open up your new workspace in your favorite IDE and start editing code, but if you like how fast this has been so far, continue reading!

The Vast User Interface

In Vast Studio with your new workspace open:

  1. Expand the online-store folder in the left-hand Explorer panel
  2. Click on the app item with the orange icon
  3. In the table that appears, select the getHello row

The orange app resource is the Controller and is responsible for handling incoming requests. The getHello row is a Route and processes requests on a specific path, in this case the root path (e.g. http://localhost:3000/).

Vast Studio's user interface, with a controller route selected.

In the Details Sidebar on the right-hand side you'll see how the route is configured:

  • Path: the URL the route response to. It's empty, meaning it handles the controller's default path
  • Method: The HTTP method this route will respond to
  • Request Body: The payload this route accepts, set to none by default
  • Query: The query string parameters this route accepts, set to none by default
  • Response Body: The structure of the data this route will return, set to string

Let's start our application and see how this route works.

Running the Application

In your terminal, navigate into your workspace's directory and run the following command:

$ npm run start:dev
Starting the NestJS app from the terminal

If you get an error like Error: listen EADDRINUSE: address already in use :::3000, try changing the port to something else as follows:

$ PORT=3001 npm run start:dev

This will boot the application and allow us to view it in a web browser. Try visiting the url below.

http://localhost:3000/

You should see the message "Hello World!". This is our default route handling the request and responding with a string.

Thanks to Vast Studio, we also have an OpenAPI Swagger page generated automatically for us and you can find it at the following URL:

http://localhost:3000/api

The OpenAPI (Swagger) page automatically generated by Vast Studio

This page lets you see all your routes, their documentation, and example requests and responses. In addition to this, you can test your API from within the user interface by clicking the Try it out button.

Creating a Library

In this step, we'll set up our first library which will be responsible for everything relating to users. Libraries in Vast Studio are the same as modules in NestJS. It will have a controller, several routes and a few schemas. Schemas are the same as DTOs (Data Transfer Objects) in NestJS land, and define how payloads should be structured and what validation should be applied.

In Vast Studio:

  1. Hover over the libs folder in the left-hand Explorer panel and click on the plus icon that appears
  2. In the dialog that opens, give the library a name. I called mine users
  3. Click Save
  4. Hover over the new users folder in the Explorer and click the plus icon
  5. Select New Controller... and in the dialog that opens, give it a name of users
  6. Click Save
  7. Expand the users folder in the Explorer and click on the new users controller (orange icon)
Creating a NestJS library in Vast Studio

We now have a library with a controller that will respond to requests on the /users path. All routes we create inside this controller will be prefixed with /users automatically.

Defining Routes

Let's create some routes to handle the creation and deletion of users. With the users controller open:

  1. Click on the New route button and select the newPath route in the table
  2. In the right-hand Details Sidebar, click on the newPath title to edit it. Rename it to createUser
  3. Delete the value of the Path field so the route responds to the /users path
  4. Change the Method to POST
  5. In the Request Body dropdown, select Create New Schema... to define a payload for this endpoint
  6. Name it create-user and click Save

Great! Now we have our first route and a blank schema. Let's continue to our second route before we come back to fill in the schema details. While still inside the users controller:

  1. Click the plus icon above the table to create a new route
  2. Repeat the same steps as above but use the following details
    1. Rename the route to deleteUser
    2. Change the Path to :id
    3. Change the Method to Delete
    4. Leave the Request Body, Query and Response Body fields set to none

Look at that! You just created a route that will respond to requests at /users/123 where 123 is an example user ID. You may notice when you typed in :id into the Path field that a new section appeared called Parameters. This section lets us define the data type for the user ID. It's safe to leave it as string for now.

Your users controller should look like the screenshot below. Notice the create-user schema with the green icon in the Explorer. We'll look at that in the next section.

Defining POST and DELETE NestJS routes with Vast Studio.

Validating Incoming Data

Open up the create-user schema we created earlier. This is where we define what data can be sent to our createUser route. Thanks to Vast Studio, our NestJS app will automatically validate this data and throw detailed errors if the wrong information is supplied. With the create-user schema open:

  1. Click the New property button
  2. In the right-hand Details Sidebar, click on the newProperty title and rename it to username
  3. Uncheck the Optional toggle to make it a mandatory field
  4. Click on New validator and select IsEmail
  5. Click on the plus icon above the table to add a new property
  6. Repeat the steps above to create three more fields with the following configuration:
    1. name: string, required
    2. phone: string, optional
    3. age: number, required, IsInt validator

Nice! Now anyone using our POST /users endpoint will need to send a payload like this:

{
  "username": "example@getvast.app",
  "name": "James Harrison",
  "age": 21
}

Here's what the completed schema should look like:

Defining request schemas (NestJS DTOs) including validation with Vast Studio.

Linking Dependencies

If you were to refresh the Swagger page in the browser, you might notice that our new routes have not appeared. Why is that? Because the users library has not been added to our online-store application yet. To check this, click on the System item under the Architecture heading in the left-hand Explorer panel:

NestJS module dependency graph diagram in Vast Studio.

This diagram shows how your NestJS applications and libraries are related to each other. In a complex project you would see a hierarchy of nodes with lines drawn between them to indicate dependencies. Right now we can see our online-store application and our users library, but they aren't connected. Let's fix that!

  1. Right-click on the online-store folder in the left-hand Explorer panel
  2. Select Dependencies from the contextual menu that appears
  3. You should see a single row called config (@nestjs/config). This is a built-in dependency that helps us define configuration settings for our app. We will cover this in a future article.
  4. Click on the plus icon above the table to add a new dependency
  5. In the dialog that appears, select the users library

That's it! Your application now imports the users library as a dependency. Go back to the System Architecture diagram to verify the connection:

Importing the users library from the online-store application

Testing the API

Back in the browser, reload the Swagger page and make sure you can see the new endpoints:

Updated Swagger page with routes from the users library.

Expand the POST /users accordion and follow these steps:

  1. Click the Try it out button
  2. In the request body, paste the JSON payload below
  3. Scroll down and click the Execute button
{
  "username": "example",
  "name": "James",
  "age": "21"
}

Scroll down to the Server Response section. You should see a 400 Bad Request error with the following body:

{
  "statusCode": 400,
  "message": [
    "username must be an email",
    "age must be an integer number",
    "age must be a number conforming to the specified constraints"
  ],
  "error": "Bad Request"
}

Look at that! It's picked up the problems with the username and age fields and given us descriptive error messages. Let's fix the payload and try again:

{
  "username": "example@getvast.app",
  "name": "James",
  "age": 21
}

Check the Server response and make sure you get a 500 Internal server error. Why an error? Because we haven't implemented the logic for the route yet. But a 500 error shows that our payload passed validation, which is a good thing!

Editing the Code

Now that we're happy with our work in Vast Studio, it's time to switch back to our IDE to write some code. There's an easy way to do this. Open up the users controller in Vast Studio and click on the Open in IDE button in the top-right corner of the screen. This should open your IDE and load up the users.controller.ts file where you can take over and add the necessary logic.

Switching from Vast Studio to code with the Open in IDE button.

Wrapping Up

This article explored how Vast Studio accelerates NestJS project setup by automating common tasks like monorepo organization, controller and route generation, schema validation, and Swagger documentation. These steps, which are typically time-consuming, are handled seamlessly, providing you with a solid, best-practice foundation. By using Vast Studio, you can skip repetitive scaffolding and focus on building business logic, improving both efficiency and project quality.

If you enjoyed this article, please share it with your programmer friends and colleagues! As always, you can join us in the Vast Discord Community to continue the discussion.

Thanks for reading, happy programming!

Heading

James Harrison - Founder of Vast Technology Inc.
James Harrison
This is some text inside of a div block.
·
This is some text inside of a div block.