Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add example of (and fix) static asset proxy #254

Merged
merged 4 commits into from
Nov 29, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions packages/remix-oxygen/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ export function createRequestHandler<Context = unknown>({
request: Request,
params: OxygenHandleRequestOptions,
) => Promise<Context> | Context;
/**
* By default, Hydrogen will prefix all static assets with a CDN url.
* If you need to serve static assets from the same domain or from the root,
* then update the `shouldProxyAsset: (url: string) => boolean` function below
* to return `true` when the url (pathname) matches your asset.
*
* @example
* ```ts
* shouldProxyAsset(url) {
* return new URL(url).pathname === '/robots.txt';
* }
* ```
*/
shouldProxyAsset?: (url: string) => boolean;
}) {
const handleRequest = createRemixRequestHandler(build, mode);
Expand All @@ -39,8 +52,22 @@ export function createRequestHandler<Context = unknown>({
shouldProxyAsset?.(request.url)
) {
const url = new URL(request.url);
const assetBasePath = (build.publicPath || '').replace(/\/$/, '');
return fetch(request.url.replace(url.origin, assetBasePath), request);

/**
* Use the assetPrefix (publicPath) as the origin. Note that Remix expects client assets to be
* prefixed with `/build/*`, and as such, `/build/` is included in the Oxygen-created `assetPrefix`.
* However, we need strip out the leading `/build/` for this use case, as developers may wish to
* serve a static asset from the root `/public` folder (one level up from `/build`).
*/
const newOriginAndPathPrefix = (build.publicPath || '').replace(
/\/build\/$/,
'',
);

return fetch(
request.url.replace(url.origin, newOriginAndPathPrefix),
request,
);
}

return await handleRequest(request, {
Expand Down