Next.js HCaptcha
Introduction
This library provides simple higher order function
with responsibility of "guarding" specific Next.js API route.
Sample usage:
import { withHCaptcha } from 'next-hcaptcha'
export default withHCaptcha((req, res) => {
res.status(200).json({ name: 'John Doe' })
})
Configuration
Configuration is done by passing options object as second withHCaptcha
function call argument.
Default options with all properties explained:
const defaultOptions = {
captchaVerifyUrl: 'https://hcaptcha.com/siteverify',
passRequestIpAddress: false,
skipCaptchaRequestsOptimization: false,
exceptions: false,
cleanInterception: true,
errorDisplayMode: 'message',
forwardCaptchaResponse: false,
enterprise: {
scoreThreshold: null,
},
envVarNames: { secret: 'HCAPTCHA_SECRET' },
}
Configuration sharing
Configuration sharing can be done by creating next-hcaptcha.config.js
in root of your Next.js project and simply importing it and passing as argument in every (or specific) route(s).
next-hcaptcha.config.js
const config = {
}
export default config
pages/api/your-route.js
import { withHCaptcha } from 'next-hcaptcha'
import config from '../../next-hcaptcha.config'
export default withHCaptcha((req, res) => {
res.status(200).json({ name: 'John Doe' })
}, config)
Errors
next-hcaptcha
informs about errors as described in the official HCaptcha docs with some (i believe) tweaks.
NOTE: Error optimization described in point 2. and 3. can be disabled by setting skipCaptchaRequestsOptimization
in configuration to true
and way of informing about errors described in point 1.
can be restored to traditional way by setting errorDisplayMode
to 'code'
-
Error messages (descriptions in docs) are shown directly instead of informing about the error code. This has purpose of improving overall work with the library and reduce eventual frustration caused by jumping between loads of documentation.
-
missing-input-secret
is handled by the library before sending request to HCaptcha verification endpoint by checking sanity of HCAPTCHA_SECRET
environment variable. and results in runtime exception.
-
missing-input-response
is also handled by the library before sending request to HCaptcha verification endpoint and results in standard error respecting the first point.
-
If enterprise.scoreThreshold
is specified and no score
is returned from HCaptcha API, it will result in runtime exception.
Ending speech
This project is licensed under the MIT license.
All contributions are welcome.