Custom integration
Customize the managed router, connect your own sessions, or use the two manual login methods.
On this page
Install the current SDK source for these helpers.
For existing 0.1.0 installations, use the
versioned package walkthrough.
Use the Quickstart unless you need custom storage or routes. The managed router is available in the Node SDK; other backend SDKs provide the manual methods below. Browser-only authentication is deferred. Browser helpers always call your backend.
React, Vue, Astro, HTML and other frontend examples use the same managed handler.
Hono and Workers
The same managed handler uses standard Request/Response objects:
import { createAuth } from "@anyoauth/node/auth";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
app.all("/auth/*", (c) => auth.handle(c.req.raw));
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
In Workers, construct the handler with credentials from your Worker bindings. The encrypted cookies work across processes and deployments with the same configuration.
Fastify
Use the SDK’s Node HTTP middleware with Fastify’s raw request and response:
import { createAuth } from "@anyoauth/node/express";
const auth = createAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
origin: "http://localhost:3000",
});
const router = auth.router();
app.all("/auth/*", async (request, reply) => {
reply.hijack();
await router(request.raw, reply.raw);
});
npm install @anyoauth/nodeManaged backend routerCurrent source example · published 0.1.0 predates these helpers
reply.hijack() hands the response to the SDK, which writes the status, headers and
cookies. The /express entrypoint is Node HTTP-compatible middleware; it does not
require Express. Keep your other routes on Fastify as usual.
Configure the router
Defaults: authPath: '/auth', returnTo: '/', sessionMaxAge: 86400 (one day).
Register ${origin}${authPath}/callback in your AnyOAuth project. returnTo must be
a fixed local path; the router does not accept arbitrary return URLs from visitors.
Optional sessionSecret supplies a separate cookie key. Otherwise keys are derived
from the backend client secret, separated by purpose and bound to the project, origin
and auth path. Rotating the effective key invalidates existing cookie sessions.
The SDK contract describes all configuration fields.
Connect your user database
const auth = createAuth({
...config,
onLogin: async (profile) => {
await users.upsert(profile.subject, profile);
},
});users is your database service. The hook runs after verification and before session
creation. Identify users by subject, not email; do not merge accounts by email.
The SDK authenticates users; your application still decides their permissions.
Use your own sessions
Supply an adapter instead of the default cookie session:
const auth = createAuth({
...config,
session: {
read: (request) => sessions.readProfile(request),
create: (profile, request) => sessions.signIn(profile, request),
destroy: (request) => sessions.signOut(request),
},
});sessions is your session service. read returns a normalized profile or null;
create and destroy return Set-Cookie headers. Async implementations are supported.
Locate sessions from their authenticated cookie, never a visitor-supplied user ID.
The SDK still manages the private login cookie and callback validation.
Default sessions are stateless encrypted cookies. Logout clears this browser’s cookie; a copied cookie remains valid until expiry. Use the adapter for immediate server-side revocation, your existing database sessions, or profiles too large for a cookie.
Protect backend routes
Read the authenticated profile on the server before allowing access:
app.get('/account', async (req, res) => {
const profile = await auth.getProfile(req);
if (!profile) return res.sendStatus(401);
res.json({ subject: profile.subject });
});The Express adapter accepts its request object. The Fetch handler accepts a standard
Request. A profile displayed or stored in browser JavaScript is not a backend credential.
Manage the login routes yourself
All backend SDKs retain the simple manual flow. Configure an AnyOAuth client with
your backend credentials and call startLogin in your login route:
import { AnyOAuth } from "@anyoauth/node";
const client = new AnyOAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID ?? "YOUR_CLIENT_ID",
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET ?? "YOUR_CLIENT_SECRET",
baseUrl: process.env.ANYOAUTH_API_ORIGIN ?? "https://api.anyoauth.com",
});
// After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
const login = await client.startLogin({
provider: "google",
redirectUri: process.env.ANYOAUTH_REDIRECT_URI ?? "https://your-app.example/auth/callback"
});
npm install @anyoauth/nodeConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
import os
from anyoauth import Client
client = Client(os.getenv("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), os.getenv("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"), os.getenv("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"))
# After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
login = client.start_login({"provider": "google", "redirectUri": os.getenv("ANYOAUTH_REDIRECT_URI", "https://your-app.example/auth/callback")})
python -m pip install anyoauth-sdkConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
package main
import (
"os"
anyoauth "github.com/AnyOAuth/anyoauth-go"
)
func env(key, fallback string) string { if v := os.Getenv(key); v != "" { return v }; return fallback }
func main() {
// After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
client, err := anyoauth.NewClient(env("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"), env("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), env("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"))
if err != nil { panic(err) }
login, err := client.StartLogin(map[string]any{"provider": "google", "redirectUri": env("ANYOAUTH_REDIRECT_URI", "https://your-app.example/auth/callback")})
if err != nil { panic(err) }
_ = login
}
go get github.com/AnyOAuth/anyoauth-goConfidential backend SDKCurrent source example
<?php
require 'vendor/autoload.php';
$client = new \AnyOAuth\Client((getenv("ANYOAUTH_CLIENT_ID") ?: "YOUR_CLIENT_ID"), (getenv("ANYOAUTH_CLIENT_SECRET") ?: "YOUR_CLIENT_SECRET"), (getenv("ANYOAUTH_API_ORIGIN") ?: "https://api.anyoauth.com"));
// After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
$login = $client->startLogin(["provider" => "google", "redirectUri" => (getenv("ANYOAUTH_REDIRECT_URI") ?: "https://your-app.example/auth/callback")]);
composer require anyoauth/anyoauthConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
import com.anyoauth.AnyOAuth;
import com.google.gson.*;
public class Example {
static String env(String key, String fallback) { String value = System.getenv(key); return value == null ? fallback : value; }
public static void main(String[] args) {
// After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
AnyOAuth client = new AnyOAuth(env("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"), env("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), env("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"));
JsonObject params = new JsonObject();
params.addProperty("provider", "google");
params.addProperty("redirectUri", env("ANYOAUTH_REDIRECT_URI", "https://your-app.example/auth/callback"));
var login = client.startLogin(params);
}
}
Gradle: implementation("com.anyoauth:anyoauth:0.1.0")Confidential backend SDKCurrent source example · published 0.1.0 predates these helpers
require "anyoauth"
client = AnyOAuth::Client.new(ENV.fetch("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), ENV.fetch("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"), ENV.fetch("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"))
# After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
login = client.start_login({"provider" => "google", "redirectUri" => ENV.fetch("ANYOAUTH_REDIRECT_URI", "https://your-app.example/auth/callback")})
gem install anyoauth-sdkConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
using System;
using System.Text.Json.Nodes;
using AnyOAuth;
// After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
using var client = new Client(Environment.GetEnvironmentVariable("ANYOAUTH_API_ORIGIN") ?? "https://api.anyoauth.com", Environment.GetEnvironmentVariable("ANYOAUTH_CLIENT_ID") ?? "YOUR_CLIENT_ID", Environment.GetEnvironmentVariable("ANYOAUTH_CLIENT_SECRET") ?? "YOUR_CLIENT_SECRET");
var login = await client.StartLogin(new JsonObject { ["provider"] = "google", ["redirectUri"] = Environment.GetEnvironmentVariable("ANYOAUTH_REDIRECT_URI") ?? "https://your-app.example/auth/callback" });
dotnet add reference /path/to/anyoauth/sdks/dotnet/AnyOAuth.SDK.csprojConfidential backend SDKCurrent source example
use anyoauth_sdk::*;
use serde_json::json;
fn env(key: &str, fallback: &str) -> String { std::env::var(key).unwrap_or_else(|_| fallback.to_owned()) }
fn main() -> Result<(), Box<dyn std::error::Error>> {
// After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
let client = Client::new(&env("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"), &env("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), &env("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"))?;
let login = client.start_login(&json!({"provider": "google", "redirectUri": env("ANYOAUTH_REDIRECT_URI", "https://your-app.example/auth/callback")}))?;
let _ = &login;
Ok(())
}
cargo add anyoauth-sdkConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
client = AnyOAuth.new((System.get_env("ANYOAUTH_CLIENT_ID") || "YOUR_CLIENT_ID"), (System.get_env("ANYOAUTH_CLIENT_SECRET") || "YOUR_CLIENT_SECRET"), (System.get_env("ANYOAUTH_API_ORIGIN") || "https://api.anyoauth.com"))
# After this call, save loginAttempt in the browser-bound server session, persist it, then redirect to url.
login = AnyOAuth.start_login(client, %{"provider" => "google", "redirectUri" => (System.get_env("ANYOAUTH_REDIRECT_URI") || "https://your-app.example/auth/callback")})
mix.exs: {:anyoauth_sdk, "~> 0.1"}Confidential backend SDKCurrent source example · published 0.1.0 predates these helpers
Save login.loginAttempt in the initiating browser’s server session, persist it,
then redirect to login.url. In your registered callback:
import { AnyOAuth } from "@anyoauth/node";
const client = new AnyOAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID ?? "YOUR_CLIENT_ID",
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET ?? "YOUR_CLIENT_SECRET",
baseUrl: process.env.ANYOAUTH_API_ORIGIN ?? "https://api.anyoauth.com",
});
// Inside your callback route: session is the initiating browser's server-side session.
// pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
const result = await client.completeLogin({
loginAttempt: session.pendingLogin
});
npm install @anyoauth/nodeConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
import os
from anyoauth import Client
client = Client(os.getenv("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), os.getenv("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"), os.getenv("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"))
# Inside your callback route: session is the initiating browser's server-side session.
# pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
result = client.complete_login({"loginAttempt": session["pendingLogin"]})
python -m pip install anyoauth-sdkConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
package main
import (
"os"
anyoauth "github.com/AnyOAuth/anyoauth-go"
)
func env(key, fallback string) string { if v := os.Getenv(key); v != "" { return v }; return fallback }
func main() {
// Inside your callback route: session is the initiating browser's server-side session.
// pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
client, err := anyoauth.NewClient(env("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"), env("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), env("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"))
if err != nil { panic(err) }
result, err := client.CompleteLogin(map[string]any{"loginAttempt": session["pendingLogin"]})
if err != nil { panic(err) }
_ = result
}
go get github.com/AnyOAuth/anyoauth-goConfidential backend SDKCurrent source example
<?php
require 'vendor/autoload.php';
$client = new \AnyOAuth\Client((getenv("ANYOAUTH_CLIENT_ID") ?: "YOUR_CLIENT_ID"), (getenv("ANYOAUTH_CLIENT_SECRET") ?: "YOUR_CLIENT_SECRET"), (getenv("ANYOAUTH_API_ORIGIN") ?: "https://api.anyoauth.com"));
// Inside your callback route: session is the initiating browser's server-side session.
// pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
$result = $client->completeLogin(["loginAttempt" => $_SESSION["pendingLogin"]]);
composer require anyoauth/anyoauthConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
import com.anyoauth.AnyOAuth;
import com.google.gson.*;
public class Example {
static String env(String key, String fallback) { String value = System.getenv(key); return value == null ? fallback : value; }
public static void main(String[] args) {
// Inside your callback route: session is the initiating browser's server-side session.
// pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
AnyOAuth client = new AnyOAuth(env("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"), env("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), env("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"));
JsonObject params = new JsonObject();
params.add("loginAttempt", session.getAsJsonObject("pendingLogin"));
var result = client.completeLogin(params);
}
}
Gradle: implementation("com.anyoauth:anyoauth:0.1.0")Confidential backend SDKCurrent source example · published 0.1.0 predates these helpers
require "anyoauth"
client = AnyOAuth::Client.new(ENV.fetch("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), ENV.fetch("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"), ENV.fetch("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"))
# Inside your callback route: session is the initiating browser's server-side session.
# pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
result = client.complete_login({"loginAttempt" => session["pendingLogin"]})
gem install anyoauth-sdkConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
using System;
using System.Text.Json.Nodes;
using AnyOAuth;
// Inside your callback route: session is the initiating browser's server-side session.
// pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
using var client = new Client(Environment.GetEnvironmentVariable("ANYOAUTH_API_ORIGIN") ?? "https://api.anyoauth.com", Environment.GetEnvironmentVariable("ANYOAUTH_CLIENT_ID") ?? "YOUR_CLIENT_ID", Environment.GetEnvironmentVariable("ANYOAUTH_CLIENT_SECRET") ?? "YOUR_CLIENT_SECRET");
var result = await client.CompleteLogin(new JsonObject { ["loginAttempt"] = session["pendingLogin"]!.DeepClone() });
dotnet add reference /path/to/anyoauth/sdks/dotnet/AnyOAuth.SDK.csprojConfidential backend SDKCurrent source example
use anyoauth_sdk::*;
use serde_json::json;
fn env(key: &str, fallback: &str) -> String { std::env::var(key).unwrap_or_else(|_| fallback.to_owned()) }
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Inside your callback route: session is the initiating browser's server-side session.
// pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
let client = Client::new(&env("ANYOAUTH_API_ORIGIN", "https://api.anyoauth.com"), &env("ANYOAUTH_CLIENT_ID", "YOUR_CLIENT_ID"), &env("ANYOAUTH_CLIENT_SECRET", "YOUR_CLIENT_SECRET"))?;
let result = client.complete_login(&json!({"loginAttempt": session["pendingLogin"].clone()}))?;
let _ = &result;
Ok(())
}
cargo add anyoauth-sdkConfidential backend SDKCurrent source example · published 0.1.0 predates these helpers
client = AnyOAuth.new((System.get_env("ANYOAUTH_CLIENT_ID") || "YOUR_CLIENT_ID"), (System.get_env("ANYOAUTH_CLIENT_SECRET") || "YOUR_CLIENT_SECRET"), (System.get_env("ANYOAUTH_API_ORIGIN") || "https://api.anyoauth.com"))
# Inside your callback route: session is the initiating browser's server-side session.
# pendingLogin is the loginAttempt you saved before redirecting. Reject a missing session/attempt.
result = AnyOAuth.complete_login(client, %{"loginAttempt" => session["pendingLogin"]})
mix.exs: {:anyoauth_sdk, "~> 0.1"}Confidential backend SDKCurrent source example · published 0.1.0 predates these helpers
Keep the attempt for pending. Remove it for terminal results; only succeeded
with a profile creates your application session. Rotate that session’s ID on login.
Do not automatically retry uncertain retrieval: start a fresh login instead.
Existing createLoginSession, loginResult, authorization-code helpers and HTTP
payloads remain compatible. API reference · Callback protection.