API Integration (Custom Apps)
React example with server-side token validation.
Use this when:
- You have a custom web application
- You want server-side token validation
- You need full control over verification flow
Installation
npm install @magentrust/client @magentrust/nodeClient-Side (React)
// hooks/useMAGENVerification.ts
import { useState, useEffect } from 'react';
import { MAGENClient } from '@magentrust/client';
const client = new MAGENClient({
siteId: process.env.NEXT_PUBLIC_MAGEN_SITE_ID!,
apiKey: process.env.NEXT_PUBLIC_MAGEN_API_KEY!,
});
export function useMAGENVerification(formId: string) {
const [sessionId, setSessionId] = useState('');
const [verificationToken, setVerificationToken] = useState<string | null>(null);
const [isVerifying, setIsVerifying] = useState(false);
useEffect(() => {
const session = client.createSession(formId);
setSessionId(session.id);
session.startTracking();
return () => session.stopTracking();
}, [formId]);
const verify = async () => {
setIsVerifying(true);
try {
const result = await client.verify(sessionId);
setVerificationToken(result.token);
return result;
} finally {
setIsVerifying(false);
}
};
return { sessionId, verify, isVerifying, verificationToken };
}Component Usage
// components/ContactForm.tsx
import { useMAGENVerification } from '@/hooks/useMAGENVerification';
export default function ContactForm() {
const [formData, setFormData] = useState({ name: '', email: '', message: '' });
const { verify, isVerifying } = useMAGENVerification('contact-form');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
const verification = await verify();
if (!verification.verified) {
alert('Please interact naturally with the form.');
return;
}
const response = await fetch('/api/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...formData, magenToken: verification.token })
});
if (response.ok) alert('Message sent!');
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={formData.name} onChange={...} placeholder="Name" required />
<input type="email" value={formData.email} onChange={...} placeholder="Email" required />
<textarea value={formData.message} onChange={...} placeholder="Message" required />
<button type="submit" disabled={isVerifying}>
{isVerifying ? 'Verifying...' : 'Send'}
</button>
</form>
);
}Server-Side Validation (Next.js API Route)
// app/api/contact/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { MAGENServer } from '@magentrust/node';
const magen = new MAGENServer({ apiKey: process.env.MAGEN_SECRET_KEY! });
export async function POST(req: NextRequest) {
const { name, email, message, magenToken } = await req.json();
const validation = await magen.validateToken(magenToken);
if (!validation.valid) {
return NextResponse.json({ error: 'Invalid verification token' }, { status: 403 });
}
if (validation.entropyScore < 0.7) {
return NextResponse.json({ error: 'Verification score too low' }, { status: 403 });
}
// Process the form...
return NextResponse.json({ success: true });
}