Created
January 28, 2025 05:51
-
-
Save mubaidr/ccbbe2b659181960a04e5e4385cf42d9 to your computer and use it in GitHub Desktop.
A sample implementation of middleware for Nuxt Atnetication whcih supports unauthenticated access.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default defineNuxtRouteMiddleware(async (to) => { | |
const { loggedIn, user, clear } = useUserSession() | |
const auth = to.meta.auth as | |
| undefined | |
| boolean | |
| { | |
unauthenticatedOnly: boolean | |
navigateAuthenticatedTo: string | undefined | |
} | |
if (auth === false) { | |
return | |
} | |
if (auth === true || auth === undefined || auth === null) { | |
if (loggedIn && user.value) { | |
if (!user.value?.emailVerified) { | |
if (!to.path.includes("/email-verification")) { | |
return navigateTo({ | |
path: "/email-verification", | |
}) | |
} | |
return | |
} | |
return | |
} else { | |
await clear() | |
return navigateTo({ | |
path: "/login", | |
query: { | |
redirect: to.path, | |
}, | |
}) | |
} | |
} | |
// advance config | |
const { unauthenticatedOnly, navigateAuthenticatedTo } = auth | |
if (unauthenticatedOnly) { | |
if (user.value) { | |
return navigateTo({ | |
path: navigateAuthenticatedTo || "/", | |
}) | |
} | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment