Gathering detailed insights and metrics for @dreamonkey/vue-auth0
Gathering detailed insights and metrics for @dreamonkey/vue-auth0
Gathering detailed insights and metrics for @dreamonkey/vue-auth0
Gathering detailed insights and metrics for @dreamonkey/vue-auth0
@auth0/auth0-spa-js wrapper in the "Vue way", with full TS support
npm install @dreamonkey/vue-auth0
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
6 Stars
9 Commits
2 Forks
1 Watching
2 Branches
6 Contributors
Updated on 28 Jun 2024
TypeScript (81.13%)
JavaScript (18.87%)
Cumulative downloads
Total Downloads
Last day
133.3%
7
Compared to previous day
Last week
-59.6%
19
Compared to previous week
Last month
136.7%
187
Compared to previous month
Last year
-35.7%
2,625
Compared to previous year
This is a wrapper around @auth0/auth0-spa-js
meant to ease its usage into Vue3 projects.
This is heavily inspired by the snippet into Auth0 official documentation, but with a couple more helpers.
This wrapper supports both JS and TS codebases.
1yarn add @dreamonkey/vue-auth0
Initialize the singleton instance
1import { Auth0Instance, initAuth0 } from '@dreamonkey/vue-auth0'; 2// NEVER HARDCODE AND/OR COMMIT YOUR SECRETS 3import { domain, clientId } from './env.json'; 4 5declare module '@vue/runtime-core' { 6 interface ComponentCustomProperties { 7 $auth: Auth0Instance; 8 } 9} 10 11// Vue CLI/Vite project 12import { createApp } from 'vue'; 13 14const app = createApp({}); 15 16app.config.globalProperties.$auth = initAuth0({ 17 client_id: clientId, 18 domain, 19}); 20 21// Quasar CLI project (using boot files) 22export default boot(({ app }) => { 23 app.config.globalProperties.$auth = initAuth0({ 24 client_id: clientId, 25 domain, 26 }); 27});
Check out @auth0/auth0-spa-js
documentation to learn about initialization options, as initAuth0
accepts all options from original createAuth0Client
method.
You can then access the Auth0 singleton instance via useAuth0
composable
1import { useAuth0 } from '@dreamonkey/vue-auth0'; 2 3const { user /*, ... other stuff */ } = useAuth0();
or, in templates or Option API, via the $auth
global property
1<button @click="$auth.loginWithRedirect()">Login</button>
initAuth0
accepts a couple of custom options in addition to those of createAuth0Client
method.
window.location.origin
)Overwrites native redirect_uri
option setting a sensible default for it.
If your redirect login flow starts from a page with URL http://my-domain.com/landing
, the user will be redirected to http://my-domain.com
when the flow completes.
Remember you need to add whichever URL is provided with redirectUri
to "Allowed Callback URLs" list into your Auth0 configuration.
When redirect login flow completes, this callback is called with any previously stored state as param.
If not specified, it replaces the current browser history entry with current window.location.pathname
.
This can be used to redirect the user to the originally requested page after login took place (see Recipes section).
These refs has been added for your ease, to consume Auth0 SDK in the "Vue way"
user
(default: undefined
)The original getUser()
async method served as a reactive reference.
It updates when either a login or logout action is performed.
The content after login depends on your Auth0 configuration.
1const { user } = useAuth0(); 2// Before login 3console.log(user.value); // undefined 4// After login 5console.log(user.value); // { ... }
Its type is User
by default, you can augment Auth0User
type to specify custom properties or to remove optionality from existing keys.
1import '@dreamonkey/vue-auth0'; 2 3declare module '@dreamonkey/vue-auth0' { 4 interface Auth0User { 5 twitter_handle: string; // <--- Specify a custom property which doesn't exist into User by default 6 name: string; // <--- Override User property, it won't be shown as optional anymore 7 } 8}
isAuthenticated
(default: false
)The original isAuthenticated()
async method served as a reactive reference.
true
if the user is authenticated, false
otherwise.
Helpful to change the behaviour of your app depending on the user authentication status, eg. adding an header to all outgoing requests only when the user is authenticated
1const { isAuthenticated } = useAuth0(); 2// Before login 3console.log(isAuthenticated.value); // false 4// After login 5console.log(isAuthenticated.value); // true
loading
(default: true
)true
if Auth0 client initialization is still taking place, false
when initialization completes.
popupOpen
(default: false
)true
if the login popup related to loginWithPopup()
method is open, false
otherwise.
error
(default: undefined
)Contains the error generated by the underlying library in case something goes wrong.
auth0Client
(default: undefined
)Reference to the underlying Auth0 client created with original createAuth0Client()
method.
getTokenSilently
Original getTokenSilently
method with detailedResponse
forced to false
.
This is how the method behaved before version 1.19.0.
getTokenSilentlyVerbose
Original getTokenSilently
method with detailedResponse
forced to true
.
Splitting the original method was required to support proper types, as wrapping a function and trying to infer its return type won't work if the original function has an overloaded signature.
initializationCompleted
Returns a Promise resolving when initialization completes.
Use this when you need to be sure initialization is completed and you cannot use onInitializationCompleted
hook.
1const { initializationCompleted } = useAuth0(); 2 3async function doStuff() { 4 // business ah-ah 5 await initializationCompleted(); 6 // profit! 7}
Some common events hooks have been created, ensuring your code will be executed only after a given trigger condition is met. Since they're based on internal state refs rather than an event system, if the trigger condition is valid when the hook is registered (eg. login already happened) the callback will be executed immediately.
onInitializationCompleted
Trigger: Auth0 client initialization completes. Use case: run code using Auth0 only after the client is initialized.
initializationCompleted
method could be used to achieve the same result, but with a different syntax.
1const { onInitializationCompleted } = useAuth0(); 2 3onInitializationCompleted(() => { 4 // unless initialization errors occurred, auth0Client will always be defined here 5});
onLogin
Trigger: login process completes successfully. Use case: run code once the user logs in. User data object is provided as a parameter for convenience.
Examples:
1const { onLogin } = useAuth0(); 2 3onLogin((user) => { 4 console.log(user); // { .. user data .. } 5});
onLogout
Trigger: logout process completes. Use case: run code once the user logs out.
Examples:
1const { onLogout } = useAuth0(); 2 3onLogout(() => { 4 localStorage.removeItem('user-data'); 5});
If you're using Vue Router, you'll often need to guard some routes depending on the user authentication status. This package provides you some helpers to deal with common scenarios.
authGuard
Use this helper to create guards relying on the user authentication status.
The first param your callback receives is a boolean representing the authentication status, while the second and third params are the deprecated to
and from
Vue Router guards params.
The returned guard is async as it awaits for the Auth0 client to be initialized before proceeding.
1export const redirectIfAuthenticatedGuard = authGuard((isAuthenticated) => { 2 if (isAuthenticated) { 3 return { name: 'home' }; 4 } 5});
redirectToLoginGuard
Triggers loginWithRedirect
if the user isn't authenticated, storing into appState.targetUrl
the URL the user tried to access.
You can then access it into onRedirectCallback
to redirect the user to the page he initially requested.
Here are some common use cases you may need in your projects. We'll gladly accept PRs adding new recipes if the use case is common enough.
1import { useAuth0 } from '@dreamonkey/vue-auth0'; 2import axios, { AxiosRequestConfig } from 'axios'; 3 4async function addAuthToken(config: AxiosRequestConfig) { 5 const { getTokenSilently } = useAuth0(); 6 const token = await getTokenSilently(); 7 addHeader(config, 'Authorization', `Bearer ${token}`); 8 return config; 9} 10 11axios.interceptors.request.use(addAuthToken);
1import { initAuth0 } from '@dreamonkey/vue-auth0'; 2import { useRouter } from 'vue-router'; 3import { domain, clientId } from './env.json'; 4 5const router = useRouter(); 6 7initAuth0<{ targetUrl?: string }>({ 8 client_id: clientId, 9 domain, 10 onRedirectCallback: (appState) => 11 router.push(appState?.targetUrl ?? window.location.pathname), 12});
1import { RouteRecordRaw } from 'vue-router'; 2import { redirectToLoginGuard } from '@dreamonkey/vue-auth0'; 3 4const routes: RouteRecordRaw[] = [ 5 { 6 path: '/', 7 component: () => import('layouts/authenticated.vue'), 8 beforeEnter: redirectToLoginGuard, 9 children: [ 10 { 11 path: 'home', 12 name: 'home', 13 component: () => import('pages/home.vue'), 14 }, 15 ], 16 }, 17];
1import { RouteRecordRaw } from 'vue-router'; 2import { authGuard } from '@dreamonkey/vue-auth0'; 3 4export const redirectIfAuthenticatedGuard = authGuard((isAuthenticated) => { 5 if (isAuthenticated) { 6 return { name: 'home' }; 7 } 8}); 9 10export const redirectIfGuestGuard = authGuard((isAuthenticated) => { 11 if (!isAuthenticated) { 12 return { name: 'landing' }; 13 } 14}); 15 16const routes: RouteRecordRaw[] = [ 17 { 18 path: '/', 19 redirect: () => ({ name: 'landing' }), 20 }, 21 { 22 path: '/', 23 name: 'guest', 24 component: () => import('layouts/guest.vue'), 25 beforeEnter: redirectIfAuthenticatedGuard, 26 children: [ 27 { 28 path: 'landing', 29 name: 'landing', 30 component: () => import('pages/landing.vue'), 31 }, 32 ], 33 }, 34 { 35 path: '/', 36 component: () => import('layouts/authenticated.vue'), 37 beforeEnter: redirectIfGuestGuard, 38 children: [ 39 { 40 path: 'home', 41 name: 'home', 42 component: () => import('pages/home.vue'), 43 }, 44 ], 45 }, 46];
1import { RouteRecordRaw } from 'vue-router'; 2import { useAuth0 } from '@dreamonkey/vue-auth0'; 3 4const routes: RouteRecordRaw[] = [ 5 { 6 path: '/home', 7 component: async () => { 8 const { user, initializationCompleted } = useAuth0(); 9 await initializationCompleted(); 10 11 if (!user.value) { 12 return import('pages/landing.vue'); 13 } 14 15 switch (user.value.role) { 16 case 'admin': 17 return import('pages/home/admin.vue'); 18 case 'manager': 19 return import('pages/home/manager.vue'); 20 default: 21 return import('pages/home/user.vue'); 22 } 23 }, 24 }, 25];
No vulnerabilities found.
No security vulnerabilities found.