How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
NestJS · TypeScript/React

Fix BadRequestException: Validation failed (numeric string is expected) in NestJS

This error occurs when a NestJS validation pipe rejects input that does not match the expected type or DTO constraints. Common causes include passing a string where a number is expected, missing required fields, or invalid enum values. Fix it by ensuring client input matches the DTO schema and pipe configuration.

Reading the Stack Trace

BadRequestException: Validation failed (numeric string is expected) at ParseIntPipe.exceptionFactory (node_modules/@nestjs/common/pipes/parse-int.pipe.js:23:16) at ParseIntPipe.transform (node_modules/@nestjs/common/pipes/parse-int.pipe.js:31:24) at /node_modules/@nestjs/core/pipes/pipes-consumer.js:18:33 at PipesConsumer.applyPipes (node_modules/@nestjs/core/pipes/pipes-consumer.js:30:17) at RouterExplorer.executePipeline (node_modules/@nestjs/core/router/router-execution-context.js:174:41) at /node_modules/@nestjs/core/router/router-execution-context.js:48:28 at /node_modules/@nestjs/core/router/router-proxy.js:9:23 at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5) at next (node_modules/express/lib/router/route.js:144:13) at Route.dispatch (node_modules/express/lib/router/route.js:114:3)

Here's what each line means:

Common Causes

1. Non-numeric ID in route parameter

The route expects a numeric ID but receives a string like 'abc' or an empty value.

@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
  return this.service.findOne(id);
}
// GET /users/abc -> Validation failed

2. Missing required fields in request body

The DTO requires certain fields but the client sends an incomplete request body.

export class CreateUserDto {
  @IsNotEmpty()
  name: string;

  @IsEmail()
  email: string;
}
// Client sends: { name: 'Alice' } -> email is missing

3. ValidationPipe not configured globally

The validation pipe is not applied globally, so some routes skip validation and receive invalid data.

// main.ts - no global pipe configured
const app = await NestFactory.create(AppModule);
await app.listen(3000);

The Fix

Customize the ParseIntPipe exception factory to return a human-readable error message. Apply ValidationPipe globally so all DTOs are validated automatically. Use whitelist to strip unexpected properties and transform to auto-cast types.

Before (broken)
import { Controller, Get, Param, ParseIntPipe } from '@nestjs/common';

@Controller('users')
export class UserController {
  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.userService.findOne(id);
  }
}
After (fixed)
import { Controller, Get, Param, ParseIntPipe, BadRequestException } from '@nestjs/common';

@Controller('users')
export class UserController {
  @Get(':id')
  findOne(
    @Param('id', new ParseIntPipe({
      exceptionFactory: () => new BadRequestException('User ID must be a valid integer'),
    }))
    id: number,
  ) {
    return this.userService.findOne(id);
  }
}

// In main.ts - apply global validation pipe
// app.useGlobalPipes(new ValidationPipe({
//   whitelist: true,
//   forbidNonWhitelisted: true,
//   transform: true,
// }));

Testing the Fix

import { Test, TestingModule } from '@nestjs/testing';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { BadRequestException } from '@nestjs/common';

describe('UserController', () => {
  let controller: UserController;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      controllers: [UserController],
      providers: [
        { provide: UserService, useValue: { findOne: jest.fn().mockResolvedValue({ id: 1 }) } },
      ],
    }).compile();

    controller = module.get<UserController>(UserController);
  });

  it('returns a user for a valid numeric ID', async () => {
    const result = await controller.findOne(1);
    expect(result).toEqual({ id: 1 });
  });

  it('ParseIntPipe rejects non-numeric strings', () => {
    const pipe = new (require('@nestjs/common').ParseIntPipe)({
      exceptionFactory: () => new BadRequestException('User ID must be a valid integer'),
    });
    expect(() => pipe.transform('abc', { type: 'param' })).rejects.toThrow('User ID must be a valid integer');
  });
});

Run your tests:

npm test

Pushing Through CI/CD

git checkout -b fix/nestjs-pipe-validation,git add src/user/user.controller.ts src/user/__tests__/user.controller.spec.ts src/main.ts,git commit -m "fix: add descriptive validation errors and global ValidationPipe",git push origin fix/nestjs-pipe-validation

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      - run: npm ci
      - run: npm test -- --coverage
      - run: npm run build

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

npm install bugstack-sdk

Step 2: Initialize

import { initBugStack } from 'bugstack-sdk'

initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Configure ValidationPipe globally in main.ts.
  2. Add descriptive exception factories to built-in pipes.
  3. Add class-validator decorators to all DTOs.
  4. Run tests to verify validation behavior.
  5. Open a PR, merge after CI, and verify in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

The whitelist option strips any properties from the request body that are not defined in the DTO class. This prevents clients from injecting unexpected fields.

ValidationPipe returns all errors by default. Each error includes the property name, failed constraints, and messages, giving the client a complete list of what needs to be fixed.