React
Welcome to the React SDK documentation! This is a wrapper over the JavaScript SDK for ease of use in React components. In case you're looking for the JavaScript SDK, head over to the JavaScript SDK guide.
Quick Start
Before you can integrate Duckity into your application, you'll need to have the following:
- An application,
- CORS origins set up pointing to your application's origin(s),
- At least one policy created in that application, and
- The ID of the policies to use
If you're missing either of those, head over to the Duckity Dashboard or read the Quick Start guide to learn how to set those up.
Once you got those ready, follow these steps to get things running on your client:
Install the SDK
Run the following line in your terminal to install the Duckity SDK.
npm install @duckity/reactThen import the React hook in your code:
import { useChallenge } from "@duckity/react";Use the Hook
Use the hook as follows:
"use client";
import { useChallenge } from "@duckity/react";
function MyComponent() {
const duckity = useChallenge(process.env.NEXT_PUBLIC_DUCKITY_POLICY_ID);
}When the component is first rendered, it'll start fetching and solving a challenge.
Get a Challenge Solution
useChallenge() returns an object with multiple properties and functions to help you react to state
changes. Reading the solution is doable in two different ways.
- Reading
useChallenge().solution: string | undefined, and - Calling
useChallenge().wait(): Promise<string>.
Most of the time, you'll likely want to call useChallenge().wait().
import { SubmitEvent } from "react";
import { useChallenge } from "@duckity/react";
function MyComponent() {
const duckity = useChallenge(...);
async function handleSubmit(e: SubmitEvent<HTMLFormElement>) {
e.preventDefault();
const solution: string = await duckity.wait();
// Submit the form to your backend.
}
return (
<form onSubmit={handleSubmit}>
<input required placeholder="Email" type="email" />
<input required placeholder="Password" type="Password" />
<button type="submit">Log In</button>
</form>
)
}In case you need to submit more than one solution (e.g. because the user can perform multiple
protected actions without reloading the page), call duckity.refresh() once you have used the
solution token. It will fetch a new challenge and solve it in the background.
UseChallengeResult
Setting up the hook and calling wait() works well for simple setups. However, once your component
scales, you may want to use the rest of the properties returned by useChallenge().
Prop
Type
Contributing & License
All contributions are welcome to the SDK. Whether it's bug fixes, suggestions, new features, documentation updates, or fixing a typo, if you think you can make this SDK better, feel free to make a pull request in the GitHub repository.
This SDK is licensed under the permissive MIT License, and so will be all contributions to the SDK.