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
Here's what each line means:
- at ParseIntPipe.transform (node_modules/@nestjs/common/pipes/parse-int.pipe.js:31:24): The ParseIntPipe tried to convert the input to an integer but the value was not a valid numeric string.
- at PipesConsumer.applyPipes (node_modules/@nestjs/core/pipes/pipes-consumer.js:30:17): NestJS applies all registered pipes in order before the route handler executes.
- at RouterExplorer.executePipeline (node_modules/@nestjs/core/router/router-execution-context.js:174:41): The execution pipeline runs pipes after guards but before the controller method, rejecting invalid input early.
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.
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);
}
}
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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Configure ValidationPipe globally in main.ts.
- Add descriptive exception factories to built-in pipes.
- Add class-validator decorators to all DTOs.
- Run tests to verify validation behavior.
- 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.