Custom Adapter
Create your own custom captcha adapter for VitNode.
If you want to use captcha in your custom form or somewhere else, follow these steps.
Usage
Activate captcha in route
import { buildRoute } from "@vitnode/core/api/lib/route";
export const exampleRoute = buildRoute({
pluginId: CONFIG_PLUGIN.pluginId,
route: {
method: "post",
description: "Create a new user",
path: "/sign_up",
withCaptcha: true,
},
handler: async c => {},
});Get config from middleware API
import { getMiddlewareApi } from "@vitnode/core/lib/api/get-middleware-api";
export const SignUpView = async () => {
const { captcha } = await getMiddlewareApi();
return <FormSignUp captcha={captcha} />;
};Use useCaptcha hook
Inside your client component, use the useCaptcha hook to handle captcha rendering and validation. Remember to add div with id="vitnode_captcha" where you want the captcha widget to appear.
"use client";
import { AutoForm } from "@vitnode/core/components/form/auto-form";
export const FormSignUp = ({
captcha,
}: {
captcha: z.infer<typeof routeMiddlewareSchema>["captcha"];
}) => {
const { isReady, getToken, onReset } = useCaptcha(captcha);
const onSubmit = async () => {
await mutationApi({
// ...other values,
captchaToken: await getToken(),
});
// Handle success or error
onReset(); // Reset captcha after submission
};
return (
<form onSubmit={onSubmit}>
{/* Render captcha widget */}
<div id="vitnode_captcha" />
<Button disabled={!isReady}>Submit</Button>
</form>
);
};Submit form with captcha
"use server";
import type { z } from "zod";
import { fetcher } from "@vitnode/core/lib/fetcher";
export const mutationApi = async ({
captchaToken,
}: {
captchaToken;
}) => {
await fetcher(usersModule, {
path: "/test",
method: "post",
module: "blog",
captchaToken,
});
};