halitsever/nest-cloudflare-turnstile
☁️ Cloudflare Turnstile Captcha integration for NestJS
☁️ Cloudflare Turnstile integration for NestJS
Installation:
npm install nest-cloudflare-turnstile --save
add module to imports array with forRoot method:
imports: [TurnstileModule.forRoot({
secretKey: '1x0000000000000000000000000000000AA',
tokenResponse: (req) => req.body?.turnstileToken // or you can use req.headers.turnstileToken
})],
or with forRootAsync method:
imports: [
TurnstileModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (config: ConfigService) => {
const secretKey = config.get<string>(
'CLOUDFLARE_TURNSTILE_PRIVATE_KEY',
);
if (!secretKey) {
throw new Error('Missing Cloudflare Turnstile secret');
}
return {
secretKey,
tokenResponse: (req) => req.body?.turnstileToken,
};
},
}),
]
use TurnstileCaptcha decorator on controller:
import { TurnstileCaptcha } from 'nest-cloudflare-turnstile'
@Post()
@TurnstileCaptcha()
getHello(): string {
return this.appService.getHello();
}
Use skipIf to bypass Turnstile validation conditionally. Useful for development or test environments:
imports: [TurnstileModule.forRoot({
secretKey: '1x0000000000000000000000000000000AA',
tokenResponse: (req) => req.body?.turnstileToken,
skipIf: process.env.NODE_ENV === 'development',
})],
No download data available
No tracked packages depend on this.
Use exceptionFactory to customize the exception thrown on validation failure. The factory receives 'missing' or 'invalid' as the reason:
import { UnauthorizedException } from '@nestjs/common';
imports: [TurnstileModule.forRoot({
secretKey: '1x0000000000000000000000000000000AA',
tokenResponse: (req) => req.body?.turnstileToken,
exceptionFactory: (reason) => {
if (reason === 'missing') {
return new UnauthorizedException('Turnstile token is required.');
}
return new UnauthorizedException('Turnstile token is invalid.');
},
})],
Without exceptionFactory, the guard throws a BadRequestException by default.
And thats it! For more information, please check the docs
MIT LICENSE | Halit Sever