Shopify / hydrogen

Hydrogen lets you build faster headless storefronts in less time, on Shopify.
https://hydrogen.shop
MIT License
1.45k stars 277 forks source link

Support localized redirect url in storefrontRedirect #2564

Open juanpprieto opened 2 months ago

juanpprieto commented 2 months ago

Hello,

I had few cases were I couldn't use storefrontRedirect so I had to do my own implementation (by copy-pasting storefrontRedirect code and modify it).

The main thing is that it doesn't handle route params, e.g locale.

For example, there is a redirect configured in Shopify like following: From: /myUrlFrom, To: /myUrlTo

The storefront redirect will not handle theses:

/fr/myUrlFrom/ -> doesn't match any redirect url

So we should have a parameter or something to deal with locale.

In my own implementation I added 2 paramaters:

/ locale (e.g: fr-fr) to prefix redirect url, if the redirect url is absolute then we don't prefix it / localePrefix?: string; / Full string url. e.g: https://example.com/search?query=param, it will be used to match the redirect url / matchingUrl: string; Since we are not tied anymore to the request parameter we can pass everything we want. Also if we want to prefix the redirect url we can.

Context https://github.com/Shopify/hydrogen/discussions/2562#discussion-7228900

duncan-fairley commented 1 month ago

Yes, this is something we've solved several times with a form of fork of storefrontRedirect() which feels tough.

I've added two params to our custom implementations to solve for this (localePrefix and alsoMatchLocaleSpecificRedirects which allows for concurrently searching for both locale specific and global redirects - eg: /path/ and /eu/path when localePrefix === 'eu'

type StorefrontRedirect = {
    /** The [Storefront client](/docs/api/hydrogen/2024-07/utilities/createstorefrontclient) instance */
    storefront: Storefront<I18nBase>;
    /** The [MDN Request](https://developer.mozilla.org/en-US/docs/Web/API/Request) object that was passed to the `server.ts` request handler. */
    request: Request;
    /** The [MDN Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) object created by `handleRequest` */
    response?: Response;
    /** By default the `/admin` route is redirected to the Shopify Admin page for the current storefront. Disable this redirect by passing `true`. */
    noAdminRedirect?: boolean;
    /** By default, query parameters are not used to match redirects. Set this to `true` if you'd like redirects to be query parameter sensitive */
    matchQueryParams?: boolean;
    /** When present, storefrontRedirect will ignore this segment of the URL when searching for matching redirects */
    localePrefix?: string;
    /** By default, when localePrefix is set, it will not be used to search for matching redirects. Set this to `true` if you'd like to also search for redirects that are specific to a single locale */
    alsoMatchLocaleSpecificRedirects?: boolean;
};