Welcome back! In the last two lessons, you learned how to:
- Register users securely (with hashed passwords).
- Let users log in and receive a JWT (JSON Web Token).
Now, it’s time to put those JWTs to work by protecting API routes.
In real-world applications, not every endpoint should be open to everyone. For example:
- Public: listing books (anyone can view).
- Private: creating, updating, or deleting books (requires login).
In this unit, you’ll enforce authentication only: a valid JWT is required to access certain routes.
Authorization (like restricting book creation to admins) comes later in the next unit.
So far, you have:
- A registration system that hashes and stores user passwords.
- A login system that validates credentials and returns a signed JWT.
- A JWT payload that contains the user’s ID (
sub) and role.
Now you’ll enforce authentication by requiring a valid JWT for protected endpoints.
NestJS provides a powerful concept called guards. Think of them as security checkpoints for routes.
A guard decides whether a request is allowed to continue to the route handler.
For authentication, NestJS provides the @nestjs/passport package, which integrates with Passport strategies (like JWT).
By using AuthGuard('jwt'), you can easily protect any route:
