Search code examples
javascriptsveltesveltekit

Is this code hidden for the client in sveltekit?


Will the api key be hidden from the user?

# $lib/config.js

import { initializeApp } from 'firebase/app';
import { getFirestore } from "firebase/firestore/lite";
        
        
const firebaseConfig = {
      apiKey: "my-key",
};
        
const app = initializeApp(firebaseConfig);
        
export const db = getFirestore(app);


#index.svelte

import {db} from "$lib/config"

db.get...and so on

Trying to understand how to deal with things you want to keep hidden in sveltekit as normally js is visible for the user if wanted through source.


Solution

  • You need to divide your index.svelte file into 2 parts. Public and providing data.

    BTW: Your code suggestion won't work because the code won't always execute on the server (SSR). You cannot access the database in the browser.

    index.json.js, always run on server, where you can authenticate user and prepare data. (Read more about endpoints)

    
    import {db} from "$lib/config"
    
    db.get...and so on
    

    index.svelte, where you load prepared data

    <script context="module">
        /** @type {import('@sveltejs/kit').Load} */
        export async function load({ params, fetch, session, stuff }) {
            const url = `index.json`;
            const res = await fetch(url);
    
            if (res.ok) {
                return {
                    props: {
                        article: await res.json()
                    }
                };
            }
    
            return {
                status: res.status,
                error: new Error(`Could not load ${url}`)
            };
        }
    </script>