v19 launch sale ends in ... Get 25% off BUY NOW
3d cartoon hands holding a phone

Unlock full course by purchasing a membership

Lesson 1

Building your Own Simple Server with NestJS

STANDARD

Building your Own Simple Server

Everything we have dealt with so far has involved entirely local data. In other words, the Internet is not required — there is no data coming into the application and there is no data going out.

Many applications do operate this way, but many also need to communicate with the outside world. Maybe they want to backup data to some external server and sync across devices, maybe there is shared data in the application like a chat application or social media app, maybe you need to pull in the current weather data into the application. There are lots of scenarios where we might need to pull data into our application or send it out into the world wide web (and we will be doing exactly this in a real application soon).

But first, some theory and a fun little example. This module is going to focus on exploring the basics of communicating with an external API.

The Lucky Number API

To help remove some of the mysteriousness around servers if you have never built your own… we are going to build our own API/server! If you are not aiming to be a backend or fullstack developer then this isn’t likely something you will actually need to do, but it will help to have a basic understanding of what is going on.

The idea is reasonably simple. Our application will allow the user to guess a number, and if it is the “lucky” number they win! We could handle this entirely locally, we could just have our application generate the “lucky” number, but there are nefarious users out there. If we were giving away more than just the satisfaction of having won, then people could inspect the client side code to see how numbers are being generated.

If we handle this on an external server, the nefarious users now no longer have access to see how this number is generated — all they get is the result. That isn’t to say this approach is perfectly secure, I’m sure some clever hackers could still probably find a way to cheat the system but it’s good enough for our demonstration.

Although this is just a fun example, handling logic on servers in this way is also useful in the real world. Using secret API keys is a common example. Let’s say you have some API key that needs to be kept secret, and you use that API key to access some service that your application uses. You can’t just put that API key in your client side/frontend code (the Angular application) because anybody could easily steal the API key and use it themselves. If you instead store that key on your server, and have your server handle making the requests using the API key instead, the API key is now no longer exposed to your users (and your frontend application makes requests to your server).

NOTE: Some API keys are allowed to be public and some need to be kept secret. Make sure you check carefully in the documentation of whatever API you are using to see whether it is safe to expose your API key in your front end code or not (more on that later).

Ok, let’s get into building this server!

Creating a REST API with NestJS

NestJS is an amazing way to build backend applications. We aren’t really going to be learning anything about it in this course, we are just going to use the starter template to create the most basic REST server possible. Again, not going to dive too deep into what REST is, but the basic idea is that it will allow us to make GET requests to a URL to retrieve data from the server, and POST requests to the server to send it data.

NestJS is basically a way to build backend/server applications in an Angular style. Rather than using bare bones NodeJS, NestJS makes it easier for us to build servers with NodeJS by giving us a lot of things out of the box. It is not the same thing as Angular, but so many of the concepts come from Angular that you already have a massive head start in using NestJS if you know Angular concepts already. Hopefully this little teaser makes you curious to dive into NestJS a little more on your own.

Create a new NestJS application with the following command (make sure this is outside of any Angular project):

npx @nestjs/cli new api

NOTE: Choose the npm package manager.

Once the application is generated, open it in your editor.

Open src/app.controller.ts and find this:

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }

I’m not going to dive into NestJS concepts, but the basic idea here is that a controller controls what happens when the application makes a request to certain endpoints on your server. For example if a GET request is made to https://my-api.com/users or https://my-api.com/users/1. To do this, we decorate a function inside of the @Controller('users') with the @Get() decorator and whatever that function returns is what the request will return.

Since no argument is supplied to @Get(), the code above is just defining the GET response for the default endpoint (i.e. when we make a request to https://my-api.com/). We are going to keep things super simple here because this module isn’t about learning how to build servers, it’s about learning how to integrate with them.

Modify the code above to reflect the following:

  @Get()
  getLuckyNumber(): number {
    return Math.floor(Math.random() * 100);
  }

Now our default endpoint is going to return a random number between 0 and 99 — this isn’t the greatest way to generate a random number (random numbers generated by a computer are never really random) but it will do for us!

There is one more thing we will need to do before our server will work, we need to enable CORS or Cross-origin Resource Sharing. The basic idea is that if we try to make a request to our server from some other domain, which is what we will be doing in the case of our Angular application, it will be blocked by default. To allow other domains to make requests to our server we need to enable it.

Modify the bootstrap method in main.ts to reflect the following:

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  await app.listen(3000);
}
STANDARD
Key

Thanks for checking out the preview of this lesson!

You do not have the appropriate membership to view the full lesson. If you would like full access to this module you can view membership options (or log in if you are already have an appropriate membership).