Token-based authentication utilities for React Native / Expo apps.
- JWT token storage with automatic refresh
- React Context provider for auth state
- Configurable API endpoints
- Works with
vayu-storagefor secure token storage
npm install vayu-auth vayu-storage expo-secure-storeimport { AuthProvider } from 'vayu-auth';
const authConfig = {
apiBaseUrl: 'https://api.myapp.com',
endpoints: {
refresh: '/api/auth/refresh',
logout: '/api/auth/logout',
me: '/api/users/me',
},
// Optional: transform API response to your user type
transformUser: (data) => ({
id: data.id,
email: data.email,
name: data.first_name + ' ' + data.last_name,
}),
};
export default function App() {
return (
<AuthProvider config={authConfig}>
<YourApp />
</AuthProvider>
);
}import { useAuth } from 'vayu-auth';
function ProfileScreen() {
const { authState, logout } = useAuth();
if (!authState.isAuthenticated) {
return <LoginScreen />;
}
return (
<View>
<Text>Welcome, {authState.user?.name}</Text>
<Button onPress={logout} title="Logout" />
</View>
);
}import { useAuth } from 'vayu-auth';
function LoginScreen() {
const { login } = useAuth();
const handleLogin = async () => {
// After your OAuth flow completes...
const { token, expiresAt, sessionId, user } = await myOAuthFlow();
await login(token, expiresAt, sessionId, user);
};
return <Button onPress={handleLogin} title="Login" />;
}import { createAuthService } from 'vayu-auth';
const authService = createAuthService({
apiBaseUrl: 'https://api.myapp.com',
endpoints: {
refresh: '/api/auth/refresh',
logout: '/api/auth/logout',
me: '/api/users/me',
},
});
// Get token for API calls
const token = await authService.getAuthToken();
// Check auth status
const isLoggedIn = await authService.isAuthenticated();interface AuthConfig {
// Base URL for auth API endpoints
apiBaseUrl: string;
// Endpoint paths (relative to apiBaseUrl)
endpoints: {
refresh: string; // POST - refresh token
logout: string; // POST - logout
me: string; // GET - fetch current user
};
// Storage key prefix (default: 'auth')
storagePrefix?: string;
// Seconds before expiry to trigger refresh (default: 60)
refreshGracePeriod?: number;
// Transform user data from API response
transformUser?: (data: any) => any;
}{
"jwt_token": "new.jwt.token",
"expires_at": 1234567890,
"session_id": "optional-session-id"
}Returns user data (transformed by transformUser if provided).
MIT