Shopify routes
The handleShopifyRoutes function serves Shopify's storefront endpoints, such as checkout permalinks and the Storefront API proxy, and your custom route handlers. Use createShopifyRouteHandler to add your own endpoints that receive the request context, the session, and the Storefront API client.
To wire Shopify routes, redirects, and handler groups into your server, refer to Wire Hydrogen request handlers.
On Oxygen, Shopify answers requests for your UCP profile, your MCP endpoints, and some other /.well-known/* paths before they reach your Worker, so handleShopifyRoutes doesn't run for them. Refer to Routes that bypass your Worker.
Import handleShopifyRoutes and createShopifyRouteHandler from @shopify/hydrogen.
Anchor to Shopify endpointsShopify endpoints
Serves Shopify's storefront endpoints and your custom route handlers from your app. Call the function at the start of request handling, before your framework's router.
When a route matches, the function returns a promise for the response. Return that response as is, because the response already carries the request context's headers. When no route matches, the function returns null synchronously, and your framework's router handles the request. The function throws when differs from the Storefront API client's request context. When a route handler throws, the returned promise rejects. With , a thrown with status 429 resolves to a JSON 429 response with the error code , a constant message, Cache-Control: no-store, and a validated Retry-After header. Inside a try block, use return await on the result.
The function checks these routes in order and returns the first match: the Hydrogen manifest at , the Shopify API proxy at /__shopify, the Storefront API proxy at , Liquid-style ?variant= product URLs, registered handler groups, UCP buy permalinks at , checkout and cart permalinks, the UCP business profile at , allowlisted .well-known resources, the UCP MCP proxy at , the MCP proxy at , and AJAX cart URLs.
The Hydrogen manifest is always on. It describes your app's route templates and the locales of the definition in the request context, so Shopify services can build URLs for your storefront. Its routes field is null when you don't pass , and its i18n field is null when the request context has no definition.
Some routes answer unsupported methods with a 405 response. A registered handler path returns 405 for any method that no handler on that path registers. The Hydrogen manifest, checkout permalinks, and cart permalinks accept only GET and HEAD. Buy permalinks accept only GET, and the UCP MCP proxy accepts only POST.
When your bundler resolves the package's development export condition, the function also serves the GraphiQL explorer at /graphiql for GET requests that match no other route, and accepts a graphiql option. Set to an object with , , and to add a Customer Account API tab. The explorer skips the tab when it can't fetch the schema.
Anchor to handleShopifyRoutes-parametersParameters
- Anchor to optionsoptionsoptionsHydrogenRoutesOptionsHydrogenRoutesOptionsrequiredrequired
The request, its context, the Storefront API client, your route templates, your handler groups, and the session manager when a registered handler needs one.
A promise for the matched route's response, or
nullwhen no route matches.
HydrogenRoutesOptions
TypeScript
Examples
Handle routes before the router
Description
Build the request context and client, then serve Shopify's endpoints before the app router. This example falls through to the app router when no route matches.
TypeScript
import { createShopifyRequestContext, createStorefrontClient, handleShopifyRoutes, type ShopifyRouteHandlerContext, type ShopifyRouteHandlerGroup, type ShopifyRouteTemplates, type StorefrontClient, } from "@shopify/hydrogen"; export async function fetch( request: Request, appRouter: (request: Request, storefrontClient: StorefrontClient) => Promise<Response>, sessionManager: ShopifyRouteHandlerContext["sessionManager"], routeTemplates: ShopifyRouteTemplates, cartHandlers: ShopifyRouteHandlerGroup, ) { const requestContext = createShopifyRequestContext({ request, i18n: { country: "US", language: "EN" }, }); const storefrontClient = createStorefrontClient({ type: "public", requestContext, config: { storeDomain: process.env.PUBLIC_STORE_DOMAIN! }, }); const shopifyRoute = handleShopifyRoutes({ request, requestContext, sessionManager, storefrontClient, routeTemplates, handlers: [cartHandlers], }); if (shopifyRoute) return await shopifyRoute; const routedResponse = await appRouter(request, storefrontClient); const response = new Response(routedResponse.body, routedResponse); requestContext.applyResponseHeaders(response.headers); return response; }
Anchor to Custom endpointsCustom endpoints
Creates a custom endpoint in your app for one pathname and HTTP method. Collect handlers in an object, and pass an array of handler objects to in its handlers option.
Use paths other than , which the cart server handlers use. Return a JSON, redirect, or error result from the handler. Hydrogen sends a JSON result with status 200, an error result with status 400 by default, and a redirect result with status 303 by default. An error result is JSON unless it sets format: "text". When a redirect result uses a status other than 301, 302, 303, 307, or 308, the promise from rejects. With on , a thrown with status 429 becomes a 429 error response () with a validated Retry-After header. Other errors still propagate.
Annotate the handler's context parameter with only the fields the handler reads, for example , so apps without a session manager can register it. Hydrogen infers the context only from an annotated parameter. A handler with no parameter, or with an unannotated destructured parameter, gets the full context, so still requires for it.
Marking optional in the annotation doesn't make it optional at runtime. It still makes required, and when an untyped caller omits it, Hydrogen passes a stand-in that throws when the handler uses it. A check such as is always true, so don't use it as a fallback.
- Anchor to pathnamepathnamepathnameTPathname extends stringTPathname extends stringrequiredrequired
The exact URL pathname that the handler matches. Hydrogen doesn't match path parameters or prefixes.
- Anchor to methodmethodmethodTMethod extends stringTMethod extends stringrequiredrequired
The HTTP method that the handler matches, in uppercase, such as
POST.- Anchor to handlerhandlerhandler(context: TContext) => Promise<ShopifyRouteHandlerResult>(context: TContext) => Promise<ShopifyRouteHandlerResult>requiredrequired
The function that receives the request, its context, the session manager, and the Storefront API client, and returns a JSON, redirect, or error result.
The handler to add to a handler object.
ShopifyRouteHandlerResult
The JSON, redirect, or error result that a route handler returns.
ShopifyRouteJsonResult<TData> | ShopifyRouteRedirectResult | ShopifyRouteErrorResult<TError>ShopifyRouteJsonResult
A route handler result that Hydrogen sends as a `200` JSON response.
- data
The value that Hydrogen serializes as the response body.
TData - headers
Extra headers for the response. Hydrogen sets `content-type` to `application/json` and overrides any value you pass.
HeadersInit - type
Set to `json` for a JSON response.
'json'
ShopifyRouteRedirectResult
A route handler result that Hydrogen sends as a redirect response.
- headers
Extra headers for the redirect response.
HeadersInit - location
The redirect target. Hydrogen resolves a relative path against the request's origin.
string - status
The HTTP redirect status. Defaults to `303`.
ShopifyRedirectStatus - type
Set to `redirect` for a redirect response.
'redirect'
ShopifyRedirectStatus
The HTTP status codes a route handler can use for a redirect.
301 | 302 | 303 | 307 | 308ShopifyRouteErrorResult
A route handler result that Hydrogen sends as a JSON or plain-text error response.
- error
The error that Hydrogen serializes as the response body's `error` field.
TError - format
The body format. `json`, the default, sends `{error: {code, message}}` as `application/json`. `text` sends only `error.message` as `text/plain`. Use `text` for a native form submission, because the browser shows the response as a page.
'json' | 'text' - headers
Extra headers for the error response. Hydrogen sets `content-type` for the body format and overrides any value you pass.
HeadersInit - status
The HTTP status for the error response. Defaults to `400`.
number - type
Set to `error` for an error response.
'error'
ShopifyRouteHandler
ShopifyRouteHandlerContext
The values that Hydrogen passes to each registered route handler.
- request
The incoming request that matched the handler's pathname and method.
Request - requestContext
The current request's context, the same one the Storefront API client uses.
ShopifyRequestContext - sessionManager
Your app's session storage for the current request. `handleShopifyRoutes` requires it only when a registered handler's context includes this field.
ShopifyRouteSessionManager - storefrontClient
The Storefront API client for the current request.
StorefrontClient
ShopifyRequestContext
The context for one request. Pass the context to Hydrogen's API clients and route handlers for that request.
ShopifyRequestContextBase & {
/** The locale resolved for this request, with the path prefix it is served under. */
locale: RequestLocale<TI18n>;
/**
* The locale resolved for this request.
* @deprecated Use `locale` instead. Removed in the next major release.
*/
i18n: RequestLocale<TI18n>;
}ShopifyRequestContextBase
The fields and methods on every request context.
- __hydrogenShopifyRequestContextBrand
A type-only marker. Create request contexts only with `createShopifyRequestContext`.
never - applyResponseHeaders
Adds the headers that a Hydrogen storefront needs to the final response. Call the method on each response that your app builds. Responses from `handleShopifyRoutes` and `handleShopifyRedirects` already carry these headers. Append your committed session headers before you call the method. The method makes any response that sets a cookie private and uncacheable. The method also sets the `powered-by` header, makes responses marked with `markResponseAsPersonalized()` private and uncacheable, and adds eligible Shopify cookies only to non-document responses for methods other than `GET` and `HEAD`. Pass the response's `status` as well. When the status is `429` and the Storefront API rate limited a request that used this context, the method sets `Cache-Control: no-store` and removes `Surrogate-Control` and every vendor `*-Cache-Control` header. It also sets `Retry-After` to the later of the response's own valid `Retry-After` value and the latest valid retry deadline from all Storefront API `429` responses on this context, including recovered errors. Delay-seconds and IMF-fixdates are accepted. The value is the remaining delay-seconds, rounded up and never negative. React Router doesn't copy the headers of a thrown response, so this keeps the headers of a `429` from `withStorefrontRateLimit`. Responses with other statuses keep their cache headers. When you omit `status` after a Storefront API rate limit, the method logs one warning and adds no rate-limit headers. The `429` response can then lose `Retry-After` and `Cache-Control: no-store`.
(headers: Headers, status?: number) => void - applyStorefrontRequestHeaders
Adds the Hydrogen SDK headers and the customer's cookie, privacy, and origin headers to a Storefront API request. The Storefront API client and the API proxies call the method for you.
(headers: Headers) => void - buyerIp
The customer's trusted IP address. Private Storefront API clients require it.
string - captureStorefrontRateLimit
Tracks Storefront API `429` responses and the latest valid retry deadline, independent of completion order. Delay-seconds start at capture time; HTTP dates specify absolute deadlines. Invalid values do not replace valid advice. The Storefront API client calls the method for you.
(retryAfter: string) => void - captureSubrequestHeaders
Saves the cookies from the first Storefront API response that sets cookies. The Storefront API client calls the method for you, and `applyResponseHeaders()` can add the cookies to your response.
(headers: Headers) => void - consumeStorefrontResponseHeaders
Saves the cookies from a proxied Storefront API response and removes the `set-cookie` header from that response. The API proxies in `handleShopifyRoutes` call the method for you.
(headers: Headers) => void - cookie
The incoming request's `Cookie` header. Hydrogen forwards the header to the Storefront API.
string - getForwardedRequestHeaders
Returns the incoming request's headers with Shopify's request headers added. Pass the headers when you forward the request to a proxy or another origin.
() => Headers - i18nDefinition
The i18n definition the context matched its locale against. Absent for the deprecated fixed-locale input.
ShopifyI18n - markResponseAsPersonalized
Marks the final response as private and uncacheable because the response holds customer data, such as a server-rendered cart. `applyResponseHeaders()` then sets `Cache-Control: private, no-store, max-age=0, must-revalidate` and removes `Surrogate-Control` and every vendor `*-Cache-Control` header. Call the method before `applyResponseHeaders()`, and only on requests whose response holds customer data, so other responses stay cacheable. Pass a short `reason` that names the customer data. The Customer Account API client and the customer session call the method for you.
(reason: string) => void - markResponseAsSessionEstablishing
Lets the final response set Shopify cookies before the customer has a Shopify session, and marks the response as private and uncacheable. The UCP MCP proxy calls the method for you.
(reason: string) => void - requestGroupId
The ID that groups this request's Shopify API calls. Hydrogen reads the ID from the request headers or generates one.
string - signal
The incoming request's abort signal. Hydrogen's API clients stop their requests when the signal aborts.
AbortSignal - storefrontOrigin
The origin of the incoming request's URL. Hydrogen forwards the origin to the Storefront API.
string - url
The incoming request's URL.
string
Headers
ShopifyI18n
Module-scope internationalization definition shared by the server request context, route matching, URL builders, and client scripts. Create it with `defineShopifyI18n`.
- defaultLocale
Locale used when routing determines nothing: unprefixed paths or unrecognized hostnames.
ShopifyLocale - routing
Omit for single-locale storefronts.
ShopifyI18nRouting
ShopifyLocale
A `{language, country}` pair identifying one locale a storefront serves.
- country
ShopifyCountryCode - language
ShopifyLanguageCode
ShopifyCountryCode
ShopifyLanguageCode
ShopifyI18nRouting
{
type: "pathname";
/**
* Locales served under a prefix. `defaultLocale` is served unprefixed only and must not be
* listed here, so every page has one canonical URL.
*/
locales: readonly ShopifyPathnameLocale[];
} | {
type: "domain";
/**
* Locales served per hostname. `defaultLocale` must be listed here so it has a canonical
* hostname for links and sitemaps; it is also what unrecognized hosts (localhost, preview
* URLs) resolve to.
*/
locales: readonly ShopifyDomainLocale[];
}ShopifyPathnameLocale
A locale served under a URL path prefix. The prefix is derived from the locale as `/{language}-{country}` (lowercased, `_` → `-`), so `{language: "FR", country: "CA"}` is served at `/fr-ca`. Set `pathSegment` when the derived segment is undesirable, for example `PT_BR` + `BR` derives to `pt-br-br`. A segment is a single path part: no slashes.
ShopifyLocale & {
pathSegment?: string;
}ShopifyDomainLocale
A locale served from its own hostname. Match is exact on `URL.hostname` (no port), so `fr.example.com`, `example.fr`, and `example.com` are three separate entries. Aliases such as `www.` are a redirect concern and must not be listed here.
ShopifyLocale & {
hostname: string;
}RequestLocale
The locale a request context resolves: matched from a definition, or the legacy fixed locale.
TI18n extends ShopifyI18n
? ShopifyMatchedLocale<TI18n>
: TI18n extends I18nConfig
? NormalizedI18nConfig<TI18n>
: neverShopifyMatchedLocale
A locale resolved for one request. `pathSegment` is replaced by the derived `pathPrefix` (`""` for the default locale and under domain routing), which is what URL builders consume. Domain-routed locales keep their `hostname` so canonical and `hreflang` URLs can be built.
DistributiveOmit<
ShopifySupportedLocale<TI18n>,
"pathSegment"
> & {
pathPrefix: string;
}DistributiveOmit
T extends unknown ? Omit<T, K> : neverShopifySupportedLocale
Every locale entry a definition can resolve to, keeping any extra per-locale fields.
ShopifySupportedLocale<TI18n>I18nConfig
Deprecated: a fixed request locale with an optional path prefix. Removed in the next major release.
- country
The request's country.
ShopifyCountryCode - language
The request's language.
ShopifyLanguageCode - pathPrefix
The URL prefix for localized routes, such as `/es-es`. Hydrogen adds the prefix to standard route redirects and product variant URLs.
string
NormalizedI18nConfig
Omit<TConfig, "pathPrefix"> & {
pathPrefix: string;
}ShopifyRouteSessionManager
The session storage that route handlers and the customer session read and write. Implement the methods with your app's session.
- commit
Saves session changes and returns the headers, such as a cookie, to add to the response.
() => Awaitable<void | HeadersInit> - getSessionItem
Returns the session value stored under a key.
(key: string) => unknown - getSessionOrigin
Returns your storefront's HTTPS origin. Customer account sign-in builds its OAuth redirect URL from the origin.
() => Awaitable<string> - removeSessionItem
Deletes the session value stored under a key.
(key: string) => Awaitable<void> - setSessionItem
Stores a value in the session under a key.
(key: string, value: unknown) => Awaitable<void>
Awaitable
A value or a promise for that value.
T | Promise<T>StorefrontClient
A Storefront API client. Call `graphql()` with a document to run a query or mutation and get a typed result.
- apiUrl
The Storefront API GraphQL endpoint that the client calls.
string - graphql
Runs a Storefront API query or mutation and returns a typed result. Pass a `gql` document or a plain query string. When the operation declares `$country: CountryCode` or `$language: LanguageCode`, the client sets the variable from the request context and overrides any value you pass. Variables with other types stay caller-owned. The method throws an error when a query passes a `cache` strategy and the client has no cache, or when the strategy uses `private` mode. A catch block for `StorefrontApiError` doesn't catch this configuration error. To cache customer-specific data, use `createRunWithCache` with a key unique to the customer.
<const Doc extends DocLike | string>(doc: Doc, ...options: GqlRestParam<ResolveDoc<Doc>, Extra>) => Promise<StorefrontGraphqlResult<ResolveDoc<Doc>>> - i18n
The locale resolved for this request.
RequestContext["i18n"] - locale
The locale resolved for this request. The client sends its country and language for `$country` and `$language` variables.
RequestContext["locale"] - requestContext
The request context that you passed to `createStorefrontClient`.
RequestContext - storefrontId
The storefront ID from the client options.
string - storeUrl
Your store's URL with its protocol, such as `https://my-store.myshopify.com`.
string - type
The client type that you passed to `createStorefrontClient`.
Type
DocLike
A document that the client's GraphQL method accepts, from `gql` or from `gql`.tada.
TadaDocumentNode<any, any> | AnyStorefrontQueryStringAnyStorefrontQueryString
Any `gql` document, whatever its result and variables types. Use the type to accept any Storefront API document.
string & StorefrontQueryMetadataStorefrontQueryMetadata
Type-only properties that mark a string as a `gql` document.
- __hydrogenQueryBrand
Marks a string that `gql` returns. The property exists only in types.
true - __hydrogenQueryParts
The operation text followed by each distinct fragment text the document appends. The property exists only in types.
Parts - __hydrogenQuerySource
The document's query text, which TypeScript reads to infer types. The property exists only in types.
Source
GqlRestParam
The options argument of a GraphQL call. Pass the options argument when the document declares a required variable. You can leave the options argument out when every variable is optional, or when the only required variables are `$country` and `$language`, which the client fills.
HasNoRequiredKeys<MergedOptions<Doc, GraphqlExtraOptionsForDoc<Doc, Extra>>> extends true
? [options?: MergedOptions<Doc, GraphqlExtraOptionsForDoc<Doc, Extra>>]
: [options: MergedOptions<Doc, GraphqlExtraOptionsForDoc<Doc, Extra>>]HasNoRequiredKeys
Resolves to `true` when an object type has no required keys.
Record<string, never> extends T ? true : falseMergedOptions
The options for a GraphQL call. The call needs `variables` only when the document declares a required variable.
Extra & StorefrontGraphqlOptions & (HasNoRequiredKeys<UserVariables<Doc>> extends true
? { variables?: UserVariables<Doc> }
: { variables: UserVariables<Doc> })StorefrontGraphqlOptions
Options that every Storefront API GraphQL call accepts.
- signal
Cancels the request when the signal aborts. The request context's signal and the client timeout also cancel the request. The signal doesn't cancel a stale-while-revalidate refresh.
AbortSignal
UserVariables
Variables the caller passes: everything except the i18n variables the client injects.
VariablesOfDoc
The variables that a Customer Account document declares.
Doc extends CustomerAccountDocument<unknown, infer Variables, string> ? Variables : neverCustomerAccountDocument
A Customer Account API query or mutation that `gql` from `@shopify/hydrogen/customer-account` returns. TypeScript infers the result and variables types from the document's GraphQL source. Create documents only with the Customer Account `gql` function. The client throws a `TypeError` for any other object.
DocumentDecoration<Result, Variables> & {
readonly [CUSTOMER_ACCOUNT_DOCUMENT]: true;
readonly source: Source;
/** The operation text followed by each distinct fragment text the document appends. The property exists only in types. */
readonly parts?: Parts;
}I18nVariableNamesOfDoc
The variables the client fills when omitted: those declared with the expected type, such as `$language: LanguageCode`.
string extends SourceOf<Doc>
? I18nVariableNamesByValue<VariablesOfDoc<Doc>>
: InferVariableNamesDeclaredAs<SourceOf<Doc>, I18nVariableTypes>SourceOf
Extracts the source string literal type from a Customer Account document.
Doc extends { readonly source: infer Source extends string }
? Source
: neverI18nVariableNamesByValue
I18nVariableNamesByValue<Variables>InferVariableNamesDeclaredAs
Names of the first operation's variables that are declared with the named type `Types` maps them to, nullable or non-null. List types never match.
parseDocument<T> extends infer Doc
? Doc extends { kind: "Document"; definitions: infer Defs extends readonly unknown[] }
? FirstOperation<Defs> extends { variableDefinitions: infer Vars extends readonly unknown[] }
? DeclaredNameOfType<Vars[number], Types>
: never
: never
: neverFirstOperation
Defs extends readonly [infer Def, ...infer Rest]
? Def extends { kind: "OperationDefinition" }
? Def
: FirstOperation<Rest>
: neverDeclaredNameOfType
Definition extends {
variable: { name: { value: infer Name extends keyof Types } };
type: infer Type;
}
? (Type extends { kind: "NonNullType"; type: infer Inner } ? Inner : Type) extends {
kind: "NamedType";
name: { value: Types[Name] };
}
? Name
: never
: neverDefinition
A top-level definition of a GraphQL text. A fragment is keyed by its name, any other definition by its canonical form. `canonical` joins the definition's tokens with single spaces, so two copies that differ only in whitespace, commas, or comments compare equal. `text` is the definition as written.
- canonical
string - key
string - text
string
I18nVariableTypes
typeof CUSTOMER_ACCOUNT_I18N_VARIABLE_TYPESGraphqlExtraOptionsForDoc
Offers the `cache` option only for documents that TypeScript recognizes as queries.
OperationKindOfDoc<Doc> extends "query" ? Extra : Omit<Extra, "cache">OperationKindOfDoc
The operation kind of a document, such as `query`. Resolves to `unknown` when the query text isn't a string literal type.
[SourceText<Doc>] extends [never]
? "unknown"
: string extends SourceText<Doc>
? "unknown"
: InferOperationKind<SourceText<Doc>>SourceText
The query text of a document as a string literal type. A plain string resolves to itself.
[SourceOf<Doc>] extends [never]
? Doc extends string
? Doc
: never
: SourceOf<Doc>InferOperationKind
The operation kind of a query string, such as `query`. Resolves to `unknown` unless the query text has exactly one operation.
parseDocument<T> extends infer Doc
? [Doc] extends [never]
? "unknown"
: OperationKindType<Doc>
: "unknown"OperationKindType
ResolveDoc
The typed document for a GraphQL call. Hydrogen infers the types when you pass a plain query string.
D extends DocLike ? D : D extends string ? InferredDoc<D> : neverInferredDoc
StorefrontGraphqlResult
The result of a GraphQL call, with the data, any GraphQL errors, and the response headers. Check `errors` before you read `data`. Without errors, `data` holds the full result, typed from your document. With errors, `data` is `null` after a request error or after a failed non-null field at the root. Otherwise, `data` holds a partial result, and `null` replaces each failed field or its nearest nullable parent.
{ data: ResultOfDoc<Doc>; errors?: undefined; headers: Headers } | { data: ResultOfDoc<Doc> | null; errors: GraphQLFormattedError[]; headers: Headers }ResultOfDoc
The result type of a `gql` document or a `gql`.tada document node.
Doc extends StorefrontQueryString<infer Result, infer _Variables, string>
? Result
: Doc extends TadaDocumentNode<any, any>
? TadaResultOf<Doc>
: neverStorefrontQueryString
GraphQLFormattedError
A GraphQL error from the Storefront API. The result of a GraphQL call lists GraphQL errors in its `errors` field.
- extensions
Extra details that the Storefront API adds to the error.
Record<string, unknown> - locations
The lines and columns in the query where the error occurs.
ReadonlyArray<{ line: number; column: number }> - message
The error message.
string - path
The path to the response field that failed.
ReadonlyArray<string | number>
Anchor to shopifyrouteerrorShopifyRouteError
The code and message that an error result sends in the response body's error field.
- Anchor to codecodecodestringstringrequiredrequired
A machine-readable error code.
- Anchor to messagemessagemessagestringstringrequiredrequired
A human-readable error message.
TypeScript
Examples
Register a custom route
Description
Create a GET route that queries the Storefront API. This example returns a `json` result on success and an `error` result with status `502` when the query fails.
TypeScript
import { createShopifyRouteHandler, gql, type ShopifyRouteHandlerContext, type ShopifyRouteHandlerResult, } from "@shopify/hydrogen"; const SHOP_QUERY = gql(`query { shop { name } }`); async function handleShopGet({ storefrontClient, }: ShopifyRouteHandlerContext): Promise<ShopifyRouteHandlerResult> { const result = await storefrontClient.graphql(SHOP_QUERY); if (result.errors) { return { type: "error", status: 502, error: { code: "storefront_error", message: result.errors[0]?.message ?? "Request failed" }, }; } return { type: "json", data: { name: result.data.shop.name } }; } export const shopHandlers = { get: createShopifyRouteHandler("/api/shop", "GET", handleShopGet), };Redirect from a route
Description
Return a redirect result from a handler. This example sends `/wishlist` to `/account/wishlist` with a permanent redirect.
TypeScript
import { createShopifyRouteHandler } from "@shopify/hydrogen"; export const legacyHandlers = { wishlist: createShopifyRouteHandler("/wishlist", "GET", async () => ({ type: "redirect" as const, location: "/account/wishlist", status: 301 as const, })), };