@nuxtjs/strapi

repository·main·Indexed 20 days ago

https://github.com/nuxt-modules/strapi

A Nuxt module serving as a client for connecting Nuxt 3 applications to a Strapi backend (supporting v5, v4, and v3). It provides RESTful communication, authentication flows via the Users & Permissions plugin, and TypeScript support. Key features include the useStrapi composable for CRUD operations, useStrapiGraphQL for GraphQL queries, and useStrapiAuth for managing user sessions and registration.

Tokens
17.1K
Snippets
63
Records
74
Agent score
72%

What's inside @nuxtjs/strapi

  1. Overview of Nuxt Strapi features

    main

    The @nuxtjs/strapi module provides several key capabilities for building Strapi-powered Nuxt applications:

    • Nuxt Ready: Includes auto-imported composables and Nuxt DevTools integration.
    • Multi-version Support: Compatible with Strapi v5, v4, and v3.
    • Authentication: Provides the useStrapiUser composable to manage user authentication.
    • RESTful Interaction: Supports all HTTP methods for interacting with your Strapi API.
    • Error Handling: Includes hooks to handle API errors and improve user experience.
    • TypeScript Support: Composables support types augmentation for better developer experience.
  2. Key features of Nuxt Strapi

    main

    The module provides several capabilities for integrating Strapi with Nuxt:

    • Nuxt 3 ready: Fully compatible with the Nuxt 3 ecosystem.
    • Strapi Version Compatibility: Supports Strapi v5, v4, and v3.
    • Authentication: Built-in support for Strapi authentication flows.
    • RESTful methods: Provides methods to interact with Strapi's REST API.
    • Error Handling: Includes hooks to intercept and handle errors.
    • TypeScript support: Full type definitions for a better developer experience.
  3. Understand the Nuxt Strapi module role

    main

    The @nuxtjs/strapi module acts exclusively as a client for a Strapi backend. It provides the connection between your Nuxt application and a Strapi server.

    Important: This module does not install, run, or bundle the Strapi CMS itself. You must run and host your Strapi server separately.

  4. Fetch data with useAsyncData for SSR

    main

    To leverage server-side rendering (SSR) when fetching data from Strapi, wrap the useStrapi composable methods inside Nuxt's useAsyncData. This ensures data is fetched on the server and hydrated on the client.

    <script setup lang="ts">
    import type { Restaurant } from '~/types'
    
    const route = useRoute()
    const { findOne } = useStrapi()
    
    const { data, pending, refresh, error } = await useAsyncData(
      'restaurant',
      () => findOne<Restaurant>('restaurants', route.params.id)
    )
    </script>
  5. Handle password recovery with `forgotPassword` and `resetPassword`

    main

    Forgot Password

    Sends an email to the user containing a link to your reset password page. The link includes a URL parameter code required for the next step.

    const { forgotPassword } = useStrapiAuth()
    const onSubmit = async () => {
      try {
        await forgotPassword({ email: '' })
        router.push('/')
      } catch (e) {}
    }

    Reset Password

    Updates the user's password using the code received from the email.

    const { resetPassword } = useStrapiAuth()
    const onSubmit = async () => {
      try {
        await resetPassword({ code: '', password: '', passwordConfirmation: '' })
        router.push('/authenticated-page')
      } catch (e) {}
    }
  6. Use imported GraphQL queries with useStrapiGraphQL

    main

    To use .gql files directly in your components, you need to configure a plugin like @rollup/plugin-graphql in your Nuxt/Vite configuration to process the imports.

    1. Configure Vite in nuxt.config.ts:
    import gql from "@rollup/plugin-graphql"
    
    export default defineNuxtConfig({
      // ...
      vite: {
        plugins: [ gql() ]
      }
    })
    1. Use the query in a component:
    <script setup lang="ts">
    import query from "./query/example-query.gql"
    const route = useRoute()
    const graphql = useStrapiGraphQL()
    
    const restaurant = await graphql(query, { id: route.params.id })
    </script>
    1. Fix TypeScript errors (if necessary): If TypeScript cannot find the .gql module, create a globals.d.ts file:
    declare module '*.gql' {
      import { DocumentNode } from 'graphql'
      const Schema: DocumentNode
      export = Schema
    }
    import gql from "@rollup/plugin-graphql"
    
    export default defineNuxtConfig({
      // ...
      vite: {
        plugins: [ gql() ]
      }
    })
  7. Configure Strapi security middleware for Devtools embedding

    main

    To allow the Strapi Admin to be embedded in the Nuxt Devtools, you must modify the strapi::security middleware configuration in your Strapi project's config/middlewares.js file. You need to update the contentSecurityPolicy directives to include frameAncestors for http://localhost:* and 'self'.

    module.exports = [
      'strapi::errors',
      {
        name: 'strapi::security',
        config: {
          contentSecurityPolicy: {
            directives: {
              frameAncestors: ['http://localhost:*', 'self']
            }
          }
        }
      },
      'strapi::cors',
      'strapi::poweredBy',
      'strapi::logger',
      'strapi::query',
      'strapi::body',
      'strapi::session',
      'strapi::favicon',
      'strapi::public'
    ]
  8. Enable Strapi Admin embedding in Nuxt Devtools

    main

    To use the Strapi Admin directly within the Nuxt Devtools, you must perform two steps: configure your Strapi security middleware to allow embedding and enable the devtools option in your Nuxt configuration.

    1. Configure Strapi Security Middleware

    Strapi uses helmet for security, which by default prevents the admin panel from being embedded in frames via the Content Security Policy directive frame-ancestors 'self'.

    In your Strapi project, open config/middlewares.js and update the strapi::security middleware to allow http://localhost:* and self in the frameAncestors directive:

    2. Enable Devtools in Nuxt

    In your Nuxt project, open nuxt.config.ts and set the strapi.devtools option to true.

    export default defineNuxtConfig({
      strapi: {
        devtools: true
      }
    })
  9. Use continuous preview releases with pkg.pr.new

    main

    You can access the latest features and bug fixes before official releases by using pkg.pr.new. This allows you to install specific commits or PRs directly from your package.json.

    To use a preview release, replace your package version with the specific commit hash or PR number URL.

    {
      "dependencies": {
        "@nuxtjs/strapi": "https://pkg.pr.new/@nuxtjs/strapi@95260d0"
      }
    }
  10. Install the @nuxtjs/strapi module

    main

    To add the Strapi module to your Nuxt project, use the Nuxt CLI. This will automatically register the module in your nuxt.config.ts file.

    Note that @nuxtjs/strapi is a client for a Strapi backend. It connects your Nuxt app to a Strapi server that you run and host separately. It does not install, run, or bundle Strapi itself.

    npx nuxi@latest module add strapi
  11. Override the Strapi /users/me route to populate relations

    main

    By default, the /users/me route only returns the user populated with their role. To include additional relations (like restaurants), you must override the fetchAuthenticatedUser method in your Strapi backend.

    For Strapi v5 / v4

    In your Strapi project's src/index.js:

    module.exports = {
      register ({ strapi }) {
        strapi.service('plugin::users-permissions.user').fetchAuthenticatedUser = (id) => {
          return strapi
            .query('plugin::users-permissions.user')
            .findOne({ where: { id }, populate: ['role', 'restaurants'] })
        }
      }
    }

    Note: You must enable the restaurants.find permission in the Strapi admin for the Authenticated role.

    For Strapi v3

    In your Strapi project's extensions/users-permissions/services/User.js:

    module.exports = {
      fetchAuthenticatedUser(id) {
        return strapi.query('user', 'users-permissions').findOne({ id }, ['role', 'restaurants'])
      }
    }
    module.exports = {
      register ({ strapi }) {
        strapi.service('plugin::users-permissions.user').fetchAuthenticatedUser = (id) => {
          return strapi
            .query('plugin::users-permissions.user')
            .findOne({ where: { id }, populate: ['role', 'restaurants'] })
        }
      }
    }