Repository navigation
Add UCP business profile proxy on a generalized proxy interceptor - #3976
Conversation
eeddd11 to
fd2b5bb
Compare
There was a problem hiding this comment.
🟡 Changes recommended
The UCP error mapper incorrectly converts internal setup failures into upstream 502 responses.
Once you've addressed the issues Copilot identified, you can request another Copilot review.
Pull request overview
Adds UCP business-profile discovery to Hydrogen’s Shopify route handling using a generalized proxy interceptor.
Changes:
- Adds and registers
GET /.well-known/ucp. - Extends proxy configuration for header filtering, validation, caching, and error mapping.
- Adds tests, documentation, and a patch changeset.
File summaries
| File | Description |
|---|---|
.changeset/ucp-business-profile-proxy.md |
Records the patch release. |
packages/hydrogen/skills/hydrogen-request-handlers/SKILL.md |
Documents UCP integration and validation. |
packages/hydrogen/src/core/request-routing/handle-shopify-routes.test.ts |
Tests route-level UCP behavior. |
packages/hydrogen/src/core/request-routing/handle-shopify-routes.ts |
Registers the UCP interceptor. |
packages/hydrogen/src/core/request-routing/interceptors/proxy.test.ts |
Tests generalized proxy behavior. |
packages/hydrogen/src/core/request-routing/interceptors/proxy.ts |
Adds configurable proxy hooks. |
packages/hydrogen/src/core/request-routing/interceptors/ucp.test.ts |
Tests UCP proxy behavior and failures. |
packages/hydrogen/src/core/request-routing/interceptors/ucp.ts |
Implements the UCP profile proxy. |
packages/hydrogen/src/core/url.ts |
Adds the exact UCP route matcher. |
Review details
- Files reviewed: 9/9 changed files
- Comments generated: 1
- Review effort level: Balanced
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
| mapError: (error) => ({ | ||
| status: error instanceof DOMException && error.name === "TimeoutError" ? 504 : 502, | ||
| headers: { "cache-control": UCP_NO_CACHE_CONTROL }, | ||
| }), |
| responseValidation: (upstream) => { | ||
| const contentType = upstream.headers.get("content-type"); | ||
| const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase(); | ||
| if ( | ||
| (upstream.status >= 300 && upstream.status < 400) || | ||
| (upstream.ok && mediaType !== "application/json") | ||
| ) { | ||
| return { | ||
| status: 502, | ||
| body: { error: "Invalid Shopify UCP profile response" }, | ||
| headers: { "cache-control": UCP_NO_CACHE_CONTROL }, | ||
| logMessage: "invalid profile response", | ||
| log: { status: upstream.status, contentType }, | ||
| }; | ||
| } | ||
| return null; | ||
| }, |
There was a problem hiding this comment.
non-blocking: (threading on @mdamjanic7's 404 comment) checked a few real stores with accept: application/json - the Online Store already content-negotiates and returns a JSON 404 ({"errors":"Not Found"}, content-type: application/json) for unpublished profiles. So the HTML case is rarer than it sounds: it's mock.shop (the skeleton default, returns text/plain) and dead stores, not every unpublished store.
Still think a JSON route should never forward a non-JSON body though, so let's extend the check to cover non-2xx too. Two things to watch in the rewrite:
- 3xx must stay 502 (
upstream.okis false for a 302, so keying onokalone would return a body-ful 302 with nolocation) - don't
log.errorfor a plain 404 - it's the steady state for a store without a profile, not a fault
const contentType = upstream.headers.get("content-type");
const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase();
const isRedirect = upstream.status >= 300 && upstream.status < 400;
if (isRedirect || mediaType !== "application/json") {
const status = isRedirect || upstream.ok ? 502 : upstream.status;
return {
status,
body: { error: "Shopify UCP profile unavailable" },
headers: { "cache-control": UCP_NO_CACHE_CONTROL },
...(status === 502 && { logMessage: "invalid profile response", log: { status: upstream.status, contentType } }),
};
}The 3xx rejection is also spec-mandated (UCP spec, Profile Requirements > Hosting: "Profile endpoints MUST NOT use redirects (3xx)"), so worth a one-liner in code so nobody relaxes it later.
| const UCP_NO_CACHE_CONTROL = "no-store"; | ||
| const UCP_PROFILE_PATH = "/.well-known/ucp"; | ||
| const UCP_FETCH_TIMEOUT_MS = 5_000; | ||
| const UCP_RESPONSE_HEADERS = ["content-type", "etag", "last-modified", "vary"] as const; |
There was a problem hiding this comment.
non-blocking: let's drop vary from the allowlist. Upstream sends vary: Accept (plus accept-encoding), which describes variance over upstream's request headers - but we've already normalised accept to application/json so the response no longer varies on what the client sent. Forwarding it means the edge fragments the s-maxage=60 cache per distinct client accept value (*/*, application/json, application/json, text/plain...), which undercuts the whole cache policy this PR is built around. Either drop it or set vary: accept-encoding explicitly. Update the test expectation on ucp.test.ts L122 to match.
| it.each([ | ||
| [302, { location: "https://other.example/.well-known/ucp" }], | ||
| [200, { "content-type": "text/html" }], | ||
| ])("rejects invalid upstream responses", async (status, headers) => { |
There was a problem hiding this comment.
nit: both cases share the same test name, and the assertion has a conditional expected value (status === 200 ? "text/html" : "text/plain;charset=UTF-8"). Let's make expectedContentType a third column in the table and use %i in the name so failures say which case broke:
it.each([
[302, { location: "https://other.example/.well-known/ucp" }, "text/plain;charset=UTF-8"],
[200, { "content-type": "text/html" }, "text/html"],
])("rejects invalid upstream responses (status %i)", async (status, headers, expectedContentType) => {|
|
||
| export const AGENT_BUYER_CLAIMS_RE = | ||
| /^(?:\/[a-z]{2}(?:-[a-z]{2})?)?\/agent\/(?:handoff|buyer-claims)(?:\.[^/.]+)?\/?$/i; | ||
| export const UCP_RE = /^\/\.well-known\/ucp$/; |
There was a problem hiding this comment.
nit: on preview, WELL_KNOWN_RE directly below now has a doc comment listing the .well-known resources proxied to the Online Store. /.well-known/ucp is also a .well-known path proxied to the Online Store but isn't in that list, so the next reader might "fix" it by folding it into WELL_KNOWN_RE and lose the JSON validation + cache policy. A one-liner above UCP_RE saying why it's a separate interceptor would head that off.
| "@shopify/hydrogen": patch | ||
| --- | ||
|
|
||
| Serve Shopify's managed UCP business profile from headless storefront origins through `handleShopifyRoutes`. |
There was a problem hiding this comment.
praise: nice, concise changeset. patch is right given no public API change.
Match the Online Store, which serves /.well-known/ucp with Access-Control-Allow-Origin: *, so browser-based agents can fetch it.
…opify#3976) * Add UCP business profile proxy * use existing createProxyInterceptor instead of new ucp flavor * Address UCP business profile proxy review feedback * Address remaining UCP profile review suggestions * Adapt UCP profile proxy tests to preview's logging and proxy test helpers * Allow cross-origin reads of the proxied UCP profile Match the Online Store, which serves /.well-known/ucp with Access-Control-Allow-Origin: *, so browser-based agents can fetch it. --------- Co-authored-by: Misha Damjanic <misha.damjanic@shopify.com>
…links Drop the HTML/document classification so the header matches Liquid and Oxygen. The Next.js proxy no longer leaves the UCP Link on NextResponse.next(), because Next.js lets a proxy header replace a route handler's header of the same name. Update the Nuxt skill reference to sync every header, and the changeset to note the dependency on #3976.
handleShopifyRoutes serves /.well-known/ucp through handleUcpProfileProxy (#3976), ahead of the .well-known allowlist. The TSDoc route list left it out, so the shopify.dev reference didn't mention it. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…fy#4158) handleShopifyRoutes serves /.well-known/ucp through handleUcpProfileProxy (Shopify#3976), ahead of the .well-known allowlist. The TSDoc route list left it out, so the shopify.dev reference didn't mention it. Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…links Drop the HTML/document classification so the header matches Liquid and Oxygen. The Next.js proxy no longer leaves the UCP Link on NextResponse.next(), because Next.js lets a proxy header replace a route handler's header of the same name. Update the Nuxt skill reference to sync every header, and the changeset to note the dependency on #3976.
* Add UCP discovery Link header to HTML document responses applyResponseHeaders now appends `Link: </.well-known/ucp>; rel="ucp"` to HTML documents, matching Liquid storefronts and Oxygen. It keeps existing Link values, skips responses that already carry a rel="ucp" link (using Oxygen's pattern, so Oxygen does not add a second one), omits version, and skips *.myshopify.dev Oxygen deployment hosts where the profile does not resolve. * Send the UCP discovery Link on every response and keep Next.js route links Drop the HTML/document classification so the header matches Liquid and Oxygen. The Next.js proxy no longer leaves the UCP Link on NextResponse.next(), because Next.js lets a proxy header replace a route handler's header of the same name. Update the Nuxt skill reference to sync every header, and the changeset to note the dependency on Shopify#3976. * Trim redundant UCP discovery link tests * Align Next.js UCP Link docs with the template's save-and-restore * Call out the Next.js Link upgrade impact and preview-domain policy * Parse Link rel parameters to detect an existing UCP link Replace the whole-header regex with a small RFC 8288 parser: split link-values and parameters outside URIs and quoted strings, then match `ucp` in any rel relation list. Recognizes relation lists and spaced `=`, and no longer false-positives on quoted non-rel text such as title="; rel=ucp". * Regenerate docs after rebase --------- Co-authored-by: freddie <rincofrederico@gmail.com>
WHY are these changes introduced?
Agents starting discovery from a headless storefront cannot currently find Shopify's managed UCP business profile. Serving it on the storefront origin lets them discover the authoritative services and endpoints on the store's
myshopify.comdomain.WHAT is this pull request doing?
Adds
GETandHEAD /.well-known/ucptohandleShopifyRoutes, using the shared proxy interceptor. Applications already callinghandleShopifyRoutesbefore framework routing gain discovery automatically. This includes a patch changeset; there is no new public API or migration.Profile behavior
Accept: application/json, forwarding onlyIf-None-MatchandIf-Modified-Since. Query strings, shopper cookies, authorization, and storefront request headers are omitted.Content-Type,ETag, andLast-Modifiedupstream response headers. UpstreamVaryis dropped because the upstream representation is fixed; cookies and internal headers are not forwarded.304 Not ModifiedresponsesCache-Control: public, max-age=60, s-maxage=60, stale-while-revalidate=300, stale-if-error=300. The short stale window limits how long rotated signing keys may remain advertised during an outage.404for unpublished profiles without logging an error. Other non-JSON upstream errors become JSON errors while preserving their status. Redirects, except the non-redirecting304revalidation response, and non-JSON successes return502.500for setup errors,504for the five-second fetch timeout, and502for other fetch failures. The shared factory rejects JSONP callback parameters with400. Generated errors always use JSON andCache-Control: no-store; HEAD responses have no body.Shared proxy implementation
The internal factory adds optional query-string suppression, storefront request-header suppression, response-header allowlisting, and response validation. The existing response
preparehook uses bodyless upstream metadata through its context; validation rejections cancel the upstream body centrally.mapErrorcan choose a status and body while preserving the setup/fetch default status split and existingformatErrorfallback. The factory owns generated error headers. The profile interceptor is nameducp-profile-proxyto distinguish it from the UCP MCP proxy.The request-handler skill documents discovery, conditional requests, HEAD, caching, and error behavior. Existing proxy descriptors retain their behavior.
HOW to test your changes?
Automated validation after merging the latest
preview:pnpm --filter @shopify/hydrogen test— package build and all 2,258 unit/type tests passed. The final shared-mock cleanup was also checked with the focused proxy tests.pnpm --filter @shopify/hydrogen typecheck.pnpm run lintandpnpm run format:check.node scripts/assert-no-major-changesets.ts.For manual verification, configure a Shopify store with a published profile and serve the storefront over HTTPS. Check that GET returns JSON with the cache policy above, HEAD returns the same headers without a body, and a matching conditional request returns
304. An unpublished profile should return an uncached JSON404; POST should continue to the application's normal routing. These live-store checks are not part of the automated validation.Post-merge steps
None.
Checklist