Vue Storefront is now Alokai! Learn More
Setup for Nuxt

Setup for Nuxt

By default, Alokai integration with Contentful is meant to be used with our Alokai Storefront solution. However, if you want to use it with a freshly bootstrapped or already existing Nuxt 3 application, this guide explains how to get started.

Requirements

Something's missing?

If you don't have a Nuxt 3 project yet, create one by following the official guide. If you don't have a Contentful space yet, we suggest you request a demo from the Contentful team.

Creating .npmrc file

In order to start working with our enterprise packages, add a .npmrc file with the following content to the root of your repository:

@vsf-enterprise:registry=https://registrynpm.storefrontcloud.io

Importing integration components

Alokai ships with a CLI tool for CMS integrations which will import all of the frontend acceleration files into your project.

The CLI tool has been tested with a fresh Nuxt 3 project.

To use the CLI, simply run the following command from the root of your project:

npx @vsf-enterprise/cms-cli contentful:components -f nuxt

This will create (or overwrite) the following files in your project:

├── components
│   └── cms
│       ├── layout
│       │   ├── Footer.vue
│       │   └── MegaMenu.vue
│       ├── page
│       │   ├── Accordion.vue
│       │   ├── Banner.vue
│       │   ├── Card.vue
│       │   ├── CategoryCard.vue
│       │   ├── Editorial.vue
│       │   ├── Gallery.vue
│       │   ├── Grid.vue
│       │   ├── Hero.vue
│       │   ├── NewsletterBox.vue
│       │   ├── ProductCard.vue
│       │   └── Scrollable.vue
│       └── wrappers
│           └── RenderComponent.vue
├── layouts
│   └── contentful.vue
└── pages
    └── [...slug].vue

Enabling layouts

The contentful.vue layout will only take effect when the NuxtLayout component is used within the app.vue component. Make sure yours has it.

<template>
  <NuxtLayout />
</template>

Installing dependencies

The integration requires a few additional dependencies to run. That includes supplementary packages related to Storefront UI or agnostic CMS components.

Check out our compatibility matrix for the integration before installing the dependencies described in this guide.

yarn add @storefront-ui/typography @nuxtjs/google-fonts @vsf-enterprise/cms-components-utils

Loading Storefront UI

The UI layer of the integration relies on Storefront UI and its dependencies. Follow the official guide to install the library in your project.

Loading Google Fonts

The default Storefront UI setup uses Google Fonts. One way to loading these fonts to your project is by installing the @nuxtjs/google-fonts module in your project and adding the following lines to your nuxt.config.ts:

export default defineNuxtConfig({
  // ...
  modules: [
    // ...
    ['@nuxtjs/google-fonts', {
      families: {
        'Red Hat Display': [400, 500, 700],
        'Red Hat Text': [300, 400, 500, 700]
      }
    }]
  ]
});

To complete the fonts setup, add the following Storefront UI typography configuration to your Tailwind config file:

import sfTypography from '@storefront-ui/typography';

export default {
  // ...
  plugins: [sfTypography],
  theme: {
    fontFamily: {
      sans: 'Red Hat Text, sans-serif',
    }
  }
};

Loading Nuxt Image

In the Installing dependencies section, you've already installed the @nuxt/image module in your project. Now, register it in your nuxt.config.ts:

export default defineNuxtConfig({
  // ...
  modules: [
    // ...
    '@nuxt/image'
  ]
});

Configuring Server Middleware

The next step is configuring Contentful integration in the Server Middleware.

Key concept: Server Middleware

Middleware concept is described in detail in our Key concepts: Server Middleware docs.

In the root of your project, create a [middleware.config.jsfile to register Contentful integration in your Server Middleware. Replace<contentful_space_id>and<contentful_access_token>` with your space's credentials:

module.exports = {
  integrations: {
    cntf: {
      location: '@vsf-enterprise/contentful-api/server',
      configuration: {
        space: '<contentful_space_id>',
        token: '<contentful_access_token>',
      },
    },
  },
};

Good to know

Information on where to get your Contentful access token from can be found here.

Keep your tokens safe

We recommend keeping your Contentful access token in the .env file and referencing it through process.env in middleware.config.js.

With the configuration file in place, we need a script which will import it and spin up the Server Middleware on a dedicated port. Let's create it and name it middleware.js:

// middleware.js

const { createServer } = require('@vue-storefront/middleware');
const { integrations } = require('./middleware.config');
const cors = require('cors');

(async () => {
  const app = await createServer({ integrations });
  // By default it's running on the localhost.
  const host = process.argv[2] ?? '0.0.0.0';
  // By default it's running on the port 8181.
  const port = process.argv[3] ?? 8181;
  const CORS_MIDDLEWARE_NAME = 'corsMiddleware';

  const corsMiddleware = app._router.stack.find(
    (middleware) => middleware.name === CORS_MIDDLEWARE_NAME
  );

  // You can overwrite the cors settings by defining allowed origins.
  corsMiddleware.handle = cors({
    origin: ['http://localhost:3000'],
    credentials: true,
  });

  app.listen(port, host, () => {
    console.log(`Middleware started: ${host}:${port}`);
  });
})();

Now your Server Middleware should be ready for take off. You can start it by running node middleware.js.

Configuring Alokai SDK

The last step in the installation process is configuring Alokai SDK for Contentful in your frontend application. It ships with functions responsible for fetching and resolving raw data from Contentful.

Key concept - SDK

SDK is described in detail in our Key concepts: SDK docs. Also, read about middlewareModule used by our Contentful SDK module under the hood.

In the root of your project, create a new sdk.config.ts file with the following content:

import { contentfulModule } from '@vsf-enterprise/contentful-sdk';
import type { Endpoints as ContentfulEndpoints } from "@vsf-enterprise/contentful-api";

export default defineSdkConfig(
  ({ buildModule }) => ({
    contentful: buildModule(contentfulModule<ContentfulEndpoints>, {
      apiUrl: 'http://localhost:8181/cntf',
    }),
  }),
);

Next, register the @vue-storefront/nuxt module in your nuxt.config.ts. It will expose a global useSdk function which is used by some of the Contentful integration components (e.g. contentful.vue).

export default defineNuxtConfig({
  // ...
  modules: [
    // ...
    '@vue-storefront/nuxt',
  ]
});

Finally, set the verbatimModuleSyntax to false in your tsconfig.json file. We need it so that we don't get errors from integration components that don't use the import type.

{
  // ...
  "compilerOptions": {
    // ...
    "verbatimModuleSyntax": false
  }
}

Now your Contentful SDK is ready. To see a full list of available methods, check out the API Reference.

What next?

With your frontend application ready, it's time to prepare a corresponding setup in Contentful. Fortunately, Alokai ships with a pre-defined set of Content Types matching your frontend components. Proceed to the Bootstrapping Contentful guide to find out how you can import them into your space.