create-sitecore-jss 22.3.0-canary.1 → 22.3.0-canary.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,10 +12,3 @@ PROXY_HOST=http://localhost:3000
12
12
 
13
13
  # Your XM Cloud Proxy server path is needed to build the app. The build output will be copied to the proxy server path.
14
14
  PROXY_BUILD_PATH=<%- locals.relativeProxyAppDestination.replace(/\\/g, '\\\\') %>dist
15
-
16
- # ==============================================
17
-
18
- # An optional Sitecore Personalize scope identifier.
19
- # This can be used to isolate personalization data when multiple XM Cloud Environments share a Personalize tenant.
20
- # This should match the PAGES_PERSONALIZE_SCOPE environment variable for your connected XM Cloud Environment.
21
- PERSONALIZE_SCOPE=
@@ -0,0 +1,55 @@
1
+ # Angular for XMCloud
2
+
3
+ > Sitecore JSS Angular App for XM Cloud. For the current release this feature is experimental.
4
+
5
+ [Documentation](<TODO>)
6
+
7
+ This Single Page Application (SPA) built with Angular is designed to be fully compatible with XM Cloud, incorporating several key add-ons and features to streamline the development process and enable seamless integration. The supported key features are as follows:
8
+
9
+ - `Context ID`: The Context ID environment variable simplifies setting up and configuring XM Cloud solutions. It's a unified identifier that maps to all your configured resources, such as content, sites, files, forms, and integration settings.
10
+
11
+ - `Pages new editing integration via HTTP render engine endpoint`: Before JSS 22.1, JSS Next.js apps integrated with Sitecore editors through chromes, where data was sent via a POST request. With the 22.1 release, a new metadata method was introduced, rendering the app inside an iframe in XM Cloud Pages, offering benefits like faster load times, simpler configuration, and direct local host connections without tunneling.
12
+
13
+ - `XM Cloud proxy personalization` with embedded personalization and A/B Component Test support.
14
+
15
+ - `Forms support`: provides the capability to consume and post Sitecore Forms from JSS apps. Sitecore Forms is a form-authoring framework that enables marketers to author their own forms, collect data, and analyze form performance.
16
+
17
+ This SPA is tailored to enhance development workflows and enable full utilization of XM Cloud’s capabilities, providing a seamless and efficient foundation for developers.
18
+
19
+ ## Components and Supporting Applications
20
+
21
+ The following components and supporting applications have been added to the Angular base app to ensure compatibility with XM Cloud:
22
+
23
+ - `XM Cloud Angular`: Adds support for the Sitecore Context data, which simplifies connecting the application to XM Cloud and configuring the integration of multiple composable Sitecore products. Angular app provides components and can be used during development. Once the app is built and its build artifacts are copied into the proxy, the proxy app can be used to connect to an XMCloud instance and render its content (including personalization etc).
24
+
25
+ - `XM Cloud Proxy`: Adds integration with XMCloud for the JSS SPA applications and enables editing, personalization and A/B component testing support.
26
+
27
+ ## Environment Variables
28
+
29
+ The following environment variables can be set to configure the angular app. You can use the `.env` file located in the root of the app or set these directly in the environment (for example, in containers).
30
+
31
+ | Parameter | Description |
32
+ | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
33
+ | `PROXY_HOST` | Your XM Cloud Proxy hostname is needed to build the app and execute the client-side requests against the proxy server. Default value `http://localhost:3000` |
34
+ | `PROXY_BUILD_PATH` | Your XM Cloud Proxy server path is needed to build the app. The build output will be copied to the XMCloud Proxy application path. Default value `<xmcloud_proxy_path>\dist`.
35
+ | `SITECORE_EDGE_CONTEXT_ID` | The Context ID, which covers many system configurations, required for connecting to the XM Cloud back end. This is an XM Cloud system environment variable. When the application runs on the XM Cloud rendering host, this value is always set to the preview Context ID. |
36
+ | `SITECORE_API_KEY` | The API key for GRAPH_QL_ENDPOINT authentication. For Experience Edge, you can find the API key in the Sites dashboard by opening the actions menu for a site and navigating to Settings > Developer settings. Copy the value for SITECORE_API_KEY. For a preview endpoint (a CM instance either on XM Cloud or locally), use your preview API Key from the CM instance.
37
+ | `SITECORE_API_HOST` | The API hostname, needed to build the application. This should be used in combination with SITECORE_API_KEY for local development or local container setup. For example, https://<xmc_cm_host>.sitecorecloud.io. |
38
+ | `GRAPH_QL_ENDPOINT` | Your GraphQL Edge endpoint. This is typically optional. By default, the endpoint is calculated using the resolved Sitecore API hostname + the `graphQLEndpointPath` defined in your `package.json`. For a preview endpoint (a CM instance on XM Cloud or a local one), the value is <xmc_cm_host>/sitecore/api/graph/edge. |
39
+ | `SITECORE_SITE_NAME` | The name of your site. This variable overrides the config.appName defined in the package.json file. You can find this value in the Sites dashboard by opening the actions menu for a site and navigating to Settings > Developer settings. Default value `<appName>`,
40
+ ` |
41
+ | `DEFAULT_LANGUAGE` | The default language of your app. Default value `en` |
42
+ | `DEBUG` | Optional. Debug level for the proxy. Set the DEBUG environment variable to 'sitecore-jss:*,proxy*,http-proxy-middleware*' to see all logs. Refer to the [official docs](https://doc.sitecore.com/xp/en/developers/hd/latest/sitecore-headless-development/debug-logging-in-jss-apps.html#namespaces) for all the available namespaces.
43
+
44
+ ## Build & run
45
+
46
+ Build your Angular SPA app bundle with `jss build` or `npm run build`. The build output should be placed in the `dist` folder and will automatically get copied to the proxy app.
47
+
48
+ To run your app in production mode. Go to the proxy app:
49
+
50
+ 1. Run `npm install`
51
+
52
+ 2. Run `npm run start`
53
+
54
+ You should be able to see the following message:
55
+ `server listening on port 3000!`.
@@ -8,8 +8,8 @@
8
8
  "prepare:proxy-build": "ts-node --project src/tsconfig.webpack-server.json ./scripts/proxy-build.ts"
9
9
  },
10
10
  "dependencies": {
11
- "@sitecore-cloudsdk/core": "^0.4.0-rc.0",
12
- "@sitecore-cloudsdk/events": "^0.4.0-rc.0",
11
+ "@sitecore-cloudsdk/core": "^0.4.1",
12
+ "@sitecore-cloudsdk/events": "^0.4.1",
13
13
  "font-awesome": "^4.7.0",
14
14
  "sass": "^1.52.3",
15
15
  "sass-alias": "^1.0.5"
@@ -5,12 +5,12 @@ import { layoutServiceFactory } from './src/app/lib/layout-service-factory';
5
5
  import { environment } from './src/environments/environment';
6
6
  import { components } from './src/app/components/app-components.module';
7
7
  import metadata from './src/environments/metadata.json';
8
-
9
8
  /**
10
9
  * Define the required configuration values to be exported from the server.bundle.ts.
11
10
  */
12
11
 
13
12
  const defaultLanguage = environment.defaultLanguage;
13
+ const sitecoreSiteName = environment.sitecoreSiteName;
14
14
  const getClientFactoryConfig = getGraphQLClientFactoryConfig;
15
15
 
16
16
  export {
@@ -19,6 +19,7 @@ export {
19
19
  dictionaryServiceFactory,
20
20
  layoutServiceFactory,
21
21
  defaultLanguage,
22
+ sitecoreSiteName,
22
23
  components,
23
24
  metadata,
24
25
  };
@@ -28,10 +28,9 @@ export const getGraphQLClientFactoryConfig = () => {
28
28
  : getEdgeProxyContentUrl(env.sitecoreEdgeContextId, env.proxyHost),
29
29
  };
30
30
  } else if (env.graphQLEndpoint && env.sitecoreApiKey) {
31
- const graphQLEndpointPath = new URL(env.graphQLEndpoint).pathname;
32
-
31
+ // we ignore ssr-proxy and query CM directly in case apiKey is used (i.e. in dev docker deployments)
33
32
  clientConfig = {
34
- endpoint: isServer ? env.graphQLEndpoint : `${env.proxyHost}${graphQLEndpointPath}`,
33
+ endpoint: env.graphQLEndpoint,
35
34
  apiKey: env.sitecoreApiKey,
36
35
  };
37
36
  }
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "dependencies": {
3
- "@sitecore/components": "~2.0.0",
4
- "@sitecore-cloudsdk/core": "^0.4.0",
5
- "@sitecore-cloudsdk/events": "^0.4.0",
6
- "@sitecore-feaas/clientside": "^0.5.17"
3
+ "@sitecore/components": "~2.0.1",
4
+ "@sitecore-cloudsdk/core": "^0.4.1",
5
+ "@sitecore-cloudsdk/events": "^0.4.1",
6
+ "@sitecore-feaas/clientside": "^0.5.19"
7
7
  }
8
8
  }
@@ -21,7 +21,6 @@ class PersonalizePlugin implements MiddlewarePlugin {
21
21
  order = 1;
22
22
 
23
23
  constructor() {
24
-
25
24
  this.personalizeMiddleware = new PersonalizeMiddleware({
26
25
  // Configuration for your Sitecore Experience Edge endpoint
27
26
  edgeConfig: {
@@ -12,3 +12,14 @@ PROXY_BUNDLE_PATH=
12
12
 
13
13
  # Set the DEBUG environment variable to 'sitecore-jss:*,sitecore-jss:proxy,http-proxy-middleware*' to see all logs:
14
14
  #DEBUG=sitecore-jss:*,http-proxy-middleware*
15
+
16
+ # An optional Sitecore Personalize scope identifier.
17
+ # This can be used to isolate personalization data when multiple XM Cloud Environments share a Personalize tenant.
18
+ # This should match the PAGES_PERSONALIZE_SCOPE environment variable for your connected XM Cloud Environment.
19
+ PERSONALIZE_SCOPE=
20
+
21
+ # Timeout (ms) for Sitecore CDP requests to respond within. Default is 400.
22
+ PERSONALIZE_MIDDLEWARE_CDP_TIMEOUT=
23
+
24
+ # Timeout (ms) for Sitecore Experience Edge requests to respond within. Default is 400.
25
+ PERSONALIZE_MIDDLEWARE_EDGE_TIMEOUT=
@@ -2,35 +2,129 @@
2
2
 
3
3
  > Sitecore JSS Proxy for XM Cloud is considered experimental.
4
4
 
5
- [Documentation](<TODO>)
5
+ [Documentation](TODO)
6
+
7
+ This proxy will serve as the backbone for supporting various SPA frameworks by handling server-side rendering (SSR), data queries, and middleware functionalities.
6
8
 
7
9
  This is a sample setup showing one of how you can configure XM Cloud rendering server.
8
10
 
9
- ## Pre-requisites
11
+ ## Features Supported
10
12
 
11
- 1. SPA sample supports XM Cloud out of the box.
13
+ - `Context ID`: The Context ID environment variable simplifies setting up and configuring XM Cloud solutions. It's a unified identifier that maps to all your configured resources, such as content, sites, files, forms, and integration settings.
14
+
15
+ - `Pages new editing integration via HTTP render engine endpoint`: Before JSS 22.1, JSS Next.js apps integrated with Sitecore editors through chromes, where data was sent via a POST request. With the 22.1 release, a new metadata method was introduced, rendering the app inside an iframe in XM Cloud Pages, offering benefits like faster load times, simpler configuration, and direct local host connections without tunneling.
16
+
17
+ - `XM Cloud proxy personalization` with embedded personalization and A/B Component Test support.
18
+
19
+ - `Forms support`: provides the capability to consume and post Sitecore Forms from JSS apps. Sitecore Forms is a form-authoring framework that enables marketers to author their own forms, collect data, and analyze form performance.
20
+
21
+ ## Configuration Setup
22
+
23
+ The config.ts file in this proxy app handles essential configurations for server-side rendering, data queries, and middleware functionalities. Here are the main configurations defined:
24
+
25
+ - Server Bundle Configuration:
26
+
27
+ - The app loads a server.bundle.js file, pre-built from your SPA app, for SSR support.
28
+ - This file contains the configuration and factory functions essential for rendering and data querying.
29
+
30
+ - GraphQL Endpoint Setup:
12
31
 
13
- 1. Build your SPA app bundle with `jss build`. The build output should be placed in the `dist` folder.
32
+ - Defines a graphQLEndpoint for handling Sitecore GraphQL requests. It differentiates between production (Sitecore Edge) and development (Sitecore CM) endpoints.
33
+ - Constructs the target URL and path for proxy requests, ensuring compliance with http-proxy-middleware requirements.
14
34
 
15
- ## Setup
35
+ - Port Configuration:
16
36
 
17
- Open `config.js` and specify your application settings.
37
+ - Configures the port for running the proxy, with a default of 3000 or an environment-specified port.
38
+
39
+ - Personalization Configuration (personalizeConfig):
40
+
41
+ - Sets up Sitecore personalization through PersonalizeConfig, defining settings for both Sitecore Experience Edge and CDP endpoints.
42
+ - Contains options to control personalization features, including:
43
+ - Timeouts for Edge and CDP endpoints (default 400ms, configurable via environment variables).
44
+ - Scope and site name used for Sitecore Personalize.
45
+ - Enable/Disable Switch: Functions that allow you to conditionally disable personalization based on the environment (e.g., disabled in development mode) and cookie consent policy.
46
+ - Language Configuration: defaultLanguage serves as a fallback if language data is unavailable in layout data.
47
+
48
+ This configuration is designed to be flexible and secure, with dynamic settings managed via environment variables where appropriate.
18
49
 
19
50
  ### Environment Variables
20
51
 
21
52
  The following environment variables can be set to configure the Proxy sample instead of modifying `config.js`. You can use the `.env` file located in the root of the app or set these directly in the environment (for example, in containers).
22
53
 
23
- | Parameter | Description |
24
- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
25
- | `PROXY_BUNDLE_PATH` | Path to the JSS SPA app's `server.bundle.js`. Default can be seen in [config.js](./config.js) file. |
26
- | `PROXY_PORT` | Optional. Port which will be used when start sample. Default can be seen in [config.js](./config.js) file. |
27
- | `DEBUG` | Optional. Debug level for the proxy. Set the DEBUG environment variable to 'sitecore-jss:*,proxy*,http-proxy-middleware*' to see all logs. |
54
+ | Parameter | Description |
55
+ | ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
56
+ | `PROXY_BUNDLE_PATH` | Path to the JSS SPA app's `server.bundle.js`. Default can be seen in [config.js](./config.js) file. |
57
+ | `PROXY_PORT` | Optional. Port which will be used when start sample. Default can be seen in [config.js](./config.js) file. |
58
+ | `DEBUG` | Optional. Debug level for the proxy. Set the DEBUG environment variable to 'sitecore-jss:_,proxy_,http-proxy-middleware\*, 'sitecore-jss:layout','sitecore-jss:personalize' to see all logs. |
59
+
60
+ ## Pre-requisites
61
+
62
+ 1. SPA sample supports XM Cloud out of the box.
63
+
64
+ 2. Build your SPA app bundle with `jss build` or `npm run build`. The build output should be placed in the `dist` folder. |
28
65
 
29
66
  ## Build & run
30
67
 
31
68
  1. Run `npm install`
32
69
 
33
- 1. Run `npm run start`
70
+ 2. Run `npm run start`
34
71
 
35
72
  You should be able to see the following message:
36
73
  `server listening on port 3000!`.
74
+
75
+ ## Deploy to Netlify
76
+
77
+ `NOTE: If you are using the Angular starter from the XM-Cloud Foundation repository within a monorepo, please skip to Step 3.`
78
+
79
+ 1. Run `npm init` in the root directory and add the following scripts to package.json:
80
+ ```
81
+ "build": "cd ./<your-proxy-app-name> && npm run build-all && cd ..",
82
+ "install": "cd ./<your-proxy-app-name> && npm install && npm run install-all && cd ..",
83
+ ```
84
+ 2. Ensure that `<your-proxy-app-name>/package.json` includes the following commands to handle the build and install steps properly::
85
+ ```
86
+ "build-all": "cd ../angular && npm run build && cd ../<your-proxy-app-name> && tsc",
87
+ "install-all": "cd ../angular && npm i && cd ../<your-proxy-app-name>"
88
+ ```
89
+ 3. Add `serverless-http` to the list of dependencies in `<your-proxy-app-name>/package.json` and then add the following variable to your ``<your-proxy-app-name>/src/index.ts` file.
90
+ ```
91
+ export const handler = serverless(server);
92
+ ```
93
+ 4. Create a `netlfiy.toml` file if not already created and ensure that the following Netlify configuration is added there:
94
+ - Following functions lets the proxy app to treated as netlify functions. [Functions Overview](https://docs.netlify.com/functions/overview/)
95
+ ```
96
+ [functions]
97
+ directory = "<your-proxy-app-name>/src"
98
+ node_bundler = "esbuild"
99
+ included_files = ["<your-proxy-app-name>/dist/**"]
100
+ ```
101
+ - To ensure that static assets are accessed properly we may need to add redirects statement for them to the toml file:
102
+ ```
103
+ [[redirects]]
104
+ from = "/dist/browser/*"
105
+ status = 200
106
+ to = "/browser/:splat"
107
+ ```
108
+ - To ensure that static files under /dist are not accessible via browser add `force=true` to the above
109
+ ```
110
+ [[redirects]]
111
+ from = "/*"
112
+ status = 200
113
+ to = "/.netlify/functions/index/:splat"
114
+ force = true
115
+ ```
116
+ - Build command
117
+ ```
118
+ [build]
119
+ command = "npm run build"
120
+ publish = "<your-proxy-app-name>/dist"
121
+ ```
122
+ 5. Create your netlify deployment: [A Step-by-Step Guide: Deploying on Netlify | Netlify](https://www.netlify.com/blog/2016/09/29/a-step-by-step-guide-deploying-on-netlify/)
123
+ a. Set up all your necessary environment variables like SITECORE_EDGE_CONTEXT_ID, SITECORE_SITE_NAME etc.
124
+ b. Set up your build settings in Site configuration --> Build and Deploy tab.
125
+ sample configuration:
126
+ Base Directory: /
127
+ Build command: npm run build
128
+ Publish directory: /proxy/dist
129
+ Functions directory: /proxy/src
130
+ NOTE: If proxy/dist folder is not picked up properly by Netlify make sure that the `PROXY_BUILD_PATH` env variable is unix style path e.g. `../proxy/dist`
@@ -1,5 +1,5 @@
1
1
  import { Config, ServerBundle } from './types';
2
-
2
+ import { PersonalizeConfig } from '@sitecore-jss/sitecore-jss-proxy';
3
3
  /**
4
4
  * The server.bundle.js file from your pre-built SPA app.
5
5
  */
@@ -13,6 +13,39 @@ try {
13
13
  throw new Error(`ERROR: The server.bundle.js error. ${error}`);
14
14
  }
15
15
 
16
+ const clientFactoryConfig = serverBundle.getClientFactoryConfig();
17
+
18
+ /**
19
+ * GraphQL endpoint resolution to meet the requirements of the http-proxy-middleware
20
+ */
21
+ export const graphQLEndpoint = (() => {
22
+ try {
23
+ const graphQLEndpoint = new URL(clientFactoryConfig.endpoint);
24
+ // GraphQL endpoint URL (Edge endpoint for production and GraphQL Sitecore CM endpoint for dev)
25
+ const graphQLEndpointUrl = `${graphQLEndpoint.protocol}//${graphQLEndpoint.hostname}`;
26
+ // Sitecore Edge Context ID - will only be present for production
27
+ const sitecoreEdgeContextId = graphQLEndpoint.searchParams.get('sitecoreContextId');
28
+ // Browser request path to the proxy. Includes only the pathname.
29
+ const pathname = graphQLEndpoint.pathname;
30
+ // Target URL for the proxy. Can't include the query string.
31
+ const target = `${graphQLEndpointUrl}${pathname}`;
32
+
33
+ return {
34
+ target,
35
+ path: pathname,
36
+ graphQLEndpointUrl,
37
+ sitecoreEdgeContextId,
38
+ };
39
+ } catch (error) {
40
+ throw new Error(
41
+ `ERROR: The serverBundle should export a getClientFactoryConfig function with valid GraphQL endpoint URL returned, current value is ${clientFactoryConfig.endpoint}. ` +
42
+ 'Please check your server bundle.'
43
+ );
44
+ }
45
+ })();
46
+
47
+ const { clientFactory } = serverBundle;
48
+
16
49
  export const config: Config = {
17
50
  /**
18
51
  * The require'd server.bundle.js file from your pre-built SPA app.
@@ -23,3 +56,36 @@ export const config: Config = {
23
56
  */
24
57
  port: process.env.PROXY_PORT || 3000,
25
58
  };
59
+
60
+ export const personalizeConfig: PersonalizeConfig = {
61
+ // Configuration for your Sitecore Experience Edge endpoint
62
+ edgeConfig: {
63
+ clientFactory,
64
+ timeout:
65
+ (process.env.PERSONALIZE_MIDDLEWARE_EDGE_TIMEOUT &&
66
+ parseInt(process.env.PERSONALIZE_MIDDLEWARE_EDGE_TIMEOUT)) ||
67
+ 400,
68
+ },
69
+ // Configuration for your Sitecore CDP endpoint
70
+ // Edge URL and ID can be taken from proxy env, or the base SPA app
71
+ cdpConfig: {
72
+ sitecoreEdgeUrl: graphQLEndpoint.graphQLEndpointUrl,
73
+ sitecoreEdgeContextId: graphQLEndpoint.sitecoreEdgeContextId || '',
74
+ timeout:
75
+ (process.env.PERSONALIZE_MIDDLEWARE_CDP_TIMEOUT &&
76
+ parseInt(process.env.PERSONALIZE_MIDDLEWARE_CDP_TIMEOUT)) ||
77
+ 400,
78
+ },
79
+ // Optional Sitecore Personalize scope identifier.
80
+ scope: process.env.PERSONALIZE_SCOPE,
81
+ // This function determines if the personalization should be turned off.
82
+ // IMPORTANT: You should implement based on your cookie consent management solution of choice.
83
+ // You may wish to keep it disabled while in development mode.
84
+ // Personalization will also be disabled when edge context id is missing
85
+ disabled: () => process.env.NODE_ENV === 'development' || !graphQLEndpoint.sitecoreEdgeContextId,
86
+ // This function determines if a route should be excluded from personalization.
87
+ excludeRoute: () => false,
88
+ sitecoreSiteName: serverBundle.sitecoreSiteName || '',
89
+ // defaultLanguage will be used as fallback for personalization, if language cannot be read from layout service data
90
+ defaultLanguage: serverBundle.defaultLanguage,
91
+ };
@@ -1,11 +1,11 @@
1
1
  import 'dotenv/config';
2
2
  import express, { Response } from 'express';
3
3
  import compression from 'compression';
4
- import { createProxyMiddleware } from 'http-proxy-middleware';
4
+ import { createProxyMiddleware, fixRequestBody } from 'http-proxy-middleware';
5
5
  import { debug } from '@sitecore-jss/sitecore-jss';
6
- import { editingRouter } from '@sitecore-jss/sitecore-jss-proxy';
7
- import { healthCheck } from '@sitecore-jss/sitecore-jss-proxy';
8
- import { config } from './config';
6
+ import { editingRouter, healthCheck } from '@sitecore-jss/sitecore-jss-proxy';
7
+ import { config, graphQLEndpoint } from './config';
8
+ import { personalizeHelper, personalizePlugin } from './personalize';
9
9
 
10
10
  const server = express();
11
11
 
@@ -45,31 +45,6 @@ const layoutService = layoutServiceFactory.create();
45
45
 
46
46
  const dictionaryService = dictionaryServiceFactory.create();
47
47
 
48
- const clientFactoryConfig = config.serverBundle.getClientFactoryConfig();
49
-
50
- /**
51
- * GraphQL endpoint resolution to meet the requirements of the http-proxy-middleware
52
- */
53
- const graphQLEndpoint = (() => {
54
- try {
55
- const graphQLEndpoint = new URL(clientFactoryConfig.endpoint);
56
- // Browser request path to the proxy. Includes only the pathname.
57
- const pathname = graphQLEndpoint.pathname;
58
- // Target URL for the proxy. Can't include the query string.
59
- const target = `${graphQLEndpoint.protocol}//${graphQLEndpoint.hostname}${pathname}`;
60
-
61
- return {
62
- target,
63
- path: pathname,
64
- };
65
- } catch (error) {
66
- throw new Error(
67
- `ERROR: The serverBundle should export a getClientFactoryConfig function with valid GraphQL endpoint URL returned, current value is ${clientFactoryConfig.endpoint}. ` +
68
- 'Please check your server bundle.'
69
- );
70
- }
71
- })();
72
-
73
48
  /**
74
49
  * Parse requested url in order to detect current route and language
75
50
  * @param {string} reqRoute requested route
@@ -105,6 +80,8 @@ const handleError = (res: Response, err: unknown) => {
105
80
 
106
81
  // enable gzip compression for appropriate file types
107
82
  server.use(compression());
83
+ // enable access to req.body
84
+ server.use(graphQLEndpoint.path, express.json());
108
85
 
109
86
  // turn off x-powered-by http header
110
87
  server.settings['x-powered-by'] = false;
@@ -125,6 +102,12 @@ server.use(
125
102
  createProxyMiddleware({
126
103
  target: graphQLEndpoint.target,
127
104
  changeOrigin: true,
105
+ selfHandleResponse: true,
106
+ on: {
107
+ proxyReq: fixRequestBody,
108
+ },
109
+ // for client-side routing, personalization is performed by modifying layout service response
110
+ plugins: [personalizePlugin],
128
111
  })
129
112
  );
130
113
 
@@ -165,11 +148,17 @@ server.use(async (req, res) => {
165
148
  }
166
149
 
167
150
  // Language is required. In case it's not specified in the requested URL, fallback to the default language from the app configuration.
168
- const layoutData = await layoutService.fetchLayoutData(
151
+ let layoutData = await layoutService.fetchLayoutData(
169
152
  route,
170
153
  lang || config.serverBundle.defaultLanguage
171
154
  );
172
-
155
+ // for SSR loading routing, personalization is performed by modifying layoutData directly
156
+ const personalizedLayoutData = await personalizeHelper.personalizeLayoutData(
157
+ req,
158
+ res,
159
+ layoutData
160
+ );
161
+ layoutData = personalizedLayoutData;
173
162
  const viewBag = { dictionary: {} };
174
163
 
175
164
  viewBag.dictionary = await dictionaryService.fetchDictionaryData(
@@ -0,0 +1,34 @@
1
+ import { GRAPHQL_LAYOUT_QUERY_NAME, PersonalizeHelper } from '@sitecore-jss/sitecore-jss-proxy';
2
+ import { personalizeConfig } from './config';
3
+ import { responseInterceptor } from 'http-proxy-middleware';
4
+ import { Plugin } from 'http-proxy-middleware/dist/types';
5
+ import { IncomingMessageWithBody } from './types';
6
+
7
+ export const personalizeHelper = new PersonalizeHelper(personalizeConfig);
8
+
9
+ // personalize plugin to modify intercepted Layout Service request data
10
+ export const personalizePlugin: Plugin = (proxyServer) => {
11
+ proxyServer.on(
12
+ 'proxyRes',
13
+ responseInterceptor(async (responseBuffer, _, req, res) => {
14
+ let responseText = responseBuffer.toString('utf8');
15
+ const payload = JSON.stringify((req as IncomingMessageWithBody).body);
16
+
17
+ // only apply personalization onto JSS layout service results
18
+ if (payload.includes(GRAPHQL_LAYOUT_QUERY_NAME)) {
19
+ let layoutDataRaw = JSON.parse(responseText);
20
+ if (!layoutDataRaw?.data?.layout?.item?.rendered?.sitecore) {
21
+ return responseText;
22
+ }
23
+ const personalizedLayout = await personalizeHelper.personalizeLayoutData(
24
+ req as IncomingMessageWithBody,
25
+ res,
26
+ layoutDataRaw?.data?.layout?.item?.rendered
27
+ );
28
+ layoutDataRaw.data.layout.item.rendered = personalizedLayout;
29
+ responseText = JSON.stringify(layoutDataRaw);
30
+ }
31
+ return responseText;
32
+ })
33
+ );
34
+ };
@@ -1,3 +1,4 @@
1
+ /* eslint-disable no-unused-vars */
1
2
  import {
2
3
  GraphQLRequestClientFactory,
3
4
  GraphQLRequestClientFactoryConfig,
@@ -6,6 +7,7 @@ import { DictionaryService } from '@sitecore-jss/sitecore-jss/i18n';
6
7
  import { Metadata } from '@sitecore-jss/sitecore-jss/utils';
7
8
  import { LayoutService } from '@sitecore-jss/sitecore-jss/layout';
8
9
  import { AppRenderer, RouteUrlParser } from '@sitecore-jss/sitecore-jss-proxy';
10
+ import { IncomingMessage } from 'http';
9
11
 
10
12
  export interface ServerBundle {
11
13
  [key: string]: unknown;
@@ -14,6 +16,7 @@ export interface ServerBundle {
14
16
  clientFactory: GraphQLRequestClientFactory;
15
17
  getClientFactoryConfig: () => GraphQLRequestClientFactoryConfig;
16
18
  defaultLanguage: string;
19
+ sitecoreSiteName: string;
17
20
  layoutServiceFactory: { create: () => LayoutService };
18
21
  dictionaryServiceFactory: { create: () => DictionaryService };
19
22
  components: string[] | Map<string, unknown>;
@@ -25,3 +28,10 @@ export interface Config {
25
28
  port: string | number;
26
29
  serverBundle: ServerBundle;
27
30
  }
31
+
32
+ /**
33
+ * IncomingMessage type modified with exporess.json() call to include request body
34
+ */
35
+ export type IncomingMessageWithBody = IncomingMessage & {
36
+ body: ReadableStream<Uint8Array> | null;
37
+ };
@@ -46,17 +46,16 @@
46
46
  "@apollo/client": "^3.7.4",
47
47
  "@panter/vue-i18next": "~0.15.2",
48
48
  "@sitecore-jss/sitecore-jss-vue": "~22.3.0-canary",
49
- "@vue/apollo-composable": "4.0.0-beta.2",
50
- "@vue/apollo-option": "^4.0.0-alpha.20",
51
- "@vue/apollo-ssr": "^4.0.0-alpha.18",
52
- "@vue/server-renderer": "^3.2.45",
49
+ "@vue/apollo-composable": "4.2.1",
50
+ "@vue/apollo-option": "^4.0.0",
51
+ "@vue/apollo-ssr": "^4.0.0",
53
52
  "axios": "^1.2.3",
54
53
  "bootstrap": "^5.2.3",
55
54
  "cross-fetch": "~3.1.5",
56
55
  "graphql": "^16.6.0",
57
56
  "register-service-worker": "~1.7.2",
58
57
  "serialize-javascript": "^6.0.1",
59
- "vue": "^3.2.45",
58
+ "vue": "^3.5.12",
60
59
  "vue-i18n": "9.1.10",
61
60
  "vue-meta": "3.0.0-alpha.10",
62
61
  "vue-router": "4.0.16"
@@ -69,7 +68,6 @@
69
68
  "@vue/cli-plugin-babel": "~5.0.8",
70
69
  "@vue/cli-plugin-eslint": "~5.0.8",
71
70
  "@vue/cli-service": "~5.0.8",
72
- "@vue/compiler-sfc": "^3.2.45",
73
71
  "@vue/eslint-config-prettier": "~7.0.0",
74
72
  "chalk": "~4.1.2",
75
73
  "chokidar": "~3.5.3",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-sitecore-jss",
3
- "version": "22.3.0-canary.1",
3
+ "version": "22.3.0-canary.11",
4
4
  "description": "Sitecore JSS initializer",
5
5
  "bin": "./dist/index.js",
6
6
  "scripts": {
@@ -63,5 +63,5 @@
63
63
  "ts-node": "^10.9.1",
64
64
  "typescript": "~4.9.5"
65
65
  },
66
- "gitHead": "204eb3427f26d4ba8c08f44cf9c772f19f2820a8"
66
+ "gitHead": "0c8193ab38c6cd4e7aafb151741b1401f8427b71"
67
67
  }