atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
973 stars 91 forks source link

Using this module in another Nuxt module (not Nuxt project) #243

Closed ymansurozer closed 1 month ago

ymansurozer commented 1 month ago

In my company, we're building a common module that we want to utilize in all our apps. We want to include auth functionality in this module (with user store and client & server middleware). We can install the module with NuxtKit's installModule on module setup but we are not able to access its composables inside our own module (so we cannot extend it).

So, is there any way at all for using this module in a Nuxt module as opposed to a Nuxt project? So far, the only idea we had was to copy this repo to our own module's directory which would allow import of composables and other utilities.

P.S.: I know we can use layers but they have behavior & restrictions which lead us down the module path.

ymansurozer commented 1 month ago

Thanks to @danielroe over X, this is now quite clear for me. So here is me answering myself 🫠.

You can import anything from modules your module installs from #imports like this:

runtime/plugins/auth.ts

import { defineNuxtPlugin } from '#app';
import { useUserSession } from '#imports';

export default defineNuxtPlugin((_nuxtApp) => {
  const session = useUserSession();
  console.log(session);
});

module.ts

import { defineNuxtModule, installModule } from '@nuxt/kit';

export default defineNuxtModule({
  meta: {
    name: 'my-module',
    configKey: 'myModule',
  },
  defaults: {},
  async setup(_options, _nuxt) {
    await installModule('nuxt-auth-utils');
  },
});

There are two caveats:

  1. You cannot access it inside build context (i.e. your module.ts file that installs your module).
  2. You have to do a clean install and generate types with npm run dev:prepare script.