search

Home  >  Q&A  >  body text

Initialize Svelte application based on promise

<p>I have previously developed several Vue applications that used Keycloak for authentication and authorization. For Vue applications, Keycloak provides a solution to ensure that unauthenticated users cannot load Vue applications by only initializing the application when the user is authenticated. </p> <pre class="brush:js;toolbar:false;">keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => { if (!auth) { window.location.reload(); } else { Vue.$log.info("Authenticated"); newVue({ el: '#app', render: h => h(App, { props: { keycloak: keycloak } }) }) } ... </pre> <p>Now, I'm working on a Svelte project and I want to apply the same approach. Is there a way to initialize a Svelte application based on Promises, similar to how it is done in Vue using Keycloak? </p> <p>I've tried looking for a solution but I can't find anything specifically addressing this issue for Svelte. </p> <p>The biggest advantage to me is that you are always 100% sure that the user is authenticated and you always have access to the JWT token to send to the backend when necessary. </p>
P粉872101673P粉872101673483 days ago569

reply all(1)I'll reply

  • P粉724256860

    P粉7242568602023-09-02 07:57:11

    When using Svelte alone, you can use Client-side component API

    import App from "./App.svelte"
    
    keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => {
      if (!auth) {
        window.location.reload();
      } else {
        new App({
          target: document.getElementById('#app'),
          props: { keycloak: keycloak } })
        })
      }

    In a SvelteKit application, you can add global behavior using src/routes/layout.js:

    // layout.js
    import { browser } from "$app/environment";
    
    /**
     * @type {import('./$types').LayoutLoad}
     */
    export const load = async () => {
      let keycloakPromise;
      if (browser) {
        keycloakPromise = keycloak.init({ onLoad: initOptions.onLoad }).then((auth) => {
          if (auth) {
            return keycloak;
          }
        });
      }
      return {
        keycloak: keycloakPromise,
      };
    };
    <!-- layout.svelte -->
    <script>
      import { onMount } from "svelte";
    
      /** @type {import('./$types').LayoutData} */
      export let data;
    
      onMount(() => {
        if (!data.keycloak) {
          window.location.reload();
        }
      });
    </script>
    
    {#if data.keycloak}
      <slot />
    {/if}
    

    Authentication fails when data.keycloak is not defined. This allows conditional rendering of content.

    (code example assumes keycloak is client authentication)

    reply
    0
  • Cancelreply