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

plugins/{plugin_name}/src/routes/example.ts
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

plugins/{plugin_name}/src/app/sing_up/page.tsx
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.

plugins/{plugin_name}/src/components/form/sign-up/sign-up.tsx
"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

plugins/{plugin_name}/src/components/form/sign-up/mutation-api.ts
"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, 
  });
};
Custom Adapter - VitNode