Svelte + Routify + Firebase setup

Guillaume Duhan
2 min readMar 28, 2021

--

Svelte, Routify & Firebase

Svelte is an amazing JavaScript framework that you can find here. In this article, I’ll explain how you can plug Svelte with Firebase & manage authentication.

1. Svelte / Routify

Routify offers a great developer experience to build the routes for your Svelte app. Let’s use Routify and its starter template.

npx @roxi/routify init
npm add -D firebase && npm run dev

2. Firebase setup

Create src/auth/index.js:

import firebase from 'firebase/app';
import 'firebase/auth';
import { firebaseConfig } from "../auth/config.js";
import { readable } from 'svelte/store';

firebase.initializeApp(firebaseConfig);

const userMapper = claims => ({
id: claims.user_id,
name: claims.name,
email: claims.email,
picture: claims.picture
});

export const initAuth = (useRedirect = false) => {
const auth = firebase.auth();

const loginWithEmailPassword = (email, password) =>
auth.signInWithEmailAndPassword(email, password);

const loginWithGoogle = () => {
const provider = new firebase.auth.GoogleAuthProvider();
if (useRedirect) {
return auth.signInWithRedirect(provider);
} else {
return auth.signInWithPopup(provider);
}
};

const logout = () => auth.signOut();

// We init our user store here
const user = readable(null, set => {
const unsub = auth.onAuthStateChanged(async fireUser => {
if (fireUser) {
const token = await fireUser.getIdTokenResult();
const user = userMapper(token.claims);
set(user);
} else {
set(null);
}
});
return unsub;
});

return {
user,
loginWithGoogle,
loginWithEmailPassword,
logout
};

};

Special thanks to Ilia Mikhailov for this code masterpiece :)

Then, /auth/config.js containing your Firebase project settings keys:

export const firebaseConfig = {
...
}

3. Firebase auth basic:

In pages/index.svelte:

<script>
import { initAuth } from "../auth";

const { loginWithGoogle, logout, user } = initAuth();

let _user;
user.subscribe((v) => (_user = v));
</script>

<main>
{#if _user}
<button type="button" on:click|preventDefault={logout}> Logout </button>
{:else}
<button type="button" on:click|preventDefault={loginWithGoogle}>
Sign In with Google
</button>
{/if}
</main>

Github repository here :)

Enjoy 😇

Guillaume Duhan

--

--

Guillaume Duhan
Guillaume Duhan

No responses yet