SDK Authentication
The dypai.auth module provides a complete way to handle user registration, login, and session management. It automatically handles token persistence in localStorage, background token refresh, cross-tab synchronization, and email verification callbacks.
Need help choosing the product flow first?
If you are deciding whether your app should support signup, invitation-only onboarding, or backend-only integrations, read Auth Flows first.
Email & Password
Sign Up (Registration)
const { data, error } = await dypai.auth.signUp({
email: 'user@example.com',
password: 'secure-password',
full_name: 'John Doe' // extra fields auto-forwarded to user_metadata
});
if (error) {
console.error(error.message);
return;
}
if (data.confirmationRequired) {
// Email confirmation is enabled β user must verify their email
showMessage('Check your inbox to confirm your email');
} else {
// Email confirmation disabled β user is logged in immediately
console.log('Logged in:', data.user);
}
Email confirmation is enabled by default. When active, signUp() creates the user but does NOT start a session. The user must click the confirmation link sent to their email before they can log in.
Extra fields like full_name, username, or any custom data are automatically merged into user_metadata. You can also pass them explicitly via user_data:
await dypai.auth.signUp({
email, password,
user_data: { full_name: 'John Doe', company: 'Acme' }
});
Sign In
const { data, error } = await dypai.auth.signInWithPassword({
email: 'user@example.com',
password: 'secure-password'
});
if (error) {
// If user hasn't confirmed email, error.status will be 400
console.error(error.message);
return;
}
console.log('Logged in:', data.user);
signInWithPassword() will fail with a 400 error if the user hasn't confirmed their email yet. Show a message like "Please confirm your email first" and offer to resend the confirmation email.
Resend Confirmation Email
If a user didn't receive their confirmation email or the link expired:
const { data, error } = await dypai.auth.resendConfirmationEmail('user@example.com');
if (!error) {
showMessage('Confirmation email resent β check your inbox');
}
Email Verification & Callbacks
When a user clicks a confirmation link, magic link, or password reset link from their email, the auth server redirects back to your app with tokens in the URL hash:
https://your-app.com/#access_token=eyJ...&refresh_token=xxx&type=signup
For private app invitations, use the same callback pattern with type=invite:
https://your-app.com/#access_token=eyJ...&refresh_token=xxx&type=invite
The SDK handles this automatically. On initialization, it:
- Checks
window.location.hashfor auth callback tokens. - If found: fetches user data, establishes the session, and cleans the URL.
- Emits the appropriate event:
SIGNED_INorPASSWORD_RECOVERY.
No extra code needed β just listen for auth events:
dypai.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') {
router.push('/dashboard');
}
if (event === 'PASSWORD_RECOVERY') {
router.push('/reset-password');
}
});
Invitations (Private Apps)
For B2B/private apps, invitation UX should live in the customer app (not DYPAI dashboard):
- Your backend generates an invite link via the auth system (
type=invite). redirect_tomust point to a route in the customer app (for example/auth/callback).- That route must be allowed in the auth redirect allowlist.
- SDK detects invite callback and emits
PASSWORD_RECOVERY. - Show a "Set password" form and call
dypai.auth.setPassword(...).
dypai.auth.onAuthStateChange(async (event) => {
if (event === 'PASSWORD_RECOVERY') {
await dypai.auth.setPassword('new-secure-password');
}
});
Passwordless (OTP)
Email OTP
// 1. Send a 6-digit code to the user's email
await dypai.auth.signInWithOtp({
email: 'user@example.com',
create_user: true // auto-register if user doesn't exist
});
// 2. User enters the code
const { data, error } = await dypai.auth.verifyOtp({
email: 'user@example.com',
token: '123456',
type: 'magiclink' // always 'magiclink' for email OTP
});
Phone (SMS) OTP
// 1. Send a 6-digit code via SMS
await dypai.auth.signInWithOtp({
phone: '+34600000000',
create_user: true
});
// 2. User enters the code
const { data, error } = await dypai.auth.verifyOtp({
phone: '+34600000000',
token: '123456',
type: 'sms' // always 'sms' for phone OTP
});
OTP type must match the flow. Use 'magiclink' for email OTP, 'sms' for phone OTP, and 'signup' for signup confirmation codes. Using the wrong type will cause verification to fail.
OAuth
Redirect users to sign in with their Google, GitHub, or other OAuth accounts:
await dypai.auth.signInWithOAuth('google', {
redirectTo: 'https://your-app.com/auth/callback',
scopes: ['email', 'profile'] // optional
});
This redirects the browser to the OAuth provider. When the user returns to your app, the SDK automatically picks up the session from the URL callback.
Password Recovery
// 1. Send a password reset email
await dypai.auth.resetPasswordForEmail('user@example.com');
// 2. User clicks the link in the email β SDK auto-detects the recovery token
dypai.auth.onAuthStateChange(async (event, session) => {
if (event === 'PASSWORD_RECOVERY') {
// Show "set new password" form, then:
const { data, error } = await dypai.auth.updateUser({
password: 'new-secure-password'
});
}
});
Session & User
Get Session
const { data: session, error } = await dypai.auth.getSession();
if (session) {
console.log('Token:', session.access_token);
console.log('User:', session.user);
}
getSession() waits for the SDK initialization to complete before responding, so it's safe to call on page load without race conditions.
Get Current User
const { data: user, error } = await dypai.auth.getUser();
// or the shorthand alias:
const { data: user, error } = await dypai.me();
Quick Sync Check
if (dypai.auth.isLoggedIn()) {
// User has an active session
}
isLoggedIn() is synchronous and may return false during SDK initialization. For a reliable check at startup, use await dypai.auth.getSession() or onAuthStateChange instead.
User Object and Role
The SDK normalizes the user object so your app role is always accessible as user.role:
const { data: user } = await dypai.auth.getUser();
user.id // User UUID
user.email // email
user.role // "admin", "editor", "viewer", etc. β your app role
user.confirmed_at // null if email not confirmed
user.role is always your application role, not the auth engine's internal role. Internally, the auth server stores the role in app_metadata.role. The SDK automatically extracts it to user.role so you don't need to access user.app_metadata.role manually. This applies to both dypai.auth.getUser() and dypai.users.list().
User Profile
// Read current user
const user = dypai.auth.user;
console.log(user.email, user.confirmed_at);
// Update user metadata
await dypai.auth.updateUser({
data: {
full_name: 'John Doe',
avatar_url: 'https://example.com/avatar.jpg'
}
});
Auth State Listener
React to authentication changes in real time:
const { data: { subscription } } = dypai.auth.onAuthStateChange((event, session) => {
switch (event) {
case 'INITIAL_SESSION':
// Fired on SDK init β session recovered from storage (or null)
break;
case 'SIGNED_IN':
// User logged in (password, OTP, OAuth, or email link callback)
break;
case 'SIGNED_OUT':
// User logged out or session expired
break;
case 'TOKEN_REFRESHED':
// Access token silently refreshed in background
break;
case 'USER_UPDATED':
// Profile or password changed via updateUser()
break;
case 'PASSWORD_RECOVERY':
// User arrived via password reset link β show new password form
break;
}
});
// To unsubscribe later:
subscription.unsubscribe();
Sign Out
await dypai.auth.signOut();
Method Reference
| Method | Description |
|---|---|
signUp(data) | Register a new user. Returns confirmationRequired flag. |
signInWithPassword(credentials) | Login with email and password. |
signInWithOtp(options) | Send OTP code via email or phone. |
verifyOtp(params) | Verify an OTP code and start a session. |
signInWithOAuth(provider, options) | Redirect to OAuth provider (Google, GitHub, etc.). |
getSession() | Get the current session (async, waits for init). |
getUser() | Fetch current user data from server. |
isLoggedIn() | Sync check if a session exists. |
updateUser(attributes) | Update email, password, or user metadata. |
setPassword(password) | Set/update password for the current authenticated user (invite/recovery flows). |
resetPasswordForEmail(email) | Send a password reset email. |
resendConfirmationEmail(email) | Resend the signup confirmation email. |
onAuthStateChange(callback) | Listen for auth state changes. |
signOut() | Clear the session and log out. |
refreshSession() | Manually refresh the access token. |
Aliases: login() = signInWithPassword(), register() = signUp(), logout() = signOut(), recoverPassword() = resetPasswordForEmail(), me() = getUser().