github-oauth-template
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.
This directory contains the backend implementation for the GitHub OAuth template using Hono framework.
index.ts
- Main Hono application with OAuth routes and API endpointsgithub.ts
- GitHub API client for server-side requests
- Login:
/auth/login
- Initiates GitHub OAuth flow - Callback:
/auth/callback
- Handles OAuth callback and token exchange - Logout:
/auth/logout
- Clears authentication cookies
- User Profile:
GET /api/user
- Returns authenticated user's GitHub profile - Repositories:
GET /api/repos
- Returns user's repositories - Health Check:
GET /health
- Application health status
- HTTP-only Cookies: Tokens stored securely, not accessible to JavaScript
- CSRF Protection: State parameter validation during OAuth flow
- Secure Cookies: HTTPS-only transmission with SameSite protection
- Token Validation: Automatic cleanup of invalid tokens
The application uses custom cookie helper functions since Hono's cookie helpers had import issues:
// Get cookie value
const token = getCookie(c, "github_token");
// Set secure cookie
setCookie(c, "github_token", accessToken, {
httpOnly: true,
secure: true,
sameSite: "Lax",
maxAge: 60 * 60 * 24 * 30 // 30 days
});
// Delete cookie
deleteCookie(c, "github_token");
Required environment variables:
GITHUB_CLIENT_ID
- GitHub OAuth app client IDGITHUB_CLIENT_SECRET
- GitHub OAuth app client secret
The application includes comprehensive error handling:
- OAuth errors are displayed with user-friendly messages
- Invalid tokens are automatically cleared
- API errors return appropriate HTTP status codes
- All errors bubble up with full context for debugging
The GitHubAPI
class provides a clean interface for GitHub API requests:
const github = new GitHubAPI(accessToken);
const user = await github.getUser();
const repos = await github.getRepos();
All requests include proper headers and error handling.