DEV Community

Alexander Nitrovich
Alexander Nitrovich

Posted on • Originally published at blog.eurovalidate.com

Validate EU VAT in NestJS

When working with EU VAT compliance in NestJS applications, integrating a reliable VAT validation API becomes vital. This tutorial offers a step-by-step guide to incorporating VAT validation using the EuroValidate API, ensuring your application is both compliant and efficient. We will go through setting up your NestJS application, understanding VAT validation requirements, and implementing a robust solution with error handling and testing practices.

Introduction

In the European Union, ensuring VAT compliance is crucial for businesses, as it involves verifying valid VAT numbers to prevent fraudulent activities and ensure accurate tax reporting. With the rise of API-driven applications, NestJS becomes an ideal choice for building scalable and compliant APIs. In this article, we'll explore how to implement EU VAT validation in your NestJS application using the EuroValidate API, focusing on best practices and potential pitfalls.

Prerequisites and Setting Up Your NestJS Project

Before diving into VAT validation, make sure you have the necessary tools:

  • Node.js (v12 or higher)
  • NestJS CLI for project scaffolding
  • Basic understanding of NestJS framework

To set up your project, use the following commands:

npm install -g @nestjs/cli
nest new vat-validation-project
cd vat-validation-project
npm install @nestjs/common @nestjs/core @nestjs/platform-express
npm install @eurovalidate/sdk
Enter fullscreen mode Exit fullscreen mode

Understanding EU VAT Validation Requirements

A valid EU VAT number is typically structured with a country code followed by a series of digits and possibly letters. Validation involves checking the format and verifying the number against official records. Public APIs like EuroValidate offer endpoints that provide such verification.

Integrating a VAT Validation API into NestJS

Choosing the Right API Provider

EuroValidate stands out with its developer-first API model, providing easy integration and clear documentation. Start by registering at EuroValidate to get your free API key.

Configuring API Keys and Environment Variables

Store your API key in a .env file for security:

EUROVALIDATE_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Setting up HTTP Modules for Outbound Calls

Integrate HTTP capabilities with NestJS and EuroValidate as follows:

import { Module, HttpModule } from '@nestjs/common';

@Module({
  imports: [HttpModule],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Implementing VAT Validation in a NestJS Service

Creating a Dedicated VAT Validation Service

Here's a basic VAT validation service setup:

import { Injectable, HttpService } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class VATService {
  constructor(private httpService: HttpService, private configService: ConfigService) {}

  async validateVAT(vatNumber: string): Promise<any> {
    const apiKey = this.configService.get('EUROVALIDATE_API_KEY');

    try {
      const response = await this.httpService
        .get(`https://api.eurovalidate.com/v1/vat/${vatNumber}`, {
          headers: { 'Authorization': `Bearer ${apiKey}` },
        })
        .toPromise();
      return response.data;
    } catch (error) {
      throw new Error('Unable to validate VAT number');
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Building a Controller and Exposing an API Endpoint

Create a simple controller to handle requests:

import { Controller, Get, Param } from '@nestjs/common';
import { VATService } from './vat.service';

@Controller('validate')
export class VATController {
  constructor(private readonly vatService: VATService) {}

  @Get(':vatNumber')
  async validate(@Param('vatNumber') vatNumber: string) {
    return await this.vatService.validateVAT(vatNumber);
  }
}
Enter fullscreen mode Exit fullscreen mode

Handling Errors and Exceptions

Robust error handling is crucial. Use NestJS Exception Filters:

import { ExceptionFilter, Catch, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpErrorFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    const request = host.switchToHttp().getRequest();
    const status = exception.getStatus();
    const error = exception.getResponse();

    response.status(status).json({
      timestamp: new Date().toISOString(),
      path: request.url,
      error,
    });
  }
}
Enter fullscreen mode Exit fullscreen mode

Include this filter in your application to log errors effectively.

Testing Your VAT Validation Functionality

Use Jest for unit testing:

import { Test, TestingModule } from '@nestjs/testing';
import { VATService } from './vat.service';
import { HttpModule } from '@nestjs/axios';

describe('VATService', () => {
  let service: VATService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [HttpModule],
      providers: [VATService],
    }).compile();

    service = module.get<VATService>(VATService);
  });

  it('should validate a VAT number successfully', async () => {
    const result = await service.validateVAT('NL820646660B01');
    expect(result.status).toEqual('valid');
  });

  it('should fail an invalid VAT number', async () => {
    try {
      await service.validateVAT('INVALIDVAT');
    } catch (error) {
      expect(error.message).toBe('Unable to validate VAT number');
    }
  });
});
Enter fullscreen mode Exit fullscreen mode

Remember to mock HTTP responses in your tests to simulate API calls.

Next Steps and Additional Resources

  • Optimization: Improve performance by caching frequent validation checks.
  • Documentation: Explore EuroValidate API Documentation for advanced features.
  • Community: Share your feedback and join our developer community for collaboration and support.

Ready to enhance your API with reliable VAT validation? Get your free API key at EuroValidate. Join our community to share feedback and continue your learning journey.


Ensure that you handle API calls efficiently to minimize latency, taking into consideration network speed and potential downtime. By following this guide, you'll create robust, scalable solutions for EU VAT validation in your NestJS applications.

Top comments (0)