Reputation: 244
I am building an app with sveltekit using Firebase Authentication and Firestore. I have also recently changed my Firestore rules to allow read, write: if request.auth != null;
. However, my pages are now affected by browser refreshes.
When I head to pages that requires read from firestore, everything went well. But when I refreshed, the page will refresh to a blank page with the word 500
and my console will log Missing or insufficient permissions.\nFirebaseError: Missing or insufficient permissions.
Luckily my navigation bar still shows and works and when I navigate away and back to the page, everything rendered out again. I read that Firebase takes a split second to confirm the authentication and I believe that is messing with my page?
As I needed to protect a handful of pages from Authentication, I implemented the code in my __layout.svelte
page.
__layout.svelte
<script lang="ts" context="module">
import type { User } from 'firebase/auth';
import { onAuthStateChanged } from "firebase/auth";
import { auth } from "$lib/scripts/firebaseStart";
export async function load() {
let authUser: Promise<unknown> = getAuthUser();
function getAuthUser() {
return new Promise(resolve => {
onAuthStateChanged(
auth,
user => resolve(user ? user : false)
);
});
}
return {
props: { authUser }
};
}
</script>
<script lang="ts">
import "../styles/global.css";
export let authUser: User|boolean;
</script>
<main>
{#if authUser}
<!-- page content -->
<slot></slot>
{/if}
</main>
Upvotes: 0
Views: 193
Reputation: 599216
The error you show seems to come fro one of the Firebase products that is protected by server-side security rules, and indicates that your code is trying to access data or files that don't match with the rules you configured.
Firebase indeed reauthenticates the user credentials when the page reloads, which (depending on your connection speed) actually may take longer than a split second.
There is no current user before this authentication call is completed, so if your security rules require an authenticated user, you should way with accessing the data/files until the authentication has successfully completed by only connecting to the database/file storage once your getAuthUser
promise resolves with the current user.
Upvotes: 1