Getting started
Vue.js

Vue.js

Handle authentication with Secrecy in a Vue.js app

Get an authenticated Secrecy client

First initialize the Secrecy library with setup method. if it hasn't been done yet. Then, attempt to retrieve an authenticated client, either from the current session or local storage with getSecrecyClient. If no client is found, initiates a login process with the login. Finally, on success the client SecrecyClient is returned. If there's an error or the login is not completed, it returns null.

app.vue
<script setup>
import { ref, onMounted } from 'vue';
import { getSecrecyClient, login, SecrecyClient, setup } from '@secrecy/lib';
 
// State for storing the SecrecyClient
const client = ref<SecrecyClient | null>(null);
 
onMounted(() => {
  if (client.value !== null) {
    return;
  }
 
  // Initialize the Secrecy library
  setup();
 
  // Attempt to retrieve an authenticated client from the current session or local storage
  const sessionClient = getSecrecyClient(true);
  const localStorageClient = getSecrecyClient(false);
  const storedClient = sessionClient ?? localStorageClient;
 
  // If a client is found from the current session or local storage, store it in the state
  if (storedClient) {
    client.value = storedClient;
    return;
  }
 
  // If no client is found, initiate the secrecy login process
  login({
    appId: import.meta.env.VITE_SECRECY_APP_ID,  // Ensure app ID is properly configured in your environment
    redirect: true,
    path: window.location.pathname,
    scopes: {
      email: true,
    },
    backPath: document.referrer,
  })
    .then((newClient) => {
      // On success, store the client in the state
      client.value = newClient;
    })
    .catch((e) => {
      console.error(e);
    });
});
</script>
 
<template>
  <div>
    <!-- Your application content here -->
    <p v-if="client">Client authenticated</p>
    <p v-else>Authenticating...</p>
  </div>
</template>
 
<style scoped>
/* Optional styling */
</style>
 

Get user from Secrecy client

The method secrecyClient.me is used for fetching the user's data once the client is initialized to get the user data. It returns a SelfUser object.

app.vue
<script setup>
import { ref, onMounted, watch } from 'vue';
import type { SelfUser, SecrecyClient } from '@secrecy/lib';
 
// Reactive references for user and client states
const user = ref<SelfUser | null>(null);
const client = ref<SecrecyClient | null>(null);
 
// Watching the client and user states
watch(client, () => {
  if (user.value !== null || client.value === null) {
    return;
  }
 
  // If client is available, fetch user details
  client.value.me()
    .then((fetchedUser) => {
      user.value = fetchedUser;
    })
    .catch((e) => {
      console.error(e);
    });
});
</script>
 
<template>
  <div>
    <p v-if="user">User authenticated: {{ user.name }}</p>
    <p v-else>Authenticating user...</p>
  </div>
</template>
 
<style scoped>
/* Optional styling */
</style>