Skip to content

Instantly share code, notes, and snippets.

@mubaidr
Created January 28, 2025 05:51
Show Gist options
  • Save mubaidr/ccbbe2b659181960a04e5e4385cf42d9 to your computer and use it in GitHub Desktop.
Save mubaidr/ccbbe2b659181960a04e5e4385cf42d9 to your computer and use it in GitHub Desktop.
A sample implementation of middleware for Nuxt Atnetication whcih supports unauthenticated access.
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