Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

270
Views
Error on ordering of methods in controller Nestjs

I have this basic CRUD methods in Nestjs. The issue I am facing is that when I am applying the getCurrentUserId() method on top on all methods it works fine but when I am applying in bottom it doesnt work and gives error. Is there anything wrong with middleware ?

user.controller.ts

@Controller('users')
@Serialize(UserDto)
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Post('/signup')
  create(@Body() createUserDto: CreateUserDto): Promise<User> {
    return this.usersService.create(createUserDto);
  }

  @Get('/@:userName')
  async getUserByUsername(@Param('userName') userName: string) {
    const user = await this.usersService.findByName(userName);
    console.log(userName);
    if (!user) {
      throw new NotFoundException('User Not Found');
    }

    return user;
  }

  //! Testing for current user
  @Get('/current')
  @UseGuards(JwtAuthGuard)
  async getCurrentUserId(@CurrentUser() id: string) {
    console.log('running endpoint');
    return id;
  }
}

current-user.decorator.ts

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

export const CurrentUser = createParamDecorator(
  (data : unknown , context : ExecutionContext) => {
    const req = context.switchToHttp().getRequest();
    console.log("I am running")
    return req.id;
  }
)

current-user.middleware.ts

@Injectable()
export class CurrentUserMiddleware implements NestMiddleware {
  constructor(private usersService: UsersService) {}

  async use(req: RequestId, res: Response, next: NextFunction) {
    const token = req.headers['authorization'];
    console.log(token);
    if (!token) {
      throw new UnauthorizedException('Unauthorized');
    }
    try {
      const { userId } =
        await this.usersService.getUserByToken(token);
      req.id = userId;
      console.log(req.id)
      next();
    } catch {
      throw new UnauthorizedException();
    }
  }
}

And I have added the middleware to user.module.ts like this

export class UsersModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(CurrentUserMiddleware).forRoutes(
      'users/current'
    );
  }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The route is matching on @Get('/@:userName') before it makes it to @Get('/current') so its executing the code inside of your getUserByUsername method instead.

Just move getCurrentUserId to the top and you should be fine.

Routes are evaluated in the order they are defined and the first matching one is used to handle the request. In general you should always put the most specific routes (the ones without route params) at the top of your controller to avoid this problem.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!