Published-package walkthrough
A complete login, callback, profile and logout example using the verified Node SDK release.
On this page
Install
Use Node.js 22 or newer. Install the verified SDK and the application framework’s session dependencies:
npm install @anyoauth/node@0.1.0 express express-sessionCreate an AnyOAuth project, enable Google and GitHub, and register the exact
http://localhost:3000/auth/callback URL. Configure ANYOAUTH_CLIENT_ID,
ANYOAUTH_CLIENT_SECRET and a private SESSION_SECRET of at least 32 characters
in the backend’s secret environment. No secret belongs in frontend code.
Backend
Save the following as server.mjs. The example uses the actual 0.1.0 methods:
createTransaction, authorizationUrl, validateCallback, exchangeCode,
profile and revoke.
// server.mjs — @anyoauth/node 0.1.0, Node.js 22+
import express from 'express';
import session from 'express-session';
import { AnyOAuth } from '@anyoauth/node';
const app = express();
const origin = "http://localhost:3000";
const redirectUri = "http://localhost:3000/auth/callback";
if (!process.env.SESSION_SECRET || process.env.SESSION_SECRET.length < 32) {
throw new Error('Set a private SESSION_SECRET of at least 32 characters.');
}
if (origin.startsWith('https://')) app.set('trust proxy', 1);
app.use(session({
name: 'ao_app',
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, sameSite: 'lax', secure: origin.startsWith('https://'), maxAge: 86400000 },
// For production, configure a persistent Express session store.
}));
const client = new AnyOAuth({
clientId: process.env.ANYOAUTH_CLIENT_ID,
clientSecret: process.env.ANYOAUTH_CLIENT_SECRET,
});
const save = req => new Promise((resolve, reject) => req.session.save(error => error ? reject(error) : resolve()));
app.get("/auth/login/:provider", async (req, res) => {
try {
const provider = req.params.provider;
if (!['google', 'github'].includes(provider)) return res.sendStatus(400);
const transaction = await client.createTransaction();
req.session.loginTransaction = transaction;
await save(req);
res.redirect(client.authorizationUrl({ provider, redirectUri, state: transaction.state, codeChallenge: transaction.codeChallenge }));
} catch { res.status(400).json({ error: 'sign_in_failed' }); }
});
app.get("/auth/callback", async (req, res) => {
try {
const transaction = req.session.loginTransaction;
if (!transaction) return res.status(400).json({ error: 'missing_login_transaction' });
const callback = client.validateCallback({
callbackUrl: new URL(req.originalUrl, origin).href,
redirectUri, state: transaction.state, expiresAt: transaction.expiresAt,
});
delete req.session.loginTransaction;
await save(req);
if ('error' in callback) return res.status(400).json({ error: 'sign_in_denied' });
const token = await client.exchangeCode({ code: callback.code, codeVerifier: transaction.codeVerifier, redirectUri });
let profile;
try { profile = await client.profile({ accessToken: token.access_token }); }
finally { await client.revoke({ accessToken: token.access_token }).catch(() => {}); }
await new Promise((resolve, reject) => req.session.regenerate(error => error ? reject(error) : resolve()));
req.session.profile = profile;
await save(req);
res.redirect('/');
} catch { res.status(400).json({ error: 'sign_in_failed' }); }
});
app.get("/auth/profile", (req, res) => {
res.set('Cache-Control', 'no-store');
if (!req.session.profile) return res.sendStatus(401);
res.json(req.session.profile);
});
app.post("/auth/logout", (req, res) => {
if (req.get('origin') !== origin) return res.sendStatus(403);
req.session.destroy(error => {
if (error) return res.sendStatus(500);
res.clearCookie('ao_app', { path: '/', httpOnly: true, sameSite: 'lax', secure: origin.startsWith('https://') });
res.sendStatus(204);
});
});
app.listen(Number(process.env.PORT || 3000));
Run node server.mjs. This server owns the initiating browser’s login transaction,
validates state/PKCE, redeems the code once, reads the normalized profile and creates
your application’s session. It regenerates the session ID on login and checks the
request origin on logout. Provider tokens and the client secret are not returned
to the browser.
Production configuration: use a persistent Express session store, configure trusted proxies for your deployment, set your HTTPS origin and exact registered callback, and serve your frontend on that origin. The default in-memory store is for local development. Keep any return page fixed or in your server session.
Frontend
Use these same-origin routes from HTML or your frontend framework. You do not need the browser SDK for buttons that navigate to backend login routes. Remove a button if that provider is disabled in your project.
<a href="/auth/login/google">Continue with Google</a>
<a href="/auth/login/github">Continue with GitHub</a>
<p id="anyoauth-profile"></p>
<button id="anyoauth-logout" hidden>Sign out</button>
<script type="module">
// Same-origin backend routes; no client secret or browser SDK is needed here.
const response = await fetch("/auth/profile", { credentials: 'same-origin' });
if (response.ok) {
const profile = await response.json();
document.querySelector('#anyoauth-profile').textContent = 'Signed in as ' + (profile.name ?? profile.username ?? profile.subject);
document.querySelector('#anyoauth-logout').hidden = false;
} else if (response.status !== 401) {
document.querySelector('#anyoauth-profile').textContent = 'Could not load your session.';
}
document.querySelector('#anyoauth-logout').addEventListener('click', async () => {
const result = await fetch("/auth/logout", { method: 'POST', credentials: 'same-origin' });
if (result.ok) window.location.reload();
});
</script>For React, Vue, Svelte, Astro, Next.js or Nuxt, the same three actions are:
- Navigate to
/auth/login/googleor/auth/login/github. - Fetch
/auth/profileto read the application session;401means signed out. - POST
/auth/logoutfrom the same origin, then refresh the UI.
Use a development proxy when your frontend and backend run on separate ports.
profile.subject is the stable user ID; names, usernames and emails may be null.
Your application decides authorization and account linking.
Other frameworks and languages
The Express routes are an application example, not exports from the SDK. With Hono,
Workers, Next.js or Astro server routes, use your framework’s session storage and
the same published SDK authorization-code methods. The exact registered callback
must be preserved. Do not import @anyoauth/node/auth or @anyoauth/node/express
from 0.1.0: those convenience entrypoints are not in that published release.
Install commands for every language · Registry versions and repositories.
Version boundary
The published packages use the initial 0.1.0 contract. Managed createAuth
adapters, startLogin/completeLogin, and the named browser session helpers are
newer source-only APIs. Do not combine their examples with these registry installs.
The dashboard shows them only in a separate source-only examples view.