@tenminuteschool/auth-react
v0.4.0
Published
OAuth 2.0 + PKCE browser client for Login with 10MinuteSchool
Downloads
452
Readme
@tenminuteschool/auth-react
"Login with 10MinuteSchool" for React and Next.js apps.
Drop in a login button, get back a user session. No auth system required.
Requirements
- A Client ID — get one by registering your app with 10MinuteSchool
- React ≥ 16.8 (hooks required)
- Your app's domain must be registered as an allowed origin for your Client ID
Installation
npm install @tenminuteschool/auth-react
# or
pnpm add @tenminuteschool/auth-reactQuick Start
1. Create the auth instance (once, at app level)
// lib/auth.ts
import { TenMSAuth } from '@tenminuteschool/auth-react';
export const auth = new TenMSAuth({ clientId: 'YOUR_CLIENT_ID' });2. Add the login button
'use client'; // Next.js only
import { LoginButton } from '@tenminuteschool/auth-react';
import type { AuthResponse } from '@tenminuteschool/auth-react';
import { auth } from '@/lib/auth';
export function LoginSection() {
async function handleLoginSuccess(response: AuthResponse) {
const session = await auth.handleLoginSuccess(response);
console.log(session.user); // { sub, name, email, ... }
}
return (
<LoginButton
clientId="YOUR_CLIENT_ID"
onSuccess={handleLoginSuccess}
onError={(err) => console.error(err)}
/>
);
}3. Use the session anywhere
import { auth } from '@/lib/auth';
// Get the current user (sync, reads from storage)
const user = auth.getUser();
// Get a valid access token for API calls (async, auto-refreshes if expired)
const token = await auth.getAccessToken();
// Check login status (sync)
const loggedIn = auth.isLoggedIn();
// Logout (revokes token + clears storage)
await auth.logout();4. Make authenticated API calls
const token = await auth.getAccessToken();
const res = await fetch('https://api.example.com/data', {
headers: { Authorization: `Bearer ${token}` },
});Configuration
new TenMSAuth(config)
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| clientId | string | required | Your registered client ID |
| redirectUri | string | window.location.origin | OAuth callback URL. Only needed if you want a custom path |
| storage | 'cookie' \| 'localStorage' | 'cookie' | Where to persist the session. Use cookie for SSR/Next.js, localStorage for pure SPAs |
| scopes | string[] | ['profile'] | OAuth scopes to request |
| debug | boolean | false | Logs each OAuth step to the console |
<LoginButton /> props
| Prop | Type | Default | Description |
|------|------|---------|-------------|
| clientId | string | required | Your registered client ID |
| onSuccess | (response: AuthResponse) => void | — | Called after the user logs in. Pass the response to auth.handleLoginSuccess() |
| onError | (error: Error) => void | — | Called on failure |
| theme | 'dark' \| 'light' | 'dark' | Button color scheme |
| variant | 'fill' \| 'outline' | 'fill' | Button style |
| size | 'small' \| 'medium' \| 'large' | 'large' | Button size |
| text | string | 'Login with 10MinuteSchool' | Button label |
| redirectUri | string | window.location.origin | Override the redirect URI |
| className | string | '' | Extra CSS class for layout |
Session Methods
All session data is persisted to the configured storage (cookie by default) and survives page refresh.
auth.handleLoginSuccess(response)
Exchanges the authorization code for tokens, fetches the user profile, and saves everything to storage. Returns { user, accessToken }.
const session = await auth.handleLoginSuccess(response);
// session.user → UserInfo
// session.accessToken → stringauth.getAccessToken()
Returns a valid access token. Automatically refreshes if the current token is expired and a refresh token is available. Returns null if the user is not logged in.
const token = await auth.getAccessToken(); // string | nullauth.getUser()
Returns the stored user profile synchronously. Returns null if not logged in.
const user = auth.getUser();
// { sub, name, email, phone, picture, email_verified, phone_verified }auth.isLoggedIn()
Returns true if a non-expired access token exists in storage. Synchronous, no network call.
if (auth.isLoggedIn()) { ... }auth.logout()
Revokes the access token on the server and clears all session data from storage.
await auth.logout();User Profile Shape
interface UserInfo {
sub: string; // unique user ID — always present
name?: string;
email?: string;
phone?: string;
picture?: string;
email_verified?: boolean;
phone_verified?: boolean;
}Error Handling
All SDK errors are instances of TenMSAuthError with a stable code field:
import { TenMSAuthError } from '@tenminuteschool/auth-react';
try {
await auth.handleLoginSuccess(response);
} catch (err) {
if (err instanceof TenMSAuthError) {
switch (err.code) {
case 'popup_blocked': // user needs to allow popups
case 'token_exchange_failed': // server rejected the code
case 'userinfo_failed': // couldn't fetch profile
}
}
}Common error codes:
| Code | When |
|------|------|
| popup_blocked | Browser blocked the login popup |
| token_exchange_failed | Server rejected the authorization code |
| userinfo_failed | Failed to fetch user profile |
| missing_client_id | clientId not provided |
| missing_redirect_uri | redirectUri needed but not set and window unavailable |
| state_mismatch | Possible CSRF — state param didn't match |
Full Next.js Example
// app/login/page.tsx
'use client';
import { useEffect, useState } from 'react';
import { LoginButton, TenMSAuth } from '@tenminuteschool/auth-react';
import type { AuthResponse, UserInfo } from '@tenminuteschool/auth-react';
const auth = new TenMSAuth({ clientId: 'YOUR_CLIENT_ID' });
export default function LoginPage() {
const [user, setUser] = useState<UserInfo | null>(null);
useEffect(() => {
setUser(auth.getUser());
}, []);
async function handleLoginSuccess(response: AuthResponse) {
const session = await auth.handleLoginSuccess(response);
setUser(session.user);
}
async function handleLogout() {
await auth.logout();
setUser(null);
}
if (user) {
return (
<div>
<p>Logged in as {user.name ?? user.email}</p>
<button onClick={handleLogout}>Log out</button>
</div>
);
}
return (
<LoginButton
clientId="YOUR_CLIENT_ID"
theme="dark"
onSuccess={handleLoginSuccess}
onError={(err) => console.error(err)}
/>
);
}Storage
| Storage | Survives refresh | SSR readable | Recommended for |
|---------|-----------------|--------------|-----------------|
| cookie (default) | Yes | Yes | Next.js, SSR apps |
| localStorage | Yes | No | Pure client-side SPAs |
What gets stored:
| Key | Value |
|-----|-------|
| _tenms_access_token | OAuth access token |
| _tenms_refresh_token | OAuth refresh token (if issued) |
| _tenms_expires_at | Token expiry as Unix timestamp |
| _tenms_user | JSON-serialized user profile |
Plain HTML / No Bundler
<script src="https://cdn.10minuteschool.com/sdk/tenms-auth.umd.js"></script>
<tenms-login-button
client-id="YOUR_CLIENT_ID"
theme="dark"
></tenms-login-button>
<script>
document.querySelector('tenms-login-button')
.addEventListener('tenms-success', async (e) => {
const auth = new TenMSAuth.TenMSAuth({ clientId: 'YOUR_CLIENT_ID' });
const session = await auth.handleLoginSuccess(e.detail);
console.log(session.user);
});
</script>