NestJS — Creating custom parameter decorators for your APIs with createParamDecorator()

Liu Ting Chun
4 min readDec 22, 2019

If you have played with NestJS for a while, you should have been familiar with decorators. It is because NestJS utilized decorators to do the declaration, configuration and assignment of your objects. You should have seen them everywhere.

Here are five decorators that you may already have been frequently using for creating APIs: @Session, @Param, @Body , @Query and @Headers , which access req.session , req.params , req.body , req.query and req.headers correspondingly.

@Post('create-proposal')
async createProposal(
@Body('title') title,
@Body('price') price,
...
) {
...
}

However, what if you want to access your custom request attributes, such as req.jwt ?

@Post('create-proposal')
async createProposal(
@Jwt('memberId') memberId,
@Body('title') title,
@Body('price') price,
...
) {
...
}

Custom parameter decorators with a key

Actually, NestJS already has a built-in function for you to create such custom decorators — createParamDecorator()

import { createParamDecorator } from '@nestjs/common';

export const Jwt = createParamDecorator((data, req) => {
return req.jwt;
});

--

--

Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.