Vue Storefront is now Alokai! Learn More
Setup for Next

Setup for Next

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 Next 13 application, this guide explains how to get started.

Tested with these CLI options

The procedures described in this guide have been tested on a fresh Next 13 project created with the following CLI options:

- Would you like to use TypeScript? … Yes
- Would you like to use ESLint? … Yes
- Would you like to use Tailwind CSS? … No
- Would you like to use `src/` directory? … No
- Would you like to use App Router? (recommended) … No
- Would you like to customize the default import alias (@/*)? … Yes
- What import alias would you like configured? … ~/*

We cannot guarantee they will work correctly with a Next 13 project created with different options.

Requirements

Something's missing?

If you don't have a Next 13 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.

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

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

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

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

Enabling dynamic pages

If there is an index.tsx file in your src/pages directory - delete it. Otherwise - once you run your application - it will conflict with the [[slug]].tsx component responsible for rendering dynamic CMS pages.

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 @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 load these fonts to your project is by importing them at the very top of the Next's globals.css file:

@import url('https://fonts.googleapis.com/css2?family=Red+Hat+Display:wght@400;500;700&display=swap');
@import url('https://fonts.googleapis.com/css2?family=Red+Hat+Text:wght@300;400;500;700&display=swap');

To complete the font setup, add the Storefront UI typography plugin to your Tailwind config file:

const sfTypography = require('@storefront-ui/typography');

module.exports = {
  // ...
  plugins: [sfTypography],
};

Adjusting the global.css file

We recommend deleting all default Next style rules present in the globals.css file. At the very least, consider deleting the ones responsible for setting a gray background on your Next pages:

body {
  background: linear-gradient(
      to bottom,
      transparent,
      rgb(var(--background-end-rgb))
    )
    rgb(var(--background-start-rgb)
  );
}

Also, we recommend changing the extension of the global file from css to scss. This is the format we use in our Alokai Storefront projects.

Configuring Next images

Add the following images configuration to your next.config.js file:

module.exports = {
  // ...
  images: {
    remotePatterns: [
      {
        hostname: '*',
        protocol: 'https',
      },
    ],
  }
}

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.js file 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 core is described in detail in our Key concepts: SDK docs.

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

import { contentfulModule, ContentfulModuleType } from '@vsf-enterprise/contentful-sdk';
import { createSdk } from '@vue-storefront/next';

export const { getSdk } = createSdk({ middleware: { apiUrl: '' } }, ({ buildModule }) => ({
  contentful: buildModule<ContentfulModuleType>(contentfulModule, {
    apiUrl: 'http://localhost:8181/cntf',
  }),
}));

export type Sdk = ReturnType<typeof getSdk>;

Next, create a new SdkProvider.ts file with the following content:

import { createSdkContext } from '@vue-storefront/next/client';
import { getSdk } from './sdk.config';

export const [SdkProvider, useSdk] = createSdkContext(getSdk());

Finally, create an index.ts barrel file exporting everything:

export * from './sdk.config';
export * from './SdkProvider';

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.