Nuxt Directus

repository·main·Indexed 43 days ago

https://github.com/intevel/nuxt-directus

A Nuxt 3 module for integrating Directus into Nuxt applications. It provides authentication handling, RESTful API access, full TypeScript support, and a suite of composables including useDirectusAuth, useDirectusUser, and useDirectusToken. Version 5.7.0 includes Nuxt DevTools integration and support for static site generation (SSG).

Tokens
20.6K
Snippets
95
Records
103
Agent score
53%

What's inside Nuxt Directus

  1. Overview of Nuxt Directus

    main

    Nuxt Directus is a module designed to easily integrate Directus into Nuxt applications. It provides a seamless way to interact with the Directus RESTful API while leveraging Nuxt's ecosystem.

    Key features include:

    • Nuxt 3 Ready: Built specifically for the Nuxt 3 ecosystem.
    • Authentication: Built-in support for handling Directus authentication.
    • RESTful Methods: Direct access to the Directus RESTful API.
    • TypeScript Support: Fully-typed API and composables for enhanced developer experience.
    • Nuxt DevTools Integration: Integration with Nuxt DevTools for easier debugging.
    • Static Support: Optimized for static site generation (SSG) using useAsyncData.
    • Handy Composables: A suite of composables to simplify Directus integration.
  2. Overview of nuxt-directus features

    main

    The nuxt-directus module provides seamless integration between Directus and Nuxt 3. Key features include:

    • Nuxt 3 ready: Built specifically for the Nuxt 3 ecosystem.
    • Authentication handling: Built-in support for managing Directus authentication.
    • RESTful methods: Provides access to Directus RESTful capabilities.
    • TypeScript Support: Full type safety for your Directus interactions.
  3. Use `useDirectusItems` to manage collection data

    main

    The useDirectusItems composable provides a suite of methods to perform CRUD (Create, Read, Update, Delete) operations on Directus collections. It allows you to interact with items using type-safe requests and returns data shaped by your Directus collection schema.

    const { 
      getItems, 
      getSingletonItem, 
      getItemById, 
      createItems, 
      deleteItems, 
      updateItem 
    } = useDirectusItems();
  4. Configure nuxt-directus in nuxt.config

    main

    After installation, add nuxt-directus to the modules array in your nuxt.config.ts. You must also provide the Directus server URL within the runtimeConfig.public.directus object to allow the client to connect to your backend.

    export default defineNuxtConfig({
      modules: ['nuxt-directus'],
      runtimeConfig: {
        public: {
          directus: {
            url: ""
          }
        }
      }
    })
  5. Configure Directus Content Security Policy for Devtools embedding

    main

    To allow the Directus Admin Dashboard to be embedded in Nuxt Devtools, you must modify the frame-ancestors directive in your Directus security settings. This allows the Directus interface to be rendered inside an iframe on your local development server.

    Set the following environment variable in your Directus .env file: CONTENT_SECURITY_POLICY_DIRECTIVES__FRAME_ANCESTORS=array:http://localhost:*,self

    + CONTENT_SECURITY_POLICY_DIRECTIVES__FRAME_ANCESTORS=array:http://localhost:*,self
  6. Enable Directus Admin Dashboard in Nuxt Devtools

    main

    You can embed the Directus Admin Dashboard directly within the Nuxt Devtools. This requires two steps: updating your Directus security configuration to allow embedding and enabling the feature in your Nuxt configuration.

    1. Update Directus Security Options

    By default, Directus sets the Content Security Policy directive frame-ancestors to 'self', which prevents it from being embedded in localhost. To allow embedding, update your Directus environment variables or configuration to include http://localhost:* in the frame-ancestors directive.

    2. Enable in Nuxt Configuration

    Set the directus.devtools option to true in your nuxt.config.ts file.

    // nuxt.config.ts
    export default defineNuxtConfig({
      directus: {
        devtools: true
      }
    })
  7. Protect routes by redirecting unauthenticated users to login

    main

    To protect specific routes in your Nuxt application, you can create a custom route middleware that uses useDirectusAuth() and useDirectusUser() to check for an active session. If no user is found, the middleware attempts to fetchUser() and set the user session via setUser(). If the user remains unauthenticated after the fetch attempt, the middleware redirects the user to a login page (e.g., /login) using navigateTo().

    // ./middleware/auth.ts
    export default defineNuxtRouteMiddleware(async (to, _from) => {
      const { fetchUser, setUser } = useDirectusAuth();
      const user = useDirectusUser();
    
      if (!user.value) {
        const user = await fetchUser();
        setUser(user.value);
      }
    
      if (!user.value) {
        return navigateTo("/login");
      }
    });
  8. Understand Directus data response shapes

    main

    Data returned from Directus is typically wrapped in specific interfaces depending on whether you are requesting a single item or a collection:

    • Single Item: DirectusItem<T> contains a data property of type T.
    • Collection: DirectusItems<T> contains a data array of type T[] and an optional meta object for pagination/count information.
    • Metadata: DirectusItemMetadata provides total_count and filter_count.
    export interface DirectusItemMetadata {
      total_count?: number;
      filter_count?: number;
    };
    
    export interface DirectusItems<T> {
      data: NonNullable<T[]>;
      meta?: DirectusItemMetadata;
    };
    
    export interface DirectusItem<T> {
      data: NonNullable<T>;
    };
  9. Configure automatic user fetching and token refreshing

    main

    Control how the module handles user data and authentication lifecycle:

    • autoFetch (default: true): Determines if the user should be fetched automatically.
    • autoRefresh (default: false): Enables automatic refreshing of tokens.
    • onAutoRefreshFailure() (default: not defined): A callback function that is executed if the autoRefresh process fails.
    • fetchUserParams (optional): Parameters sent when the user is fetched (conforming to DirectusQueryParams).