Overview

Get the current user in controllers without accessing the raw request object.

Features

  • Extract full user object
  • Extract specific property
  • Type-safe user data
  • Null handling

Installation

npx hanma add current-user --framework nest

Code

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

export interface CurrentUserData {
  id: string;
  email: string;
  roles: string[];
  [key: string]: unknown;
}

/**
 * Extract the current authenticated user from the request.
 * 
 * Usage:
 * @Get("profile")
 * getProfile(@CurrentUser() user: CurrentUserData) {
 *   return user;
 * }
 * 
 * // Extract specific property
 * @Get("profile")
 * getProfile(@CurrentUser("id") userId: string) {
 *   return { userId };
 * }
 */
export const CurrentUser = createParamDecorator(
  (data: keyof CurrentUserData | undefined, ctx: ExecutionContext) => {
    const request = ctx.switchToHttp().getRequest();
    const user = request.user as CurrentUserData;

    if (!user) {
      return null;
    }

    return data ? user[data] : user;
  }
);

Usage

@Get('profile')
getProfile(@CurrentUser() user: CurrentUserData) {
  return user;
}

Dependencies

No external dependencies required.

Frequently Asked Questions

How do I install Current User?
Run the following command: npx hanma add current-user --framework nest
How do I use this snippet?
Copy the code and paste it into your project. The snippet will be saved to src/decorators/current-user.decorator.ts.
Can I customize this snippet?
Yes! All snippets are copy-paste code that you own. Feel free to modify them to fit your needs.
Does this work with other frameworks?
This snippet is designed for the specific framework. Check the other framework pages for equivalent implementations.