From 4042b372dc58b45bdcd712dc9efe0f25fad41693 Mon Sep 17 00:00:00 2001 From: Adam Brauer <400763+ambrauer@users.noreply.github.com> Date: Tue, 7 Dec 2021 14:57:09 -0600 Subject: [PATCH 1/3] node-headless-ssr-proxy initializer/template added --- .../node-headless-ssr-proxy/index.ts | 15 ++ .../src/templates/nextjs/.vscode/launch.json | 15 ++ .../.vscode/launch.json | 48 +++++ .../node-headless-ssr-proxy/LICENSE.txt | 202 ++++++++++++++++++ .../node-headless-ssr-proxy/README.md | 58 +++++ .../cacheMiddleware.js | 56 +++++ .../node-headless-ssr-proxy/config.js | 152 +++++++++++++ .../node-headless-ssr-proxy/error.html | 200 +++++++++++++++++ .../node-headless-ssr-proxy/httpAgents.js | 42 ++++ .../node-headless-ssr-proxy/index.js | 48 +++++ .../node-headless-ssr-proxy/package.json | 35 +++ 11 files changed, 871 insertions(+) create mode 100644 packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts create mode 100644 packages/create-sitecore-jss/src/templates/nextjs/.vscode/launch.json create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/.vscode/launch.json create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/LICENSE.txt create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/README.md create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/cacheMiddleware.js create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/config.js create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/error.html create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/index.js create mode 100644 packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json diff --git a/packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts b/packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts new file mode 100644 index 0000000000..863d1dcb63 --- /dev/null +++ b/packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts @@ -0,0 +1,15 @@ +import path from 'path'; +import { Initializer } from '../../common/Initializer'; +import { transform } from '../../common/steps/index'; +import { BaseArgs } from '../../common/args/base'; + +export class NodeHeadlessSsrProxyInitializer implements Initializer { + async init(args: BaseArgs) { + const templatePath = path.resolve(__dirname, '../../templates/node-headless-ssr-proxy'); + await transform(templatePath, args); + + return { + appName: 'node-headless-ssr-proxy', + }; + } +} diff --git a/packages/create-sitecore-jss/src/templates/nextjs/.vscode/launch.json b/packages/create-sitecore-jss/src/templates/nextjs/.vscode/launch.json new file mode 100644 index 0000000000..897f7fd0ae --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/nextjs/.vscode/launch.json @@ -0,0 +1,15 @@ +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "name": "Attach to Process", + "type": "node", + "request": "attach", + "skipFiles": ["/**"], + "port": 9229 + } + ] +} diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/.vscode/launch.json b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/.vscode/launch.json new file mode 100644 index 0000000000..301bb6e51c --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/.vscode/launch.json @@ -0,0 +1,48 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Launch", + "type": "node", + "request": "launch", + "program": "${workspaceRoot}/index.js", + "stopOnEntry": false, + "args": [ + "doc" + ], + "cwd": "${workspaceRoot}", + "preLaunchTask": null, + "runtimeExecutable": null, + "runtimeArgs": [ + "--nolazy" + ], + "env": { + "NODE_ENV": "development" + }, + "console": "internalConsole", + "sourceMaps": false, + "outFiles": [] + }, + { + "name": "Attach", + "type": "node", + "request": "attach", + "port": 3000, + "address": "localhost", + "restart": false, + "sourceMaps": false, + "outFiles": [], + "localRoot": "${workspaceRoot}", + "remoteRoot": null + }, + { + "name": "Attach to Process", + "type": "node", + "request": "attach", + "processId": "${command.PickProcess}", + "port": 5858, + "sourceMaps": false, + "outFiles": [] + } + ] +} \ No newline at end of file diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/LICENSE.txt b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/LICENSE.txt new file mode 100644 index 0000000000..d645695673 --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/README.md b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/README.md new file mode 100644 index 0000000000..18690465ee --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/README.md @@ -0,0 +1,58 @@ +# node/express scaffolding for SSR outside of Sitecore Content Delivery + +This is a sample setup showing one one of how you can configure rendering server on top of node.js and Express. + +The setup is using `sitecore-jss-proxy` that enables request proxying to Sitecore CD along with the http cookies to enable tracking, personalization and contact identification. + +> This is a sample setup that is not officially supported by Sitecore. + +You can use this as a starting point to unlock deployment of your JSS apps to any managed node.js hosting environment (Azure App Service, Heroku, IBM BlueMix, you name it). + +## Pre-requisites + +1. Your Sitecore instance needs to be configured with JSS.Server and the API Key provisioned. Read more [here](https://jss.sitecore.com/docs/getting-started/jss-server-install) how to set it up. + + > LayoutService API should be returning output if you make the following request to your Sitecore instance. `http://sitecore-host/sitecore/api/layout/render/jss?item=/&sc_apikey={YOUR_API_KEY}` + +1. Build your JS app bundle with `jss build`. + + > You can use any of the JSS sample apps. Other apps must support server side rendering (JSS integrated mode) to operate with this project. + +1. Deploy the build artifacts from your app (`/dist` or `/build` within the app) to the `sitecoreDistPath` set in your app's `package.json` under the proxy root path. Most apps use `/dist/${jssAppName}`, for example `$proxyRoot/dist/${jssAppName}`. + +> Another way to deploy the artifacts to the proxy is to change the `instancePath` in your app's `scjssconfig.json` to the proxy root path, and then use `jss deploy files` within the app to complete the deployment to the proxy. + +## Setup + +Open `config.js` and specify your application bundle and connection settings to your Sitecore CD instance. `config.js` is heavily commented for your perusal. + +### Environment Variables + +The following environment variables can be set to configure the proxy instead of modifying `config.js`, for environments where this is more desirable like containers: + +| Parameter | Description | +| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `SITECORE_JSS_APP_NAME` | The JSS app's name. Used in dictionary service URL, and the default value of `SITECORE_JSS_SERVER_BUNDLE` if it's not set. | +| `SITECORE_JSS_SERVER_BUNDLE` | Path to the JSS app's `server.bundle.js` file. | +| `SITECORE_API_HOST` | Sitecore instance host name. Should be HTTPS in production. | +| `SITECORE_LAYOUT_SERVICE_ROUTE` | Optional. The path to layout service for the JSS application. Defaults to `/sitecore/api/layout/render/jss`. | +| `SITECORE_API_KEY` | The Sitecore SSC API key your app uses. | +| `SITECORE_PATH_REWRITE_EXCLUDE_ROUTES` | Optional. Pipe-separated list of absolute paths that should not be rendered through SSR. Defaults can be seen in [config.js](./config.js). | +| `SITECORE_ENABLE_DEBUG` | Optional. Writes verbose request info to stdout for debugging. Defaults to `false`. | + +## Build & run + +1. Run `npm install` + +1. Run `npm run start` + +You should be able to see the following message: +`server listening on port 3000!` and see all the communication between this server and your Sitecore CD instance in the console. + +More info on this setup can be found [here](https://jss.sitecore.com/docs/fundamentals/application-modes#headless-server-side-rendering-mode). + +## Production Notes + +- Ensure that `debug: false` in `config.js`. Console output will cause terrible scaling. +- Customise `error.html` in case your app throws HTTP 500 errors. +- Load test the proxy prior to launch to ensure proper performance levels for your needs. diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/cacheMiddleware.js b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/cacheMiddleware.js new file mode 100644 index 0000000000..42aa61d289 --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/cacheMiddleware.js @@ -0,0 +1,56 @@ +//cacheMiddleware for Node-level output caching + +const mcache = require('memory-cache'); + +// List of urls that will be skipped during caching +const EXCLUDED_PATHS = [ + 'layouts/system', + 'sitecore/api/jss/dictionary', + '/sitecore/api/layout' +] + +/** + * @param {string} method request method + * @param {string} url request url + * @returns {boolean} is path excluded + */ +const isExcludedPath = (method, url) => { + const containsExcludedPath = !!EXCLUDED_PATHS.find(path => url.includes(path)); + + return method !== 'GET' || containsExcludedPath; +} + +/** + * Cache requests during {@link duration} that aren't excluded in {@link EXCLUDED_PATHS} + * @param {number} duration The number of milliseconds to cache request + */ +const cacheMiddleware = (duration = 10000) => (req, res, next) => { + if (isExcludedPath(req.method, req.originalUrl)) return next(); + + const key = '__proxy_cache__' + req.originalUrl || req.url + const cachedBody = mcache.get(key) + + if (cachedBody) { + res.send(cachedBody); + return; + } + + const { end: _end, write: _write } = res; + let buffer = new Buffer.alloc(0); + + // Rewrite response method and get the content. + res.write = data => { + buffer = Buffer.concat([buffer, data]); + }; + + res.end = () => { + const body = buffer.toString(); + mcache.put(key, body, duration); + _write.call(res, body); + _end.call(res); + }; + + next() +} + +module.exports = cacheMiddleware; \ No newline at end of file diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/config.js b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/config.js new file mode 100644 index 0000000000..49e44cccfb --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/config.js @@ -0,0 +1,152 @@ +const fs = require('fs'); +const { RestDictionaryService } = require('@sitecore-jss/sitecore-jss'); +const httpAgents = require("./httpAgents"); + +/** + * The JSS application name defaults to providing part of the bundle path as well as the dictionary service endpoint. + * If not passed as an environment variable or set here, any application name exported from the bundle will be used instead. + */ +let appName = process.env.SITECORE_JSS_APP_NAME; + +/** + * The server.bundle.js file from your pre-built JSS app + */ +const bundlePath = process.env.SITECORE_JSS_SERVER_BUNDLE || `./dist/${appName}/server.bundle`; + +const serverBundle = require(bundlePath); + +httpAgents.setUpDefaultAgents(serverBundle); + +const apiHost = process.env.SITECORE_API_HOST || 'http://my.sitecore.host' + +appName = appName || serverBundle.appName; + +const apiKey = process.env.SITECORE_API_KEY || serverBundle.apiKey || '{YOUR API KEY HERE}'; + +const dictionaryService = new RestDictionaryService({ + apiHost, + siteName: appName, + apiKey, + cacheTimeout: 60, +}); + +/** + * @type {ProxyConfig} + */ +const config = { + /** + * The require'd server.bundle.js file from your pre-built JSS app + */ + serverBundle, + /** + * apiHost: your Sitecore instance hostname that is the backend for JSS + * Should be https for production. Must be https to use SSC auth service, + * if supporting Sitecore authentication. + */ + apiHost, + /** + * layoutServiceRoot: The path to layout service for the JSS application. + * Some apps, like advanced samples, use a custom LS configuration, + * e.g. /sitecore/api/layout/render/jss-advanced-react + */ + layoutServiceRoute: + process.env.SITECORE_LAYOUT_SERVICE_ROUTE || '/sitecore/api/layout/render/jss', + /** + * apiKey: The Sitecore SSC API key your app uses. + * Required. + */ + apiKey, + /** + * pathRewriteExcludeRoutes: A list of absolute paths + * that are NOT app routes and should not attempt to render a route + * using SSR. These route prefixes are directly proxied to the apiHost, + * allowing the proxy to also proxy GraphQL requests, REST requests, etc. + * Local static assets, Sitecore API paths, Sitecore asset paths, etc should be listed here. + * URLs will be encoded, so e.g. for a space use '%20' in the exclude. + * + * Need to perform logic instead of a flat list? Remove this and use + * pathRewriteExcludePredicate function instead: (url) => boolean; + */ + pathRewriteExcludeRoutes: [ + '/assets', + '/sitecore/api', + '/api', + '/-/jssmedia', + '/-/media', + '/layouts/system', + ].concat((process.env.SITECORE_PATH_REWRITE_EXCLUDE_ROUTES || '').split('|')), + /** + * Writes verbose request info to stdout for debugging. + * Must be disabled in production for reasonable performance. + */ + debug: ((process.env.SITECORE_ENABLE_DEBUG || '').toLowerCase() === 'true') || false, + /** + * Maximum allowed proxy reply size in bytes. Replies larger than this are not sent. + * Avoids starving the proxy of memory if large requests are proxied. + * Default: 10MB + */ + maxResponseSizeBytes: 10 * 1024 * 1024, + /** + * Options object for http-proxy-middleware. Consult its docs. + */ + proxyOptions: { + // Enable connection pooling + agent: httpAgents.getAgent(apiHost), + // Setting this to false will disable SSL certificate validation + // when proxying to a SSL Sitecore instance. + // This is a major security issue, so NEVER EVER set this to false + // outside local development. Use a real CA-issued certificate. + secure: true, + xfwd: true + }, + /** + * Custom headers handling. + * You can remove different headers from proxy response. + */ + setHeaders: (req, serverRes, proxyRes) => { + delete proxyRes.headers['content-security-policy']; + }, + /** + * Custom error handling in case our app fails to render. + * Return null to pass through server response, or { content, statusCode } + * to override server response. + * + * Note: 404s are not errors, and will have null route data + context sent to the JSS app, + * so the app can render a 404 route. + */ + onError: (err, response) => { + // http 200 = an error in rendering; http 500 = an error on layout service + if (response.statusCode !== 500 && response.statusCode !== 200) return null; + + return { + statusCode: 500, + content: fs.readFileSync('error.html', 'utf8'), + }; + }, + createViewBag: (request, response, proxyResponse, layoutServiceData) => { + // fetches the dictionary from the Sitecore server for the current language so it can be SSR'ed + // has a default cache applied since dictionary data is quite static and it helps rendering performance a lot + if (!layoutServiceData || !layoutServiceData.sitecore || !layoutServiceData.sitecore.context) { + return {}; + } + + // TODO: fallback language should come from app configuration + const language = layoutServiceData.sitecore.context.language || 'en'; + const site = + layoutServiceData.sitecore.context.site && layoutServiceData.sitecore.context.site.name; + + if (!site) { + return {}; + } + + return dictionaryService.fetchDictionaryData(language).then(phrases => { + const viewBag = { + dictionary: phrases, + }; + + return viewBag; + }); + }, +}; + +module.exports = config; diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/error.html b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/error.html new file mode 100644 index 0000000000..10ddd2e97c --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/error.html @@ -0,0 +1,200 @@ + + + + + + 500 Epic Fail + + + + + + +
+
+

An error has occurred

+
+
+ + + diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js new file mode 100644 index 0000000000..5e097a0cc6 --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js @@ -0,0 +1,42 @@ +const keepAlive = require("agentkeepalive"); +const http = require("http"); +const https = require("https"); + +const keepAliveConfig = { + maxSockets: 200, + maxFreeSockets: 20, + timeout: 240 * 1000, + freeSocketTimeout: 240 * 1000, +}; + +const httpAgent = new keepAlive(keepAliveConfig); +const httpsAgent = new keepAlive.HttpsAgent(keepAliveConfig); + +module.exports = { + setUpDefaultAgents: (serverBundle) => { + http.globalAgent = httpAgent; + https.globalAgent = httpsAgent; + + if (serverBundle.setUpDefaultAgents) { + serverBundle.setUpDefaultAgents(httpAgent, httpsAgent); + } + }, + /** + * Enable connection pooling. Adds `connection: keep-alive` header + * @param {string} url api host + */ + getAgent: (url) => { + if (!url) { + throw new Error("[KEEP-ALIVE-CONFIG] SITECORE_API_HOST value is required, but was undefined") + } + + if (!url.indexOf("http://")) return httpAgent; + + if (!url.indexOf("https://")) return httpsAgent; + + throw new Error( + "[KEEP-ALIVE-CONFIG] Unexpected SITECORE_API_HOST value, expected http:// or https://, but was " + + url + ); + }, +}; diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/index.js b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/index.js new file mode 100644 index 0000000000..dd12e29354 --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/index.js @@ -0,0 +1,48 @@ +const express = require('express'); +const compression = require('compression'); +const scProxy = require('@sitecore-jss/sitecore-jss-proxy').default; +const config = require('./config'); +const cacheMiddleware = require('./cacheMiddleware'); + +const server = express(); +const port = process.env.PORT || 3000; + +// enable gzip compression for appropriate file types +server.use(compression()); + +// turn off x-powered-by http header +server.settings['x-powered-by'] = false; + +// Serve static app assets from local /dist folder +server.use( + '/dist', + express.static('dist', { + fallthrough: false, // force 404 for unknown assets under /dist + }) +); + +/** + * Output caching, can be enabled, + * Read about restrictions here: {@link https://jss.sitecore.com/docs/techniques/performance/caching} + */ +// server.use(cacheMiddleware()); + +server.use((req, res, next) => { + // because this is a proxy, all headers are forwarded on to the Sitecore server + // but, if we SSR we only understand how to decompress gzip and deflate. Some + // modern browsers would send 'br' (brotli) as well, and if the Sitecore server + // supported that (maybe via CDN) it would fail SSR as we can't decode the Brotli + // response. So, we force the accept-encoding header to only include what we can understand. + if (req.headers['accept-encoding']) { + req.headers['accept-encoding'] = 'gzip, deflate'; + } + + next(); +}) + +// For any other requests, we render app routes server-side and return them +server.use('*', scProxy(config.serverBundle.renderView, config, config.serverBundle.parseRouteUrl)); + +server.listen(port, () => { + console.log(`server listening on port ${port}!`); +}); diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json new file mode 100644 index 0000000000..071883ce6d --- /dev/null +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json @@ -0,0 +1,35 @@ +{ + "name": "node-headless-ssr-proxy-sample", + "version": "20.0.0-canary", + "description": "Node server-side-rendering proxy sample for running JSS apps under Node hosting", + "main": "dist/index.js", + "scripts": { + "start": "node index.js" + }, + "engines": { + "node": ">=8.1", + "npm": ">=5.6.0" + }, + "author": { + "name": "Sitecore Corporation", + "url": "https://jss.sitecore.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sitecore/jss.git" + }, + "bugs": { + "url": "https://github.com/sitecore/jss/issues" + }, + "homepage": "https://jss.sitecore.com", + "license": "Apache-2.0", + "dependencies": { + "@sitecore-jss/sitecore-jss": "^20.0.0-canary", + "@sitecore-jss/sitecore-jss-proxy": "^20.0.0-canary", + "agentkeepalive": "^4.1.3", + "compression": "~1.7.3", + "express": "~4.16.4", + "memory-cache": "^0.2.0" + }, + "private": true +} From a901e6bffb4e8a069319dc4c9e375bd54127b031 Mon Sep 17 00:00:00 2001 From: Adam Brauer <400763+ambrauer@users.noreply.github.com> Date: Thu, 9 Dec 2021 11:01:58 -0600 Subject: [PATCH 2/3] Fixed formatting --- .../node-headless-ssr-proxy/httpAgents.js | 56 ++++++++-------- .../node-headless-ssr-proxy/package.json | 66 +++++++++---------- 2 files changed, 61 insertions(+), 61 deletions(-) diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js index 5e097a0cc6..f9f267bac6 100644 --- a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/httpAgents.js @@ -1,12 +1,12 @@ -const keepAlive = require("agentkeepalive"); -const http = require("http"); -const https = require("https"); +const keepAlive = require('agentkeepalive'); +const http = require('http'); +const https = require('https'); const keepAliveConfig = { - maxSockets: 200, - maxFreeSockets: 20, - timeout: 240 * 1000, - freeSocketTimeout: 240 * 1000, + maxSockets: 200, + maxFreeSockets: 20, + timeout: 240 * 1000, + freeSocketTimeout: 240 * 1000, }; const httpAgent = new keepAlive(keepAliveConfig); @@ -15,28 +15,28 @@ const httpsAgent = new keepAlive.HttpsAgent(keepAliveConfig); module.exports = { setUpDefaultAgents: (serverBundle) => { http.globalAgent = httpAgent; - https.globalAgent = httpsAgent; + https.globalAgent = httpsAgent; - if (serverBundle.setUpDefaultAgents) { - serverBundle.setUpDefaultAgents(httpAgent, httpsAgent); - } - }, - /** - * Enable connection pooling. Adds `connection: keep-alive` header - * @param {string} url api host - */ + if (serverBundle.setUpDefaultAgents) { + serverBundle.setUpDefaultAgents(httpAgent, httpsAgent); + } + }, + /** + * Enable connection pooling. Adds `connection: keep-alive` header + * @param {string} url api host + */ getAgent: (url) => { - if (!url) { - throw new Error("[KEEP-ALIVE-CONFIG] SITECORE_API_HOST value is required, but was undefined") - } - - if (!url.indexOf("http://")) return httpAgent; - - if (!url.indexOf("https://")) return httpsAgent; - - throw new Error( - "[KEEP-ALIVE-CONFIG] Unexpected SITECORE_API_HOST value, expected http:// or https://, but was " + - url - ); + if (!url) { + throw new Error('[KEEP-ALIVE-CONFIG] SITECORE_API_HOST value is required, but was undefined'); + } + + if (!url.indexOf('http://')) return httpAgent; + + if (!url.indexOf('https://')) return httpsAgent; + + throw new Error( + '[KEEP-ALIVE-CONFIG] Unexpected SITECORE_API_HOST value, expected http:// or https://, but was ' + + url + ); }, }; diff --git a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json index 071883ce6d..51b5c13acb 100644 --- a/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json +++ b/packages/create-sitecore-jss/src/templates/node-headless-ssr-proxy/package.json @@ -1,35 +1,35 @@ { - "name": "node-headless-ssr-proxy-sample", - "version": "20.0.0-canary", - "description": "Node server-side-rendering proxy sample for running JSS apps under Node hosting", - "main": "dist/index.js", - "scripts": { - "start": "node index.js" - }, - "engines": { - "node": ">=8.1", - "npm": ">=5.6.0" - }, - "author": { - "name": "Sitecore Corporation", - "url": "https://jss.sitecore.com" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/sitecore/jss.git" - }, - "bugs": { - "url": "https://github.com/sitecore/jss/issues" - }, - "homepage": "https://jss.sitecore.com", - "license": "Apache-2.0", - "dependencies": { - "@sitecore-jss/sitecore-jss": "^20.0.0-canary", - "@sitecore-jss/sitecore-jss-proxy": "^20.0.0-canary", - "agentkeepalive": "^4.1.3", - "compression": "~1.7.3", - "express": "~4.16.4", - "memory-cache": "^0.2.0" - }, - "private": true + "name": "node-headless-ssr-proxy-sample", + "version": "20.0.0-canary", + "description": "Node server-side-rendering proxy sample for running JSS apps under Node hosting", + "main": "dist/index.js", + "scripts": { + "start": "node index.js" + }, + "engines": { + "node": ">=8.1", + "npm": ">=5.6.0" + }, + "author": { + "name": "Sitecore Corporation", + "url": "https://jss.sitecore.com" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/sitecore/jss.git" + }, + "bugs": { + "url": "https://github.com/sitecore/jss/issues" + }, + "homepage": "https://jss.sitecore.com", + "license": "Apache-2.0", + "dependencies": { + "@sitecore-jss/sitecore-jss": "^20.0.0-canary", + "@sitecore-jss/sitecore-jss-proxy": "^20.0.0-canary", + "agentkeepalive": "^4.1.3", + "compression": "~1.7.3", + "express": "~4.16.4", + "memory-cache": "^0.2.0" + }, + "private": true } From 9043065d138625b156052484f879a3a907d685a9 Mon Sep 17 00:00:00 2001 From: Adam Brauer <400763+ambrauer@users.noreply.github.com> Date: Thu, 9 Dec 2021 15:07:15 -0600 Subject: [PATCH 3/3] changes after merge (implement new Initializer requirements) --- .../src/initializers/node-headless-ssr-proxy/index.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts b/packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts index 863d1dcb63..e0f022f47e 100644 --- a/packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts +++ b/packages/create-sitecore-jss/src/initializers/node-headless-ssr-proxy/index.ts @@ -3,7 +3,11 @@ import { Initializer } from '../../common/Initializer'; import { transform } from '../../common/steps/index'; import { BaseArgs } from '../../common/args/base'; -export class NodeHeadlessSsrProxyInitializer implements Initializer { +export default class NodeHeadlessSsrProxyInitializer implements Initializer { + get isBase(): boolean { + return true; + } + async init(args: BaseArgs) { const templatePath = path.resolve(__dirname, '../../templates/node-headless-ssr-proxy'); await transform(templatePath, args);