Skip to content

Commit

Permalink
Fix storefrontRedirect to strip trailing slashes in querying for re…
Browse files Browse the repository at this point in the history
…directs (#2110)

The admin doesn't allow you to save a redirect with a trailing slash, so it should be safe to always strip it
  • Loading branch information
blittle authored May 15, 2024
1 parent 7be0c67 commit f29c908
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/large-rivers-fold.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen': patch
---

Fix `storefrontRedirect` to strip trailing slashes when querying for redirects. Resolves [#2090](https://github.com/Shopify/hydrogen/issues/2090)
27 changes: 26 additions & 1 deletion packages/hydrogen/src/routing/redirect.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {describe, it, expect, vi} from 'vitest';
import {describe, it, expect, vi, afterEach} from 'vitest';
import type {Storefront} from '../storefront';
import {storefrontRedirect} from './redirect';

Expand All @@ -10,6 +10,10 @@ describe('storefrontRedirect', () => {
query: queryMock,
} as unknown as Storefront;

afterEach(() => {
queryMock.mockReset();
});

it('redirects to Shopify admin ', async () => {
await expect(
storefrontRedirect({
Expand Down Expand Up @@ -46,6 +50,27 @@ describe('storefrontRedirect', () => {
});
});

it('strips trailing slashes on the redirect query', async () => {
queryMock.mockResolvedValueOnce({
urlRedirects: {edges: [{node: {target: shopifyDomain + '/some-page'}}]},
});

await expect(
storefrontRedirect({
storefront: storefrontMock,
request: new Request('https://domain.com/some-page/'),
}),
).resolves.toEqual(
new Response(null, {
status: 301,
headers: {location: shopifyDomain + '/some-page'},
}),
);
expect(queryMock).toHaveBeenCalledWith(expect.anything(), {
variables: {query: 'path:/some-page'},
});
});

it('queries the SFAPI with the url lower cased', async () => {
queryMock.mockResolvedValueOnce({
urlRedirects: {edges: [{node: {target: shopifyDomain + '/some-page'}}]},
Expand Down
4 changes: 3 additions & 1 deletion packages/hydrogen/src/routing/redirect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,9 @@ export async function storefrontRedirect(
const {urlRedirects} = await storefront.query<{
urlRedirects: UrlRedirectConnection;
}>(REDIRECT_QUERY, {
variables: {query: 'path:' + redirectFrom},
// The admin doesn't allow redirects to have a
// trailing slash, so strip them all off
variables: {query: 'path:' + redirectFrom.replace(/\/+$/, '')},
});

const location = urlRedirects?.edges?.[0]?.node?.target;
Expand Down

0 comments on commit f29c908

Please sign in to comment.