0

Let's say, I have 2 user types: admin and client and the following directory structure:

pages/admin/products.vue
pages/admin/settings.vue
pages/client/products.vue
  • When a user of type admin heads to /productspages/admin/products.vue is used
  • When a user of type client heads to /products page – pages/client/products.vue is used
  • When a user of type admin heads to /settingspages/admin/settings.vue is used
  • When a user of type client heads to /settings – 404 not found because there's no pages/client/settings.vue page

In other words, I want each user to have its own routes

How can I approach this? I've played around with router.options.ts. But I can't get an instance of currently authorised user from there to read its type. If I could, there would be no problem to modify routes as needed:

// app/router.options.ts

import type { RouterConfig } from "@nuxt/schema"

export default <RouterConfig>{
  routes(routes) {
    const { user } = useAuthStore() // Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
    if (user.type === 'admin') {
      // return admin routes 
    } else {
      // return client routes
    }
  }
}
1

1 Answer 1

0

Is your store auto imported ? Usually I have to import the pinia store before using it. Example

import { useAuthStore } from '@/stores/auth'
const store = useAuthStore()

And since were in the nuxt universe I would consider a route middleware here https://nuxt.com/docs/guide/directory-structure/middleware. Within this you can use your store and have conditions to call the navigateTo() https://nuxt.com/docs/api/utils/navigate-to composable to navigate the user to a 404 page you can use showError https://nuxt.com/docs/api/utils/show-error

I can imagine that the nuxt need to have all routes at startup since your users usually are authenticated in runtime

3
  • 1) I've tried both. I get the same Error: [🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
    – Max Flex
    2 days ago
  • 2) I don't see how middleware & navigateTo can be used here. Say, I'm navigating to /products as admin, I expect /pages/admin/products.vue to open – but I get error right away because /products path doesn't exist
    – Max Flex
    2 days ago
  • 3) Yes, that's why the way I see it is to tinker with router.options.ts. Routes being initiated at startup also the reason why store is not yet available
    – Max Flex
    2 days ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.