GitHub login
GitHub login lets Auth redirect a user to GitHub, verify the OAuth callback, read the authenticated GitHub profile, link the GitHub identity, and create a Layeron Auth session.
Auth stores the OAuth state hash, callback URL, and optional redirectTo value
in the Auth state database. GitHub profile data is stored in the Auth identity
record.
Configure GitHub
Section titled “Configure GitHub”Create a GitHub OAuth app and register the callback URL that your backend route uses.
import { auth } from "@layeron/modules"
const appAuth = auth({ providers: [ { provider: "github", clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, redirectToAllowlist: ["https://app.example.com"], }, ],})GitHub login requires clientId and clientSecret. The default scopes are
read:user and user:email so Auth can read the profile and verified primary
email address.
Start Login
Section titled “Start Login”Create the GitHub authorization URL from a public route, then redirect the browser to it.
app.get("/auth/github/start", { auth: "public" }, async () => { const result = await appAuth.oauth.createAuthorizationUrl({ provider: "github", callbackUrl: "https://api.example.com/auth/github/callback", redirectTo: "https://app.example.com/dashboard", })
return Response.redirect(result.authorizationUrl, 302)})Auth creates a one-time state value and stores only its hash. The state default
lifetime is 10m.
Verify Callback
Section titled “Verify Callback”Pass the GitHub authorization code and state back to Auth.
app.get("/auth/github/callback", { auth: "public" }, async ({ request }) => { const url = new URL(request.url) const result = await appAuth.oauth.verifyCallback({ provider: "github", code: url.searchParams.get("code") ?? "", state: url.searchParams.get("state") ?? "", callbackUrl: "https://api.example.com/auth/github/callback", })
return Response.redirect(result.redirectTo ?? "/", 302)})Auth exchanges the code at GitHub, fetches /user and /user/emails, chooses
the verified primary email when GitHub returns one, writes or updates the GitHub
identity, and creates a Layeron Auth session.
User Storage Behavior
Section titled “User Storage Behavior”In managed and managed_core mode, Auth creates the user row when the GitHub
identity is first seen. Auth stores emailVerifiedAt only when GitHub returns a
verified email address.
In custom, mapped, and external mode, Auth uses github:<github-user-id>
as the application user id. Your user resolver or mapped user table must return
a user for that id before Auth creates the session.
Auth links repeat logins by the provider id github and the stable GitHub user
id. Auth does not automatically link a new GitHub identity to an existing user
by email address.
Redirect Rules
Section titled “Redirect Rules”redirectTo may be a relative path such as /dashboard. Absolute URLs must use
HTTPS and must match an origin in redirectToAllowlist.