Next.js improve page performance dynamic loading reCaptcha
2022-08-25
Google ReCAPTCHA
When we create a form we must include ReCAPTCHA to be aware of bots that can send spam to us. Usually, to resolve it we use reCAPTCHA. Please, note that a better way is to implement it on both front-end and back-end sides.
Performance issues in next.js with reCAPTCHA
We observed that in the standard implementation of ReCAPTCHA V2 in the next.js we have our Google Page speed score down by around 10 points on the mobile version:
- Install react-google-recaptcha package
yarn add react-google-recaptcha - Import it to the file with the form you will use ReCAPTCHA for
- Add check to the form, ReCAPTCHA siteKey (should be configured on Google settings) and onChage
In this version of the implementation, the package of the captcha will load along with the page. And this will get your next.js website score down around 10%.
Optimize Page speed score by dynamic loading of reCAPTCHA
- Add dynamic loading
const ReCAPTCHA = dynamic(() => import("react-google-recaptcha")); - Add a webhook to load the package only when we need it (when the user is starting to enter data into the form)
const [recaptchaNeeded, setRecaptchaNeeded] = useState(false); - Add the webhook to the validation of your form
- Show and dynamically load captcha only when it's needed (when the user changes the form):
Potential problems with dynamic import of ReCAPTCHA
Probably, because o opened a bug with the dynamic import of packages in next.js you will observe an issue:
Type '{ sitekey: string; onChange: (value: any) => void; }' is not assignable to type 'IntrinsicAttributes'.
Property 'sitekey' does not exist on type 'IntrinsicAttributes'.We have resolved it by changing import to generic and adding an interface for the import:
interface ReCAPTCHAProps {
sitekey: string;
onChange: any;
}
const ReCAPTCHA = dynamic<ReCAPTCHAProps>(import("react-google-recaptcha"));After this trick, we have our page working with 10% better performance in the mobile version!
Check out article of generation sitemap in next.js to improve SEO of your website!