• Blog
  • Docs
  • Pricing
  • We’re hiring!
Log inSign up
std

std

oauth

Login with Val Town OAuth Middleware
Unlisted
Like
1
oauth
Home
Code
7
README.md
TESTING.md
crypto.ts
H
example.tsx
middleware.ts
oauth.ts
session.ts
Branches
1
Pull requests
Remixes
History
Environment variables
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.
Sign up now
Code
/
README.md
Code
/
README.md
Search
10/29/2025
Viewing readonly version of main branch: v170
View latest version
README.md

Login with Val Town OAuth Middleware

OAuth authentication middleware for Val Town vals.

Features

  • OAuth 2.0 Authorization Code flow with PKCE
  • Dynamic client registration
  • Encrypted session cookies (stateless)
  • No database required

Usage

Create val
/** @jsxImportSource https://esm.sh/hono/jsx */ import { Hono } from "https://esm.sh/hono"; import { getOAuthUserData, oauthMiddleware, } from "https://esm.town/v/std/oauth/middleware"; const app = new Hono(); app.get("/", async (c) => { const user = await getOAuthUserData(c.req.raw); return c.html( <html> <body> {user ? <p>Logged in as {user.username}</p> : <a href="/auth/login">Log in</a>} </body> </html>, ); }); export default oauthMiddleware(app.fetch);

API

oauthMiddleware(appFetch, options?)

Wraps your application to handle OAuth routes.

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

getOAuthUserData(req: Request)

Extract user data from session cookie.

Returns: SessionData | null

interface SessionData { userId: string; username: string; accessToken: string; refreshToken?: string; idToken?: string; expiresAt: number; }

Environment Variables

  • 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

How It Works

  1. User clicks /auth/login
  2. Redirects to Val Town OAuth
  3. User authorizes
  4. Callback receives code, exchanges for tokens
  5. User data fetched from /v1/me API using access token
  6. Session encrypted and stored in cookie
  7. Use getOAuthUserData(req) to access user data

Sessions last 30 days and are stored as encrypted cookies (no server-side storage).

FeaturesVersion controlCode intelligenceCLIMCP
Use cases
TeamsAI agentsSlackGTM
DocsShowcaseTemplatesNewestTrendingAPI examplesNPM packages
PricingNewsletterBlogAboutCareers
We’re hiring!
Brandhi@val.townStatus
X (Twitter)
Discord community
GitHub discussions
YouTube channel
Bluesky
Open Source Pledge
Terms of usePrivacy policyAbuse contact
© 2025 Val Town, Inc.