Real-World Examples

Integration Examples

Complete, production-ready examples for integrating ZKAuth into your applications.

Choose Your Platform

Select the type of application you're building

Web Applications Examples

Production-ready code examples for your platform

React Authentication Hook

Complete authentication flow with React hooks and form handling

React
jsx
import { useZKAuth } from '@zkauth/react';
import { useState } from 'react';

function LoginForm() {
  const { signIn, signUp, loading, error, user } = useZKAuth();
  const [isSignUp, setIsSignUp] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    const email = formData.get('email');
    const password = formData.get('password');

    try {
      const result = isSignUp
        ? await signUp(email, password)
        : await signIn(email, password);

      if (result.success) {
        console.log('Authentication successful:', result.user);
        window.location.href = '/dashboard';
      }
    } catch (err) {
      console.error('Authentication failed:', err);
    }
  };

  if (user) {
    return <div>Welcome, {user.email}!</div>;
  }

  return (
    <div className="max-w-md mx-auto">
      <form onSubmit={handleSubmit} className="space-y-4">
        <h2 className="text-2xl font-bold">
          {isSignUp ? 'Sign Up' : 'Sign In'}
        </h2>

        <input
          name="email"
          type="email"
          placeholder="Email"
          required
          className="w-full p-3 border rounded"
        />

        <input
          name="password"
          type="password"
          placeholder="Password"
          required
          className="w-full p-3 border rounded"
        />

        <button
          type="submit"
          disabled={loading}
          className="w-full bg-blue-500 text-white p-3 rounded disabled:opacity-50"
        >
          {loading ? 'Processing...' : (isSignUp ? 'Sign Up' : 'Sign In')}
        </button>

        {error && <p className="text-red-500 text-sm">{error}</p>}

        <button
          type="button"
          onClick={() => setIsSignUp(!isSignUp)}
          className="w-full text-blue-500 underline"
        >
          {isSignUp ? 'Already have an account? Sign In' : "Don't have an account? Sign Up"}
        </button>
      </form>
    </div>
  );
}

Next.js App Router

Server-side authentication with Next.js 13+ App Router

Next.js
typescript
// middleware.ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { ZKAuth } from '@zkauth/nodejs'

const zkauth = new ZKAuth({
  apiKey: process.env.ZKAUTH_API_KEY!
})

export async function middleware(request: NextRequest) {
  if (request.nextUrl.pathname.startsWith('/dashboard')) {
    const token = request.cookies.get('zkauth-token')?.value

    if (!token) {
      return NextResponse.redirect(new URL('/auth/signin', request.url))
    }

    try {
      const isValid = await zkauth.verifyToken(token)
      if (!isValid) {
        return NextResponse.redirect(new URL('/auth/signin', request.url))
      }
    } catch (error) {
      return NextResponse.redirect(new URL('/auth/signin', request.url))
    }
  }

  return NextResponse.next()
}

export const config = {
  matcher: ['/dashboard/:path*']
}

Python FastAPI

High-performance Python backend with async authentication

Python
python
from fastapi import FastAPI, HTTPException, Depends
from fastapi.security import HTTPBearer
from zkauth import AsyncZKAuth
import os

app = FastAPI()
security = HTTPBearer()
zkauth = AsyncZKAuth(api_key=os.getenv("ZKAUTH_API_KEY"))

async def get_current_user(credentials = Depends(security)):
    try:
        user = await zkauth.verify_token(credentials.credentials)
        return user
    except Exception:
        raise HTTPException(status_code=401, detail="Invalid token")

@app.post("/auth/signup")
async def signup(email: str, password: str):
    try:
        result = await zkauth.sign_up(email, password)
        return {"success": True, "user": result.user, "token": result.token}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.post("/auth/signin")
async def signin(email: str, password: str):
    try:
        result = await zkauth.sign_in(email, password)
        return {"success": True, "user": result.user, "token": result.token}
    except Exception as e:
        raise HTTPException(status_code=401, detail=str(e))

@app.get("/protected")
async def protected_route(current_user = Depends(get_current_user)):
    return {"message": f"Hello {current_user.email}!", "user": current_user}

Additional Resources

More examples and integration guides

GitHub Repository

Complete examples with full project structure

Interactive Playground

Try ZKAuth in your browser without setup

Video Tutorials

Step-by-step video guides for each platform

Ready to Build?

Start building secure applications with ZKAuth today.