wobsoriano / vue-clerk

Community Clerk Vue SDK.
https://vue-clerk.com
MIT License
144 stars 13 forks source link

How to get access to Clerk instance outside of components? #136

Closed Xkonti closed 1 month ago

Xkonti commented 1 month ago

Hi! I'm working on an Astro app that utilizes vue-clerk. It all works great, but I have a use case where I need access to the Clerk instance in code outside of components. I know that inside the components I can use useClerk composable, but how can I get access to it in non-component code?

wobsoriano commented 1 month ago

Hello! You can access the Clerk instance attached to the window object:

console.log(window.Clerk.loaded)

Also, if you don't mind the Vue components and is cool to use Astro components, please see @clerk/astro. You can use the provided stores and create your own composables on top of that.

Worth noting that it is possible to use the the composables outside of components if we have a way of accessing the app instance in astro. See my X post here.

Xkonti commented 1 month ago

Thanks @wobsoriano ! The window.Clerk works great. @clerk/astro seems to focus on Astro with server rendering, so I'm gonna stick with vue-clerk :)

If somebody else searches for solutions, this is how I ended up using it to connect to SurrealDB database using JWT token from Clerk:

...
const token = await window.Clerk.session?.getToken();
if (!token) {
  console.error("No token to authenticate with");
  return undefined;
}

await database.connect(SURREALDB_URL, {
  prepare: async (connection) => {
    await connection.use({ namespace: "test", database: "test" });
    await connection.authenticate(token);
  },
});
...
wobsoriano commented 1 month ago

Glad it worked out for you!

FYI we support static and hybrid outputs in @clerk/astro as well!