oauth
Val Town is a collaborative website to build and scale JavaScript apps.
Deploy APIs, crons, & store data – all from the browser, and deployed in milliseconds.
example.tsx
https://std--91178458b42e11f0b6f30224a6c84d84.web.val.run
OAuth authentication middleware for Val Town vals.
- OAuth 2.0 Authorization Code flow with PKCE
- Dynamic client registration
- Encrypted session cookies (stateless)
- No database required
/** @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:
- Handler only (backwards compatible):
oauthMiddleware(appFetch) - Options first (Deno.serve style):
oauthMiddleware(options, appFetch)
Options:
scopes?: string[]- OAuth scopes (default:["openid", "offline_access", "profile", "user_rw"])clientName?: string- OAuth client name
Auto-handled routes:
/auth/login- Start OAuth flow/auth/callback- OAuth callback/auth/logout- Clear session
Extract 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- Auto-generated if not set
- Set manually (e.g.,
openssl rand -base64 32) for better performance
- User clicks
/auth/login - Redirects to Val Town OAuth
- User authorizes
- Callback receives code, exchanges for tokens
- User data fetched from
/v1/meAPI using access token - Session encrypted and stored in cookie
- Use
getOAuthUserData(req)to access user data
Sessions last 30 days and are stored as encrypted cookies (no server-side storage).