wobsoriano / nuxt-clerk-template

Auth starts here with the Nuxt and Clerk Demo
https://nuxt-clerk-template.nuxt.dev
97 stars 11 forks source link

Route Middleware (How To) #3

Closed alexander-gekov closed 1 year ago

alexander-gekov commented 1 year ago

Overview

Hello, first of all, thanks for your contributions to the Vue community. I was wondering if it is possible to use vue-clerk and/or the h3-clerk for Route Middleware and what exactly it will look like.

Thanks in advance.

selemondev commented 1 year ago

Hey @alexander-gekov, I am struggling with the same issue. Have you managed to come up with a solution?

alexander-gekov commented 1 year ago

I've managed to resolve the issue with route middleware. Initially, I was facing a problem where the clerkProvider wasn't properly set even after installing the plugin. The root cause seemed to be related to setting up the clerkPlugin within route middleware.

To fix this, I just repeated the plugin installation within my middleware:

import { useUser, clerkPlugin } from "vue-clerk";

export default defineNuxtRouteMiddleware((to) => {
  const nuxtApp = useNuxtApp();
  // Repeated the plugin installation within the middleware
  nuxtApp.vueApp.use(clerkPlugin, {
    publishableKey: useRuntimeConfig().public.clerkPublishableKey as string,
    options: {
      appearance: {
        variables: { colorPrimary: "#4C9A2A" },
      },
    },
  });

  const user = useUser();
  if (!user.value) {
    return navigateTo("/sign-in");
  }
});

Hope this helps!

wobsoriano commented 1 year ago

If I found a better solution, I will definitely update you all as well.

selemondev commented 1 year ago

I've managed to resolve the issue with route middleware. Initially, I was facing a problem where the clerkProvider wasn't properly set even after installing the plugin. The root cause seemed to be related to setting up the clerkPlugin within route middleware.

To fix this, I just repeated the plugin installation within my middleware:

import { useUser, clerkPlugin } from "vue-clerk";

export default defineNuxtRouteMiddleware((to) => {
  const nuxtApp = useNuxtApp();
  // Repeated the plugin installation within the middleware
  nuxtApp.vueApp.use(clerkPlugin, {
    publishableKey: useRuntimeConfig().public.clerkPublishableKey as string,
    options: {
      appearance: {
        variables: { colorPrimary: "#4C9A2A" },
      },
    },
  });

  const user = useUser();
  if (!user.value) {
    return navigateTo("/sign-in");
  }
});

Hope this helps!

Thank you!

jordcodes commented 1 year ago

Hi all.

Unsure if there is a new approach to this middleware now but my user is always undefined when using the above code?

wobsoriano commented 1 year ago

Updated with route middleware!