Skip to main content

storefrontRedirect
utility

Queries the Storefront API to see if there is any redirect created for the current route and performs it. Otherwise, it returns the response passed in the parameters. Useful for conditionally redirecting after a 404 response.

required

Promise<Response>
Was this section helpful?

Example code

import {storefrontRedirect, createStorefrontClient} from '@shopify/hydrogen';
// @ts-expect-error
import * as reactRouterBuild from 'virtual:react-router/server-build';
import {
createRequestHandler,
getStorefrontHeaders,
} from '@shopify/remix-oxygen';

export default {
async fetch(request, env, executionContext) {
const {storefront} = createStorefrontClient({
cache: await caches.open('hydrogen'),
waitUntil: (p) => executionContext.waitUntil(p),
privateStorefrontToken: env.PRIVATE_STOREFRONT_API_TOKEN,
publicStorefrontToken: env.PUBLIC_STOREFRONT_API_TOKEN,
storeDomain: env.PUBLIC_STORE_DOMAIN,
storefrontHeaders: getStorefrontHeaders(request),
});

const handleRequest = createRequestHandler({
build: reactRouterBuild,
mode: process.env.NODE_ENV,
});

const response = await handleRequest(request);

if (response.status === 404) {
/**
* Check for redirects only when there's a 404 from
* the app. If the redirect doesn't exist, then
* `storefrontRedirect` will pass through the 404
* response.
*/
return storefrontRedirect({request, response, storefront});
}

return response;
},
};