Tutorial
Vue 3 Integration
Add AuthMe authentication to a Vue 3 application with the official plugin, composables, and router navigation guards.
Installation
Terminal
npm install authme-sdk Plugin Setup
Register the AuthMe Vue plugin in main.ts before mounting your app.
src/main.ts
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
import { createAuthme } from 'authme-sdk/vue';
import App from './App.vue';
import router from './router';
const app = createApp(App);
const authme = createAuthme({
url: import.meta.env.VITE_AUTHME_URL,
realm: import.meta.env.VITE_AUTHME_REALM,
clientId: import.meta.env.VITE_AUTHME_CLIENT_ID,
redirectUri: window.location.origin + '/callback',
});
app.use(router);
app.use(authme);
app.mount('#app'); useAuth Composable
Access authentication state and actions in any component or composable using useAuth().
src/components/UserMenu.vue
<script setup lang="ts">
import { useAuth } from 'authme-sdk/vue';
const { user, isAuthenticated, isLoading, login, logout } = useAuth();
</script>
<template>
<div v-if="isLoading">Authenticating…</div>
<div v-else-if="isAuthenticated" class="user-menu">
<img :src="user?.picture" :alt="user?.name" />
<span>{{ user?.email }}</span>
<button @click="logout()">Sign Out</button>
</div>
<button v-else @click="login()">Sign In</button>
</template> Router Navigation Guards
Add a global beforeEach guard to redirect unauthenticated users away from protected routes.
src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
import { getAuthState } from 'authme-sdk/vue';
const routes = [
{ path: '/', component: () => import('@/views/Home.vue') },
{
path: '/dashboard',
component: () => import('@/views/Dashboard.vue'),
meta: { requiresAuth: true },
},
{
path: '/admin',
component: () => import('@/views/Admin.vue'),
meta: { requiresAuth: true, role: 'admin' },
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach(async (to) => {
if (!to.meta.requiresAuth) return true;
const { isAuthenticated, user } = await getAuthState();
if (!isAuthenticated) return { path: '/' };
if (to.meta.role && !user?.roles?.includes(to.meta.role as string)) {
return { path: '/403' };
}
return true;
});
export default router;