Skip to content

Commit

Permalink
Add proxy example
Browse files Browse the repository at this point in the history
  • Loading branch information
blittle committed Nov 21, 2022
1 parent fabaa55 commit 31c59c7
Show file tree
Hide file tree
Showing 6 changed files with 70 additions and 11 deletions.
1 change: 1 addition & 0 deletions packages/hydrogen-remix/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export * from '@shopify/hydrogen';

export {RESOURCE_TYPES, REQUIRED_RESOURCES} from './routing/types';
export {notFoundMaybeRedirect} from './routing/redirect';
export {proxyLiquidRoute} from './routing/proxy';

export type LoaderArgs = DataFunctionArgs & {
request: Request;
Expand Down
49 changes: 49 additions & 0 deletions packages/hydrogen-remix/src/routing/proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
export async function proxyLiquidRoute(
request: Request,
storefrontDomain: string,
destinationPath: string,
): Promise<Response> {
const clientIP = request.headers.get('X-Shopify-Client-IP');
const clientIPSig = request.headers.get('X-Shopify-Client-IP-Sig');

const headers = new Headers();
const host = `${storefrontDomain}.myshopify.com`;

const headersToFilterOut = ['connection'];

for (const [key, value] of request.headers.entries()) {
if (!headersToFilterOut.includes(key)) {
headers.append(
key,
swapHostname(value, {
hostname: new URL(request.url).host,
newHostname: host,
}),
);
}
}

if (!clientIP || !clientIPSig) {
console.warn(
'Proxying the online store is only available in Oxygen. This request is likely to be throttled.',
);
}

return fetch(
`https://${host}${
destinationPath.startsWith('/') ? destinationPath : '/' + destinationPath
}`,
{headers},
).then((resp) => {
const headers = new Headers(resp.headers);
headers.delete('content-encoding');
return new Response(resp.body, {headers});
});
}

function swapHostname(
str: string,
{hostname, newHostname}: {hostname: string; newHostname: string},
) {
return str.replaceAll(hostname, newHostname);
}
5 changes: 0 additions & 5 deletions templates/demo-store/app/entry.server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@ export default async function handleRequest(
responseHeaders: Headers,
remixContext: EntryContext,
) {
if (new URL(request.url).pathname === '/__health') {
// TODO: move this to @hydrogen/remix ?
return new Response(null, {status: 200});
}

const body = await renderToReadableStream(
<RemixServer context={remixContext} url={request.url} />,
);
Expand Down
2 changes: 1 addition & 1 deletion templates/demo-store/app/hooks/useDeferred.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ export function useDeferred(resource: string, route: RouteMatch) {
}

// the [resource] was awaited in the loader return it
return route.data[resource];
return route.data?.[resource];
}
8 changes: 4 additions & 4 deletions templates/demo-store/app/root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ import type {LayoutData} from '~/data';
export const handle = {
// @todo - remove any and type the seo callback
seo: (data: any) => ({
title: data.layout.shop.name,
title: data?.layout?.shop?.name,
bypassTitleTemplate: true,
titleTemplate: `%s | ${data.layout.shop.name}`,
titleTemplate: `%s | ${data?.layout?.shop?.name}`,
}),
};

Expand Down Expand Up @@ -103,7 +103,7 @@ export function CatchBoundary() {
<Links />
</head>
<body>
<Layout layout={root.data.layout}>
<Layout layout={root?.data?.layout}>
{isNotFound ? (
<NotFound type={caught.data?.pageType} />
) : (
Expand All @@ -129,7 +129,7 @@ export function ErrorBoundary({error}: {error: Error}) {
<Links />
</head>
<body>
<Layout layout={root.data.layout}>
<Layout layout={root?.data?.layout}>
<GenericError error={error} />
</Layout>
<Scripts />
Expand Down
16 changes: 15 additions & 1 deletion templates/demo-store/oxygen.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {createRequestHandler} from '@shopify/hydrogen-remix';
import {createRequestHandler, proxyLiquidRoute} from '@shopify/hydrogen-remix';
// The build remix app provided by remix build
import * as remixBuild from 'remix-build';
import {HydrogenSession} from '~/lib/session.server';
Expand All @@ -11,6 +11,12 @@ const requestHandler = createRequestHandler({
shouldProxyAsset: () => false,
});

const storefrontConfig = {
publicStorefrontToken: '3b580e70970c4528da70c98e097c2fa0',
storeDomain: 'hydrogen-preview',
storefrontApiVersion: '2023-01',
};

export default {
async fetch(
request: Request,
Expand All @@ -25,6 +31,14 @@ export default {

const session = await HydrogenSession.init(request, [env.SESSION_SECRET]);

if (new URL(request.url).pathname === '/proxy') {
return await proxyLiquidRoute(
request,
storefrontConfig.storeDomain,
'/pages/about',
);
}

try {
return await requestHandler(
request,
Expand Down

0 comments on commit 31c59c7

Please sign in to comment.