nuxt-modules / kinde

Kinde integration for Nuxt
70 stars 7 forks source link

Redirect URL/route for un-authenticated users #45

Open alwaisy opened 9 months ago

alwaisy commented 9 months ago

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?

DanielRivers commented 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.

alwaisy commented 9 months ago

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.

DanielRivers commented 7 months ago

@awaisalwaisy Have a nice solution for this incoming.

alwaisy commented 7 months ago

@awaisalwaisy Have a nice solution for this incoming.

I just visited the reference PR. Better solution to protect routes.

DanielRivers commented 1 month ago

I hope this will be merged very soon.