Custom Installation
Use this guide if you have a custom setup and are not using the standard Alokai Enterprise Storefront installation. If you project does use Storefront, see our Quick Start guide.
Prerequisites
- SAP Commerce Cloud configured - Before following this guide, make sure you have an already configured SAP Commerce Cloud project. It includes creating and configuring:
- at least one Website in
WCMS > Websitestab, - at least one Base Store connected to your Website in
Base Commerce > Base Storetab, - an OAuth Client in
System > OAuth > OAuth Clientstab, - a Catalog in the
Catalog > Catalogstab, - a Catalog version in the
Catalog > Catalog Versionstab.
- at least one Website in
- Install Node.js version >= 16.0 and < 19.0.
Using the integration
In this section, we will explain in a step-by-step guide how to initialize and use SAPCC integration in your front-end application.
Middleware preparation
First, we need to prepare the server middleware. It's an Express.js application that is running on the server-side. It's used to create a server-to-server connection with the SAP Commerce Cloud backend and the server middleware.
Key concept - Middleware You can learn more in-depth about Middleware in the Alokai Middleware documentation.
- Install
@vue-storefront/middlewarepackage. This package is used to create the server middleware.
yarn add @vue-storefront/middleware consola ts-node-devnpm i @vue-storefront/middleware consola ts-node-devpnpm i @vue-storefront/middleware consola ts-node-dev- Install the SAP Commerce Cloud API Client. This package is used to create a connection with the SAP Commerce Cloud backend and build endpoints for the server middleware.
yarn add @vsf-enterprise/sapcc-apinpm i @vsf-enterprise/sapcc-apipnpm i @vsf-enterprise/sapcc-api- Create a file
middleware.config.tswith server middleware configuration.
Middleware directory
Since different frameworks have their own middleware, we recommend creating a separate directory for the Alokai middleware, for example, server or middleware, and put all the middleware-related files there.
For the purpose of this guide, we will use the server directory.
// server/middleware.config.ts
require("dotenv").config();
export const integrations = {
sapcc: {
location: "@vsf-enterprise/sapcc-api/server",
configuration: {
OAuth: {
uri: process.env.SAPCC_OAUTH_URI,
clientId: process.env.SAPCC_OAUTH_CLIENT_ID,
clientSecret: process.env.SAPCC_OAUTH_CLIENT_SECRET,
tokenEndpoint: process.env.SAPCC_OAUTH_TOKEN_ENDPOINT,
tokenRevokeEndpoint: process.env.SAPCC_OAUTH_TOKEN_REVOKE_ENDPOINT,
cookieOptions: {
"vsf-sap-token": { secure: process.env.NODE_ENV !== "development" },
},
},
api: {
uri: process.env.SAPCC_API_URI,
baseSiteId: process.env.DEFAULT_BASE_SITE_ID,
catalogId: process.env.DEFAULT_CATALOG_ID,
catalogVersion: process.env.DEFAULT_CATALOG_VERSION,
defaultLanguage: process.env.DEFAULT_LANGUAGE,
defaultCurrency: process.env.DEFAULT_CURRENCY,
},
},
},
};- Configure environment variables in your
.envfile.
# server/.env
SAPCC_OAUTH_URI=
SAPCC_OAUTH_CLIENT_ID=
SAPCC_OAUTH_CLIENT_SECRET=
SAPCC_OAUTH_TOKEN_ENDPOINT=
SAPCC_OAUTH_TOKEN_REVOKE_ENDPOINT=
SAPCC_API_URI=
DEFAULT_BASE_SITE_ID=
DEFAULT_CATALOG_ID=
DEFAULT_CATALOG_VERSION=
DEFAULT_LANGUAGE=
DEFAULT_CURRENCY=- Create a
index.tsfile insidesrcfolder. This script is used to run the server middleware.
// server/src/index.ts
import { createServer } from "@vue-storefront/middleware";
import { integrations } from "../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: { name: string }) => 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, () => {
consola.success(`API server listening on http://${host}:${port}`);
});
})();- Export the
Endpointsinterface asSapccEndpointsfrom theserver/types.d.tsfile. This interface contains the endpoints for the SAPCC integration that are going to be used in the SDK.
// server/types.d.ts
export { Endpoints as SapccEndpoints } from "@vsf-enterprise/sapcc-api";- Let's setup a script to run the server middleware. Add the following script to your
package.jsonfile.
{
"scripts": {
"dev": "ts-node-dev src/index.ts"
}
}- Run the server middleware.
yarn devYour server middleware is now running on http://localhost:8181 and SAPCC endpoints are available on http://localhost:8181/sapcc.
SDK preparation
Next, we need to prepare the SDK. The SDK is a package that is used to communicate with the server middleware.
Key concept - SDK You can learn more in-depth about SDK in the Alokai SDK documentation.
Based on your project setup, you can use the SDK in three different ways. Please select the one that fits your project.
Installation
Next.js SDK module is based on the Alokai SDK Core. In order to use the Next.js SDK module, first you need to install the SDK Core.
# Using yarn
yarn add @vue-storefront/sdk
# Using npm
npm install @vue-storefront/sdk
# Using pnpm
pnpm install @vue-storefront/sdkOnce SDK Core is installed, you can proceed to install Next.js SDK module. Enter the command below in the root of your project to install Next.js SDK module:
# Using yarn
yarn add --dev @vue-storefront/next
# Using pnpm
pnpm add -D @vue-storefront/next
# Using npm
npm install --save-dev @vue-storefront/nextInitializing the SDK
To use the SDK in our application, we need to initialize it first. To do so, follow these steps:
- Create SDK Config file -
sdk.config.tsin root directory of your project.
It is not necessary to name the file sdk.config.ts specifically or to keep it in the root of your project, but it is recommended to keep it consistent with the rest of the Alokai project.
- Create the SDK configuration by importing the
createSdkfunction from the Next.js SDK and the modules you want to use.
import { CreateSdkOptions, createSdk } from "@vue-storefront/next";
import { SapccEndpoints } from "../server/types";
const options: CreateSdkOptions = {
middleware: {
apiUrl: "http://localhost:8181",
},
};
export const { getSdk, createSdkContext } = createSdk(
options,
({ buildModule, middlewareUrl, middlewareModule, getRequestHeaders }) => ({
sapcc: buildModule(middlewareModule<SapccEndpoints>, {
apiUrl: middlewareUrl + "/sapcc",
defaultRequestConfig: {
headers: getRequestHeaders(),
},
}),
})
);Let's break down the code above:
-
The
createSdkfunction expects- base SDK options including the middleware and (optionally) the multistore configuration as a first argument,
- and a factory function for the SDK configuration as a second argument. Those factory function receives a context, useful for creating the SDK configuration.
-
The
buildModulefunction is used to build the module. It expects the module and the module configuration as arguments. -
The
middlewareUrlis the URL of the middleware instance. -
The
getRequestHeadersfunction is used to retrieve the Cookie header with cookie values. -
The
createSdkfunction returns- the
getSdkfunction, which is used to create the new SDK instance, - and the
createSdkContextfunction, which is used to create the SDK context, to share the same SDK instance on the Client side.
- the
Registering the SDK
Once you have initialized the SDK, you can register it in your application.
Alokai SDK can be used in two ways:
-
getSdk - returns the SDK instance, which can be used to call the SDK methods directly. This is useful for server-side rendering, as it allows you to call the SDK methods directly in your application.
-
createSdkContext - returns the SDK context, which can be used to share the same SDK instance on the Client side. This is useful for client-side rendering, as it allows you to share the same SDK instance across your application.
getSdk
getSdk is used to create the new SDK instance. This is especially useful for server-side fetching, as it returns a new SDK instance that can be used to call the SDK methods directly in your application.
Below is an example of how you can use getSdk in your application:
import { getSdk } from "../sdk.config";
const sdk = getSdk();createSdkContext
For client-side rendering, you can use createSdkContext. In order to use it, you'll need to create a new file in your application, for example hooks/sdk.ts:
import { createSdkContext } from "@vue-storefront/next/client";
import { getSdk } from "../sdk.config";
export const [SdkProvider, useSdk] = createSdkContext(getSdk());Once you have created the SDK context, you can register it in your application. For example, if you're using the Pages Router, you can register it in pages/_app.tsx:
import type { AppProps } from "next/app";
import { SdkProvider } from "../hooks";
export default function App({ Component, pageProps }: AppProps) {
return (
<SdkProvider>
<Component {...pageProps} />
</SdkProvider>
);
}If you're using the App Router, you can register it in app/layout.tsx:
import { ReactNode } from "react";
import { Providers } from "./providers";
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
);
}"use client";
import { ReactNode } from "react";
import { SdkProvider } from "../hooks";
export function Providers({ children }: { children: ReactNode }) {
return <SdkProvider>{children}</SdkProvider>;
}Don't be alarmed if you see a use client directive in the app/providers.tsx file. This will not turn your application into a client-side rendered application. All children inside the provider will be still rendered on the server-side by default. You can read more about use client directive in React Documentation.
Usage
Once you have registered the SDK in your application, you can start using it. Here's an example of how you can use the SAP Commerce Cloud SDK module in your application:
import { getSdk } from "../sdk.config";
export function getServersideProps() {
const sdk = getSdk();
const { products } = await sdk.sapcc.searchProduct();
return {
props: {
products,
},
};
}import { getSdk } from "../sdk.config";
const sdk = getSdk();
const { products } = await sdk.sapcc.searchProduct();import { useEffect, useState } from "react";
import { useSdk } from "../hooks";
export function ClientComponentUsingSDK() {
const sdk = useSdk();
const [cart, setCart] = useState([]);
useEffect(() => {
const fetchCart = async () => {
const newCart = await sdk.sapcc.getCart({
cartId: "<cart_id>",
fields: "code,guid,user(FULL)",
});
setCart(newCart);
};
fetchCart();
}, []);
}For more information about the available methods, please refer to the respective Integration's documentation.
That's it! You can now use Alokai SDK Module in your Next.js app ✨
Installation
Nuxt SDK module is based on the Alokai SDK Core. In order to use the Nuxt SDK module, first you need to install the SDK Core.
# Using yarn
yarn add @vue-storefront/sdk
# Using npm
npm install @vue-storefront/sdk
# Using pnpm
pnpm install @vue-storefront/sdkOnce SDK Core is installed, you can proceed to install Nuxt SDK module. Enter the command below in the root of your project to install Nuxt SDK module:
- Add
@vue-storefront/nuxtdependency to your project
# Using yarn
yarn add --dev @vue-storefront/nuxt
# Using pnpm
pnpm add -D @vue-storefront/nuxt
# Using npm
npm install --save-dev @vue-storefront/nuxt- Add
@vue-storefront/nuxtto themodulessection ofnuxt.config.ts
export default defineNuxtConfig({
modules: ["@vue-storefront/nuxt"],
});- Configure the module
To configure the module, use vsf key in the Nuxt configuration object and provide necessary information such as the Middleware instance address:
export default defineNuxtConfig({
modules: ["@vue-storefront/nuxt"],
vsf: {
middleware: {
apiUrl: "http://localhost:8181",
},
},
});Initializing the SDK
To use SDK in our application, we need to initialize it first. To do so, follow these steps:
Create SDK Config file - sdk.config.ts in root directory of your project.
For Nuxt, it's necessary to name the file sdk.config.ts and keep it in the root of your project.
You should import all other SDK configuration components. See the example below illustrating the SDK configuration with SAP Commerce Cloud module.
import { SapccEndpoints } from "../server/types";
export default defineSdkConfig(
({ buildModule, middlewareUrl, middlewareModule, getRequestHeaders }) => ({
sapcc: buildModule(middlewareModule<SapccEndpoints>, {
apiUrl: middlewareUrl + "/sapcc",
defaultRequestConfig: {
headers: getRequestHeaders(),
},
}),
})
);Let's break down the code above:
The defineSdkConfig function is used for intializing the SDK. The parameter for calling this function should be an anonymous function that receives an injected context from the module, containing:
- the
buildModulefunction, - the middleware URL (
middlewareUrl), - a function for retrieving the Cookie header with cookie values (
getCookieHeader).
Usage
Once you have initialized the SDK, you can start using it. Here's an example of how you can use the SAP Commerce Cloud SDK module in your application:
<template>/* ... */</template>
<script setup>
const sdk = useSdk();
const { data: products } = await useAsyncData("products", () =>
sdk.sapcc.searchProduct()
);
</script>For more information about the available methods, please refer to the respective Integration's documentation.
That's it! You can now use Alokai SDK Module in your Nuxt app ✨
Installation
To install the SDK Core, run the following command:
npm install @vue-storefront/sdkyarn add @vue-storefront/sdkpnpm install @vue-storefront/sdkInitializing the SDK
Next, you have to initialize the SDK, along with any integrations' SDK modules in your frontend project. To do so, follow these steps:
- Create SDK Config file -
sdk.config.tsin root directory of your project.
It is not necessary to name the file sdk.config.ts specifically or to keep it in the root of your project, but it is recommended to keep it consistent with the rest of the Alokai project.
- Create the SDK configuration by importing the
initSDKfunction from the SDK Core and the modules you want to use.
The examples below use the SAP Commerce Cloud and Contentful SDK modules. However, the same principles apply to all modules.
When it comes to managing multiple SDK modules, there are two options for this:
- Individual exports (recommended) - initialize each integration as a separate SDK instance, allowing for better code-splitting
- Single Instance - combine multiple modules in one SDK instance
Individual Exports
import { initSDK, buildModule, middlewareModule } from "@vue-storefront/sdk";
import { SapccEndpoints } from "../server/types";
const { commerce } = initSDK({
sapcc: buildModule(middlewareModule<SapccEndpoints>, {
apiUrl: "http://localhost:8181/sapcc",
}),
});
export { commerce };Single Instance
import { initSDK, buildModule, middlewareModule } from "@vue-storefront/sdk";
import { SapccEndpoints } from "../server/types";
const sdkConfig = {
sapcc: buildModule(middlewareModule<SapccEndpoints>, {
apiUrl: "http://localhost:8181/sapcc",
}),
};
export const sdk = initSDK(sdkConfig);The SDK Core exposes two methods to help with this, buildModules, which takes in SDK modules and uses them to extend the SDK Core, and initSDK, which takes multiple modules and converts them into a type-safe interface.
You can name the modules anything you want.
For example, you can rename commerce to sapcc and cms to contentful. initSDK will return an object with the same keys as the one passed to it.
Usage
Once you have initialized the SDK, you can start using it. Here's an example of how you can use the SAP Commerce Cloud SDK module in your application:
import { commerce } from "../sdk.config";
const { products } = await commerce.searchProduct();import { sdk } from "../sdk.config";
const { products } = await sdk.commerce.searchProduct();For more information about the available methods, please refer to the respective Integration's documentation.
That's it! You can now use Alokai SDK Module in any JavaScript app ✨
OpenAPI SDK
Need more types? Extending the SAP Commerce Cloud integration? You might need the @vsf-enterprise/sap-commerce-webservices-sdk package, which includes the definitions of the types of SAP Commerce Webservices.