Edgio
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 production runtime targets Node 14.x. There may be some unexpected behavior building your project with a later version. See the Node.js guide for more information.

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.

With npm:

Bash
1npm i -g @edgio/cli

With yarn:

Bash
1yarn global add @edgio/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.

  2. 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 edgio init:

Bash
1edgio init

This will automatically update your package.json and add all of the required Edgio dependencies and files to your project. These include:

  • The @edgio/core package - Allows you to declare routes and deploy your application on Edgio
  • The @edgio/prefetch package - Allows you to configure a service worker to prefetch and cache pages to improve browsing speed
  • edgio.config.js - A configuration file for Edgio
  • routes.js - A default routes file that sends all requests to Shopify Hydrogen.

Update Edgio Configuration

Update edgio.config.js at the root of your project to the following:

JavaScript
1// This file was automatically added by edgio deploy.
2// You should commit this file to source control.
3module.exports = {
4 connector: './myconnector'
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 myconnector at the root of your project.

    • Create a file called build.js within the myconnector folder that contains the following content:
    JavaScriptmyconnector/build.js
    1const {join} = require('path');
    2 const {exit} = require('process');
    3 const {nodeFileTrace} = require('@vercel/nft');
    4 const {DeploymentBuilder} = require('@edgio/core/deploy');
    5 const {isYarn} = require('@edgio/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 that contains the following content:
    JavaScriptmyconnector/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 edgio 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('@edgio/core/router')
7
8module.exports = new Router()
9 // Prevent search engine bot(s) from indexing
10 // Read more on: https://docs.edg.io/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 CDN-as-code 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
1edgio build

Run Edgio on your local machine:

Bash
1edgio 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
1edgio build

Next, deploy the build to Edgio by running the edgio deploy command:

Bash
1edgio deploy

Refer to the Deployments guide for more information on the deploy command and its options.