Open alwaisy opened 9 months ago
Hi @awaisalwaisy,
Currently there is no built in way to redirect users to a specific URL when they are unautnticated accessing routes that you want to be protected.
This can however be achieved by a simple custom middleware.
If you add a file into the ./middleware
folder with the following content. I called this protected.ts
export default defineNuxtRouteMiddleware(() => {
if (!useNuxtApp().$auth.loggedIn) {
return navigateTo('/') // Update this URL to the where you want to redirect the user too.
}
})
Then at the top of your <script>
tag on the page you wish to protect add the following
definePageMeta({
middleware: ["protected"],
});
Let me know if this helps.
Thanks for replying...
I have implemented the following code by copying and modifying the middleware from the "kinde auth" module. It successfully worked for my needs.
Here is the code snippet from my global middleware file,
import { defineNuxtRouteMiddleware, useNuxtApp } from "#imports";
export default defineNuxtRouteMiddleware(() => {
if (!useNuxtApp().$auth.loggedIn) {
if (import.meta.server) {
return navigateTo(process.env.NUXT_CLIENT_URL + "/api/login", {
external: true,
});
} else {
console.log("Not logged in...");
}
// return abortNavigation();
}
});
Although this solution works, I believe there could be a better built-in way to handle this situation.
@awaisalwaisy Have a nice solution for this incoming.
@awaisalwaisy Have a nice solution for this incoming.
I just visited the reference PR. Better solution to protect routes.
I hope this will be merged very soon.
I am having some difficulty handling unauthenticated users. I attempted to use another global middleware, but encountered an infinite redirect error. Is there a redirect URL available for unauthenticated users similar to Clerk auth?