Google recaptcha module for NestJS.
npm install @nestlab/google-recaptchaThis package provides protection for endpoints using reCAPTCHA for NestJS REST and GraphQL applications. By integrating with reCAPTCHA, this package helps to prevent automated abuse such as spam and bots, improving the security and reliability of your application.





* Installation
* Changes
* Configuration
* Options
* REST application
* reCAPTCHA v2
* reCAPTCHA v3
* reCAPTCHA Enterprise
* Graphql application
* reCAPTCHA v2
* reCAPTCHA v3
* reCAPTCHA Enterprise
* Usage
* REST application
* Graphql application
* Validate in service
* Validate in service (Enterprise)
* Dynamic Recaptcha configuration
* Error handling
* Contribution
* License
Usage example here
```
$ npm i @nestlab/google-recaptcha
The list of changes made in the project can be found in the CHANGELOG.md file.
GoogleRecaptchaModuleOptions
| Property | Description |
|-------------------|-------------|
| response | Required.(request) => string
Type: secretKey
Function that returns response (recaptcha token) by request |
| | Optional.string
Type: debug
Google recaptcha secret key. Must be set if you don't use reCAPTCHA Enterprise |
| | Optional.boolean
Type: false
Default: logger
Enables logging requests, responses, errors and transformed results |
| | Optional.Logger
Type: new Logger()
Default: skipIf
Instance of custom logger that extended from Logger (@nestjs/common) |
| | Optional.boolean
Type: \| (request) => boolean \| Promise enterprise
Function that returns true if you allow the request to skip the recaptcha verification. Useful for involing other check methods (e.g. custom privileged API key) or for development or testing |
| | Optional.GoogleRecaptchaEnterpriseOptions
Type: secretKey
Options for using reCAPTCHA Enterprise API. Cannot be used with option. |network
| | Optional.GoogleRecaptchaNetwork
Type: \| stringGoogleRecaptchaNetwork.Google
Default: GoogleRecaptchaNetwork.Google
If your server has trouble connecting to https://google.com then you can set networks:
= 'https://www.google.com/recaptcha/api/siteverify'GoogleRecaptchaNetwork.Recaptcha = 'https://recaptcha.net/recaptcha/api/siteverify'score
or set any api url |
| | Optional.number
Type: \| (score: number) => booleannumber
Score validator for reCAPTCHA v3 or enterprise.
- minimum available score. (score: number) => boolean
- function with custom validation rules. |actions
| | Optional.string[]
Type: @Recaptcha(...)
Available action list for reCAPTCHA v3 or enterprise.
You can make this check stricter by passing the action property parameter to decorator. |remoteIp
| | Optional.(request) => string
Type: axiosConfig
A function that returns a remote IP address from the request |
| | Optional.AxiosRequestConfig
Type: global
Allows to setup proxy, response timeout, https agent etc... |
| | Optional.boolean
Type: false
Default: Defines a module in the global scope. |
GoogleRecaptchaEnterpriseOptions
| Property | Description |
|-----------------|-------------|
| projectId | Required.string
Type: siteKey
Google Cloud project ID |
| | Required.string
Type: apiKey
reCAPTCHA key associated with the site/app. |
| | Required.string
Type: reCAPTCHA Enterprise API
API key associated with the current project.
Must have permission .
You can manage credentials here. |
The module provides two static methods for configuration: forRoot and forRootAsync.
forRoot
> forRoot(options: GoogleRecaptchaModuleOptions): DynamicModule
The forRoot method accepts a GoogleRecaptchaModuleOptions object that configures the module. This method should be used in the root AppModule.
Example usage:
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
secretKey: process.env.GOOGLE_RECAPTCHA_SECRET_KEY,
response: req => req.headers.recaptcha,
})
],
})
export class AppModule {
}
forRootAsync
> forRootAsync(options: ModuleAsyncOptions): DynamicModule
The forRootAsync method is similar to forRoot, but allows for asynchronous configuration.GoogleRecaptchaModuleAsyncOptions
It accepts a object that returns a configuration object or a Promise that resolves to a configuration object.
Read more about ConfigService and custom getter function.
Example usage:
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => configService.googleRecaptchaOptions,
inject: [ConfigService],
})
],
})
export class AppModule {
}
#### REST reCAPTCHA V2
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
secretKey: process.env.GOOGLE_RECAPTCHA_SECRET_KEY,
response: req => req.headers.recaptcha,
skipIf: process.env.NODE_ENV !== 'production',
}),
],
})
export class AppModule {
}
Tip: header names transforming to lower case.
For example: If you send 'Recaptcha' header then use (req) => req.headers.recaptcha
#### REST reCAPTCHA V3
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
secretKey: process.env.GOOGLE_RECAPTCHA_SECRET_KEY,
response: req => req.headers.recaptcha,
skipIf: process.env.NODE_ENV !== 'production',
actions: ['SignUp', 'SignIn'],
score: 0.8,
}),
],
})
export class AppModule {
}
Tip: header names transforming to lower case.
For example: If you send 'Recaptcha' header then use (req) => req.headers.recaptcha
#### REST reCAPTCHA Enterprise
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
response: (req) => req.headers.recaptcha,
skipIf: process.env.NODE_ENV !== 'production',
actions: ['SignUp', 'SignIn'],
score: 0.8,
enterprise: {
projectId: process.env.RECAPTCHA_ENTERPRISE_PROJECT_ID,
siteKey: process.env.RECAPTCHA_ENTERPRISE_SITE_KEY,
apiKey: process.env.RECAPTCHA_ENTERPRISE_API_KEY,
},
}),
],
})
export class AppModule {
}
Tip: header names transforming to lower case.
For example: If you send 'Recaptcha' header then use (req) => req.headers.recaptcha
#### Graphql reCAPTCHA V2
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
secretKey: process.env.GOOGLE_RECAPTCHA_SECRET_KEY,
response: (req: IncomingMessage) => (req.headers.recaptcha || '').toString(),
skipIf: process.env.NODE_ENV !== 'production',
}),
],
})
export class AppModule {
}
Tip: header names transforming to lower case.
For example: If you send 'Recaptcha' header then use (req: IncomingMessage) => (req.headers.recaptcha || '').toString()
#### Graphql reCAPTCHA V3
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
secretKey: process.env.GOOGLE_RECAPTCHA_SECRET_KEY,
response: (req: IncomingMessage) => (req.headers.recaptcha || '').toString(),
skipIf: process.env.NODE_ENV !== 'production',
actions: ['SignUp', 'SignIn'],
score: 0.8,
}),
],
})
export class AppModule {
}
Tip: header names transforming to lower case.
For example: If you send 'Recaptcha' header then use (req: IncomingMessage) => (req.headers.recaptcha || '').toString()
#### Graphql reCAPTCHA Enterprise
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
response: (req: IncomingMessage) => (req.headers.recaptcha || '').toString(),
skipIf: process.env.NODE_ENV !== 'production',
actions: ['SignUp', 'SignIn'],
score: 0.8,
enterprise: {
projectId: process.env.RECAPTCHA_ENTERPRISE_PROJECT_ID,
siteKey: process.env.RECAPTCHA_ENTERPRISE_SITE_KEY,
apiKey: process.env.RECAPTCHA_ENTERPRISE_API_KEY,
},
}),
],
})
export class AppModule {
}
Tip: header names transforming to lower case.
For example: If you send 'Recaptcha' header then use (req) => req.headers.recaptcha
Configuration for reCAPTCHA Enterprise
`typescript`
@Module({
imports: [
GoogleRecaptchaModule.forRoot({
response: (req) => req.headers.recaptcha,
skipIf: process.env.NODE_ENV !== 'production',
actions: ['SignUp', 'SignIn'],
score: 0.8,
enterprise: {
projectId: process.env.RECAPTCHA_ENTERPRISE_PROJECT_ID,
siteKey: process.env.RECAPTCHA_ENTERPRISE_SITE_KEY,
apiKey: process.env.RECAPTCHA_ENTERPRISE_API_KEY,
},
}),
],
})
export class AppModule {
}
To protect your REST endpoints, you can use the @Recaptcha decorator.
Example:
`typescript
@Controller('feedback')
export class FeedbackController {
@Recaptcha()
@Post('send')
async send(): Promise
// TODO: Your implementation.
}
}
`
You can also override the default property that contains reCAPTCHA for a specific endpoint.
`typescript
@Controller('feedback')
export class FeedbackController {
@Recaptcha({response: req => req.body.recaptha})
@Post('send')
async send(): Promise
// TODO: Your implementation.
}
}
`
Additionally, you can override reCAPTCHA v3 options.
`typescript
@Controller('feedback')
export class FeedbackController {
@Recaptcha({response: req => req.body.recaptha, action: 'Send', score: 0.8})
@Post('send')
async send(): Promise
// TODO: Your implementation.
}
}
`
To get the verification result, you can use the @RecaptchaResult() decorator.
`typescript
@Controller('feedback')
export class FeedbackController {
@Recaptcha()
@Post('send')
async send(@RecaptchaResult() recaptchaResult: RecaptchaVerificationResult): Promise
console.log(Action: ${recaptchaResult.action} Score: ${recaptchaResult.score});
// TODO: Your implementation.
}
}
`
If you want to use the Google reCAPTCHA guard in combination with other guards, you can use the @UseGuards decorator.`typescript
@Controller('feedback')
export class FeedbackController {
@SetRecaptchaOptions({action: 'Send', score: 0.8})
@UseGuards(Guard1, GoogleRecaptchaGuard, Guard2)
@Post('send')
async send(): Promise
// TODO: Your implementation.
}
}
`
You can find a usage example in the following link.
To protect your resolver, use the @Recaptcha decorator.
`typescript`
@Recaptcha()
@Resolver(of => Recipe)
export class RecipesResolver {
@Query(returns => Recipe)
async recipe(@Args('id') id: string): Promise
// TODO: Your implementation.
}
}
Obtain verification result:
`typescriptAction: ${recaptchaResult.action} Score: ${recaptchaResult.score}
@Recaptcha()
@Resolver(of => Recipe)
export class RecipesResolver {
@Query(returns => Recipe)
async recipe(@Args('id') id: string,
@RecaptchaResult() recaptchaResult: RecaptchaVerificationResult): Promise
console.log();`
// TODO: Your implementation.
}
}
You can override the default recaptcha property for a specific endpoint.
`typescript
@Recaptcha()
@Resolver(of => Recipe)
export class RecipesResolver {
@Query(returns => Recipe)
async recipe(@Args('id') id: string): Promise
// TODO: Your implementation.
}
// Overridden default header. This query using X-Recaptcha header
@Recaptcha({response: (req: IncomingMessage) => (req.headers['x-recaptcha'] || '').toString()})
@Query(returns => [Recipe])
recipes(@Args() recipesArgs: RecipesArgs): Promise
// TODO: Your implementation.
}
}
`
`typescript
@Injectable()
export class SomeService {
constructor(private readonly recaptchaValidator: GoogleRecaptchaValidator) {
}
async someAction(recaptchaToken: string): Promise
const result = await this.recaptchaValidator.validate({
response: recaptchaToken,
score: 0.8,
action: 'SomeAction',
});
if (!result.success) {
throw new GoogleRecaptchaException(result.errors);
}
// TODO: Your implemetation
}
}
`
`typescript
@Injectable()
export class SomeService {
constructor(private readonly recaptchaEnterpriseValidator: GoogleRecaptchaEnterpriseValidator) {
}
async someAction(recaptchaToken: string): Promise
const result = await this.recaptchaEnterpriseValidator.validate({
response: recaptchaToken,
score: 0.8,
action: 'SomeAction',
});
if (!result.success) {
throw new GoogleRecaptchaException(result.errors);
}
const riskAnalytics = result.getEnterpriseRiskAnalytics();
// TODO: Your implemetation
}
}
`
class provides a convenient way to modify Recaptcha validation parameters within your application.
This can be particularly useful in scenarios where the administration of Recaptcha is managed dynamically, such as by an administrator.
The class exposes methods that allow the customization of various Recaptcha options.
RecaptchaConfigRef API:
`typescript
@Injectable()
class RecaptchaConfigRef {
// Sets the secret key for Recaptcha validation.
setSecretKey(secretKey: string): this; // Sets enterprise-specific options for Recaptcha validation
setEnterpriseOptions(options: GoogleRecaptchaEnterpriseOptions): this;
// Sets the score threshold for Recaptcha validation.
setScore(score: ScoreValidator): this;
// Sets conditions under which Recaptcha validation should be skipped.
setSkipIf(skipIf: SkipIfValue): this;
}
`Usage example:
`typescript
@Injectable()
export class RecaptchaAdminService implements OnApplicationBootstrap {
constructor(private readonly recaptchaConfigRef: RecaptchaConfigRef) {
} async onApplicationBootstrap(): Promise {
// TODO: Pull recaptcha configs from your database
this.recaptchaConfigRef
.setSecretKey('SECRET_KEY_VALUE')
.setScore(0.3);
}
async updateSecretKey(secretKey: string): Promise {
// TODO: Save new secret key to your database
this.recaptchaConfigRef.setSecretKey(secretKey);
}
}
`After call
this.recaptchaConfigRef.setSecretKey(...) - @Recaptcha guard and GoogleRecaptchaValidator will use new secret key.$3
GoogleRecaptchaException
GoogleRecaptchaException extends HttpException extends Error.The
GoogleRecaptchaException is an exception that can be thrown by the GoogleRecaptchaGuard when an error occurs. It extends the HttpException class provided by NestJS, which means that it can be caught by an ExceptionFilter in the same way as any other HTTP exception.One important feature of the
GoogleRecaptchaException is that it contains an array of Error Code values in the errorCodes property. These values can be used to diagnose and handle the error.| Error code | Description | Status code |
|----------------------------------|-------------|-------------|
|
ErrorCode.MissingInputSecret | The secret parameter is missing. (Throws from reCAPTCHA api). | 500 |
| ErrorCode.InvalidInputSecret | The secret parameter is invalid or malformed. (Throws from reCAPTCHA api). | 500 |
| ErrorCode.MissingInputResponse | The response parameter is missing. (Throws from reCAPTCHA api). | 400 |
| ErrorCode.InvalidInputResponse | The response parameter is invalid or malformed. (Throws from reCAPTCHA api). | 400 |
| ErrorCode.BadRequest | The request is invalid or malformed. (Throws from reCAPTCHA api). | 500 |
| ErrorCode.TimeoutOrDuplicate | The response is no longer valid: either is too old or has been used previously. (Throws from reCAPTCHA api). | 400 |
| ErrorCode.UnknownError | Unknown error. (Throws from reCAPTCHA api). | 500 |
| ErrorCode.ForbiddenAction | Forbidden action. (Throws from guard when expected action not equals to received). | 400 |
| ErrorCode.LowScore | Low score (Throws from guard when expected score less than received). | 400 |
| ErrorCode.InvalidKeys | keys were copied incorrectly, the wrong keys were used for the environment (e.g. development vs production), or if the keys were revoked or deleted from the Google reCAPTCHA admin console.. (Throws from reCAPTCHA api). | 400 |
| ErrorCode.NetworkError | Network error (like ECONNRESET, ECONNREFUSED...). | 500 |
| ErrorCode.SiteMismatch | Site mismatch (Throws from reCAPTCHA Enterprise api only). | 400 |
| ErrorCode.BrowserError | Browser error (Throws from reCAPTCHA Enterprise api only). | 400 |
GoogleRecaptchaNetworkException
The
GoogleRecaptchaNetworkException is an exception that extends the GoogleRecaptchaException class and is thrown in the case of a network error.
It contains a networkErrorCode property, which contains the error code of the network error, retrieved from the code property of the AxiosError object.You can handle it via ExceptionFilter.
Example exception filter implementation.
`typescript@Catch(GoogleRecaptchaException)
export class GoogleRecaptchaFilter implements ExceptionFilter {
catch(exception: GoogleRecaptchaException, host: ArgumentsHost): any {
// TODO: Your exception filter implementation
}
}
`And add your filter to application
`typescriptasync function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new ErrorFilter(), new GoogleRecaptchaFilter());
await app.listen(3000);
}
bootstrap();
``We welcome any contributions to improve our package! If you find a bug, have a feature request, or want to suggest an improvement, feel free to submit an issue on our GitHub repository.
If you want to contribute to the codebase directly, please follow our contributing guidelines outlined in the CONTRIBUTING.md file in the repository.
We value the contributions of our community and appreciate all efforts to make this package better for everyone. Thank you for your support!
This project is licensed under the MIT License - see the LICENSE.md file for details.