Edgio

Shopify Hydrogen

This guide shows you how to deploy a Shopify Hydrogen application on Edgio.

Example

Shopify Hydrogen Requirements

You’ve installed the following dependencies:
Yarn version 1.x or npm
Node.js version 16.5.0 or higher
Edgio Applications’s support for Node.js version 16 is undergoing end-of-life. View the end-of-life plan.

Sign up for Edgio

Deploying requires an account on Edgio. Sign up here for free.

Install the Edgio CLI

If you have not already done so, install the Edgio CLI
Bash
1npm i -g @layer0/cli # yarn global add @layer0/cli

Create a new Shopify Hydrogen app

If you don’t already have a Shopify Hydrogen app, create one by running the following:
Bashnpm
1# JavaScript template
2npm init @shopify/hydrogen -- --template demo-store-js
3
4OR
5
6# TypeScript template
7npm init @shopify/hydrogen -- --template demo-store-ts
Bashyarn
1# JavaScript template
2yarn create @shopify/hydrogen --template demo-store-js
3
4OR
5
6# TypeScript template
7yarn create @shopify/hydrogen --template demo-store-ts
You can verify your app works by running it locally with:
Bash
1npm run dev

Enable Server Side Rendering

  1. To enable server side rendering with your Shopify Hydrogen app, build it with target set to node with command as:
Bash
1npm run build -- --target node
2
3OR
4
5yarn build --target node
The production version of your app will be running at http://localhost:3000. You can inspect and deploy the compiled version of your Node.js Hydrogen storefront from dist/node.
NOTE: This step will be auto configured when building with Edgio as you follow the next steps.
  1. Apply middleware
Create a server.js at the root of your project consisting of the following:
JavaScriptserver.js
1const {createServer} = require('./dist/node');
2
3createServer().then(({app}) => {
4 app.listen(process.env.PORT || 3000, () => {
5 console.log(`Server ready`);
6 });
7});

Configuring your Shopify Hydrogen app for Edgio

Initialize your project

In the root directory of your project run 0 init:
Bash
10 init
This will automatically update your package.json and add all of the required Edgio dependencies and files to your project. These include:
  • The @layer0/core package - Allows you to declare routes and deploy your application on Edgio
  • The @layer0/prefetch package - Allows you to configure a service worker to prefetch and cache pages to improve browsing speed
  • layer0.config.js - A configuration file for Edgio
  • routes.js - A default routes file that sends all requests to Shopify Hydrogen.

Update Edgio Configuration

Update layer0.config.js at the root of your project to the following:
JavaScript
1// This file was automatically added by layer0 deploy.
2// You should commit this file to source control.
3module.exports = {
4 connector: './layer0'
5}

Creating Edgio connector files

  • Install @vercel/nft for Node.js File Tracing, by the following command:
    Bash
    1npm install @vercel/nft
    2
    3OR
    4
    5yarn add @vercel/nft
  • Create a folder named layer0 at the root of your project.
    • Create a file inside the layer0 folder, named build.js consistng of the following:
    JavaScriptlayer0/build.js
    1const {join} = require('path');
    2 const {exit} = require('process');
    3 const {nodeFileTrace} = require('@vercel/nft');
    4 const {DeploymentBuilder} = require('@layer0/core/deploy');
    5 const {isYarn} = require('@layer0/cli/utils/packageManager');
    6
    7 const appDir = process.cwd();
    8 const builder = new DeploymentBuilder(appDir);
    9
    10 module.exports = async function build(options) {
    11 try {
    12 builder.clearPreviousBuildOutput();
    13 let command = 'npm run build -- --target node';
    14 if (isYarn()) {
    15 command = 'yarn build --target node';
    16 }
    17 await builder.exec(command);
    18 builder.addJSAsset(join(appDir, 'dist'));
    19 builder.addJSAsset(join(appDir, 'server.js'));
    20 // Determine the node_modules to include
    21 let dictNodeModules = await getNodeModules();
    22 Object.keys(dictNodeModules).forEach(async (i) => {
    23 await builder.addJSAsset(`${appDir}/${i}`);
    24 });
    25 await builder.build();
    26 } catch (e) {
    27 console.log(e);
    28 exit();
    29 }
    30 };
    31
    32 async function getNodeModules() {
    33 // The whole app inside index.js
    34 const files = ['./dist/node/index.js'];
    35 // Compute file trace
    36 const {fileList} = await nodeFileTrace(files);
    37 // Store set of packages
    38 let packages = {};
    39 fileList.forEach((i) => {
    40 if (i.includes('node_modules/')) {
    41 let temp = i.replace('node_modules/', '');
    42 temp = temp.substring(0, temp.indexOf('/'));
    43 packages[`node_modules/${temp}`] = true;
    44 } else {
    45 packages[i] = true;
    46 }
    47 });
    48 // Sort the set of packages
    49 return Object.keys(packages)
    50 .sort()
    51 .reduce((obj, key) => {
    52 obj[key] = packages[key];
    53 return obj;
    54 }, {});
    55 }
    • Create a file named prod.js consistng of the following:
    JavaScriptlayer0/prod.js
    1module.exports = async function prod(port) {
    2 process.env.PORT = port;
    3 await import('../server.js');
    4 };

Configure the routes

Update routes.js at the root of your project to the following:
JavaScript
1// This file was added by layer0 init.
2// You should commit this file to source control.
3const ONE_HOUR = 60 * 60
4const ONE_DAY = 24 * ONE_HOUR
5
6const { Router } = require('@layer0/core/router')
7
8module.exports = new Router()
9 // Prevent search engine bot(s) from indexing
10 // Read more on: https://docs.layer0.co/guides/cookbook#blocking-search-engine-crawlers
11 .noIndexPermalink()
12 .match('/assets/:path*', ({ cache }) => {
13 cache({
14 edge: {
15 maxAgeSeconds: ONE_DAY,
16 forcePrivateCaching: true,
17 },
18 browser: {
19 maxAgeSeconds: 0,
20 serviceWorkerSeconds: ONE_DAY,
21 },
22 })
23 })
24 .match('/', ({ cache }) => {
25 cache({
26 edge: {
27 maxAgeSeconds: ONE_DAY,
28 },
29 browser: false,
30 })
31 })
32 .match('/collections/:path*', ({ cache }) => {
33 cache({
34 edge: {
35 maxAgeSeconds: ONE_DAY,
36 },
37 browser: false,
38 })
39 })
40 .match('/products/:path*', ({ cache }) => {
41 cache({
42 edge: {
43 maxAgeSeconds: ONE_DAY,
44 forcePrivateCaching: true,
45 },
46 browser: {
47 maxAgeSeconds: 0,
48 serviceWorkerSeconds: ONE_DAY,
49 },
50 })
51 })
52 .fallback(({ renderWithApp }) => renderWithApp())
Refer to the Routing guide for the full syntax of the routes.js file and how to configure it for your use case.

Run the Shopify Hydrogen app locally on Edgio

Create a production build of your app by running the following in your project’s root directory:
Bash
10 build
Run Edgio on your local machine:
Bash
10 run --production
Load the site http://127.0.0.1:3000

Deploying

Create a production build of your app by running the following in your project’s root directory:
Bash
10 build
Next, deploy the build to Edgio by running the 0 deploy command:
Bash
10 deploy
Refer to the Deploying guide for more information on the deploy command and its options.