gatsby: Gatsby Link doesn't respect trailing slash for relative links with queries

Preliminary Checks

Description

Since Gatsby 2.22.17 it is possible to make a Gatsby Link be to= a relative path. Rather than using the standard library url.resolve(from, to), Gatsby uses its own resolve implementation (require('@gatsbyjs/reach-router/lib/utils').resolve(to, from)). This is justified by the fact that Gatsby needs it to behave as if from’s path-part has a trailing slash, whether or not it actually has a trailing slash.

Anyway, there’s a bug in said resolve function in that it will actually remove a trailing slash from the to path in some situations.

Reproduction Link

See the testcase below.

Steps to Reproduce

Here is the testcase that I would include in my PR if I had the fix.

diff --git a/packages/gatsby-link/src/__tests__/index.js b/packages/gatsby-link/src/__tests__/index.js
index e6f37f4f26..f3dd0760fb 100644
--- a/packages/gatsby-link/src/__tests__/index.js
+++ b/packages/gatsby-link/src/__tests__/index.js
@@ -179,6 +179,15 @@ describe(`<Link />`, () => {
       expect(link.getAttribute(`href`)).toEqual(`/active/courses?sort=name`)
     })
 
+    it(`handles relative link with "./?"`, () => {
+      const location = `./?sort=name`
+      const { link } = setup({
+        sourcePath: `/courses/`,
+        linkProps: { to: location },
+      })
+      expect(link.getAttribute(`href`)).toEqual(`/courses/?sort=name`)
+    })
+
     it(`handles relative link with "../"`, () => {
       const location = `../courses?sort=name`
       const { link } = setup({

Apply that patch, run yarn jest gatsby-link.

Expected Result

I expected the test to pass, with link.getAttribute('href') equal to /courses/?sort=name.

Actual Result

The test fails, because link.getAttribute('href') is /courses?sort=name rather than /courses/?sort=name.

Environment

System:
    OS: Linux 5.13 Parabola
    CPU: (4) x64 Intel(R) Core(TM) i7-5600U CPU @ 2.60GHz
    Shell: 5.1.8 - /bin/bash
  Binaries:
    Node: 16.7.0 - /usr/bin/node
    Yarn: 1.22.11 - /usr/bin/yarn
    npm: 7.21.0 - /usr/bin/npm

Config Flags

No response

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 4
  • Comments: 15 (1 by maintainers)

Most upvoted comments

+1 <Link to="some-path/"> from /base/ links to /base/some-path removing the trailing slash instead of /base/some-path/.