Custom route decorators | Arshnoor Singh

Custom route decorators

Nest is built around a language feature called decorators. Decorators are a well-known concept in a lot of commonly used programming languages but in the JavaScript world they're still relatively new.

What is a decorator?

An ES2016 decorator is an expression which returns function and can take a target, name and property descriptor as arguments.

We apply it by prefixing the decorator with an `@` character and placing this at the very top of what we are trying to decorate. Decorators can be defined for either a class or property.

Param decorators

Nest provides a set of useful param decorators that you can use together with the HTTP route handlers. Below is a list of the provided decorators and the plain Express or Fastify objects they represent.

Additionally, we can create our own custom decorators.

const user = req.user;

Passing data

When the behavior of your decorator depends on some conditions, we can use the data parameter to pass an argument to the decorator's factory function. One use case for this is a custom decorator that extracts properties from the request object by key.

Authentication layer validates requests and attaches a user entity to the request object.