How to Use class-validator in a Next.js App

Samir Mirzaliyev
2 min readOct 25, 2024

--

class-validator is a popular library in TypeScript for validating object properties using decorators. It provides a powerful and flexible way to enforce rules on data, making it ideal for applications where input validation is crucial, such as APIs and form processing. In a Next.js app, integrating class-validator can help ensure that incoming requests meet specific criteria before further processing.

This article will guide you through setting up and using class-validator in a Next.js app, including configuring decorators for validation, handling API requests, and customizing error responses.

  1. Install class-validator and class-transformer
npm install class-validator class-transformer reflect-metadata

npm install --save-dev @babel/core @babel/parser babel-plugin-transform-typescript-metadata @babel/traverse @babel/plugin-transform-runtime @babel/plugin-proposal-decorators babel-plugin-parameter-decorator

2. Add the following properties compilerOptions in tsconfig.json

{
"strictPropertyInitialization": false,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
}

3. Create a file named `.babelrc` in the root directory and update it like this.

{
"presets": ["next/babel"],
"plugins": [
"babel-plugin-transform-typescript-metadata",
["@babel/plugin-proposal-decorators", { "legacy": true }],
"babel-plugin-parameter-decorator",
[
"@babel/plugin-transform-runtime",
{
"regenerator": true
}
]
]
}

4. Import the reflect-metadata to the next.config file and make forceSwcTransforms true.

import "reflect-metadata";
const nextConfig = {
experimental: {
forceSwcTransforms: true,
},
};

export default nextConfig;

Then you can define Data Transfer Objects (DTOs).

// dto/CreateUserDto.ts
import { IsString, IsEmail, Length } from 'class-validator';

export class CreateUserDto {
@IsString()
@Length(2, 30)
firstName: string;

@IsString()
@Length(2, 30)
lastName: string;

@IsEmail()
email: string;

@IsString()
@Length(6, 20)
password: string;
}

Using a class-validator in a Next.js application effectively manages validation in API routes. By defining Data Transfer Objects (DTOs) with specific rules, you ensure incoming requests meet the required criteria. Class-transformer seamlessly converts plain objects into class instances, allowing efficient validation of nested structures.

This approach streamlines validation and keeps your code organized for easier maintenance and expansion.

--

--

Samir Mirzaliyev
Samir Mirzaliyev

No responses yet