A comprehensive Firebase Authentication library for SvelteKit applications. Provides both server-side API proxy and client-side authentication state management.
npm install sveltefireauth
// src/hooks.server.ts
import { createAuthHandle } from 'sveltefireauth/server';
export const handle = createAuthHandle({
firebaseApiKey: 'YOUR_FIREBASE_API_KEY',
apiPath: '/api/auth' // optional, default: '/api/auth'
});
// src/routes/+layout.svelte
<script lang="ts">
import { initAuth } from 'sveltefireauth/client';
import { onMount } from 'svelte';
onMount(() => {
initAuth({
mode: 'proxy',
proxyPath: '/api/auth',
persistence: true,
autoRefresh: true
});
});
</script>
<!-- src/routes/login/+page.svelte -->
<script lang="ts">
import { authStore } from 'sveltefireauth/client';
let email = '';
let password = '';
async function handleLogin() {
try {
await authStore.signIn(email, password);
// Redirect on success
} catch (error) {
console.error('Login failed:', error);
}
}
</script>
{#if $authStore.loading}
<p>Loading...</p>
{:else if $authStore.isAuthenticated}
<p>Welcome, {$authStore.user?.email}!</p>
<button on:click={() => authStore.signOut()}>Sign Out</button>
{:else}
<form on:submit|preventDefault={handleLogin}>
<input type="email" bind:value={email} placeholder="Email" />
<input type="password" bind:value={password} placeholder="Password" />
<button type="submit">Login</button>
</form>
{/if}
{#if $authStore.error}
<p class="error">{$authStore.error.message}</p>
{/if}
For detailed documentation, see:
createAuthHandle(config)
Creates a SvelteKit handle for authentication.
Config Options:
firebaseApiKey
(required): Your Firebase API keyapiPath
(optional): API path prefix (default: /api/auth
)enableCallback
(optional): Enable callback handling (default: true
)callbackPath
(optional): Callback path (default: __/auth/action
)responseTransformer
(optional): Custom response transformerFor manual integration:
handleSignUp(config)
- User registrationhandleSignIn(config)
- User loginhandleRefreshToken(config)
- Token refreshhandleGetUser(config)
- Get user infohandleUpdateUser(config)
- Update profilehandleDeleteUser(config)
- Delete accounthandlePasswordReset(config)
- Password resethandleVerifyEmail(config)
- Email verificationinitAuth(config)
Initialize the auth store.
Config Options:
mode
(required): 'direct'
or 'proxy'
apiKey
(optional): Firebase API key (required for direct mode)proxyPath
(optional): Proxy path (default: /api/auth
)persistence
(optional): Enable localStorage (default: false
)autoRefresh
(optional): Auto refresh tokens (default: false
)authStore
Svelte store for authentication state.
State:
user
: Current user objectloading
: Loading stateerror
: Error objectisAuthenticated
: Authentication statusMethods:
signUp(email, password)
- Register new usersignIn(email, password)
- Sign in usersignOut()
- Sign out userupdateProfile(data)
- Update user profilesendPasswordResetEmail(email)
- Send password resetdeleteAccount()
- Delete user accountgetIdToken()
- Get current ID token// src/routes/api/auth/signup/+server.ts
import { handleSignUp } from 'sveltefireauth/server';
export const POST = handleSignUp({
firebaseApiKey: process.env.FIREBASE_API_KEY!,
responseTransformer: (data) => ({
success: true,
user: {
id: data.localId,
email: data.email
}
})
});
// src/hooks.server.ts
import { createAuthGuard } from 'sveltefireauth/server';
export const handle = createAuthGuard({
protectedRoutes: ['/dashboard', '/profile'],
redirectTo: '/login',
verify: async (event) => {
const token = event.cookies.get('token');
return !!token;
}
});
import { FirebaseAuthClient } from 'sveltefireauth/client';
const client = new FirebaseAuthClient({
apiKey: 'YOUR_FIREBASE_API_KEY',
mode: 'direct'
});
const result = await client.signIn({
email: '[email protected]',
password: 'password123'
});
# Install dependencies
npm install
# Start development server
npm run dev
# Build library
npm run build
# Run type checking
npm run check
MIT
Contributions are welcome! Please read our contributing guidelines first.