OAuth authentication middleware for Val Town vals.
/** @jsxImportSource https://esm.sh/hono/jsx */
import { Hono } from "https://esm.sh/hono";
import {
getOAuthUserData,
oauthMiddleware,
} from "https://esm.town/v/std/oauth/middleware.ts";
const app = new Hono();
app.get("/", async (c) => {
const session = await getOAuthUserData(c.req.raw);
return c.html(
<html>
<body>
{session?.user
? <p>Logged in as {session.user.username}</p>
: <a href="/auth/login">Log in</a>}
</body>
</html>,
);
});
// Simple usage with defaults
export default oauthMiddleware(app.fetch);
Wraps your application to handle OAuth routes. Supports two calling styles:
oauthMiddleware(appFetch)oauthMiddleware(options, appFetch)Options:
scopes?: string[] - OAuth scopes (default:
["openid", "offline_access", "profile", "user_rw"])clientName?: string - OAuth client nameAuto-handled routes:
/auth/login - Start OAuth flow/auth/callback - OAuth callback/auth/logout - Clear sessionExtract user data from session cookie.
Returns: SessionData | null
interface SessionData {
user: {
id: string;
bio: string | null;
email: string | null;
links: {
self: string;
profileImageUrl: string | null;
};
tier: "free" | "pro" | null;
type: "user" | "org";
url: string;
username: string | null;
};
accessToken: string;
refreshToken?: string;
idToken?: string;
expiresAt: number;
}
OAUTH_STATE_ENCRYPTION_KEY (optional) - Encryption key for state and
sessions
openssl rand -base64 32) for better performance/auth/login/v1/me API using access tokengetOAuthUserData(req) to access user dataSessions last 30 days and are stored as encrypted cookies (no server-side storage).