Skip to content

mocked next/link behavior seems inconsistenst with next/link from next.js when the as prop is used  #89

@sebaholesz

Description

@sebaholesz

In our codebase we use the logic of dynamic paths and query parameters to create a more complex abstraction on top of the basic next.js routing logic. In essence, we have a couple of specific pages between we navigate using a next/link like in the example below:

<NextLink
    as={isStatic ? as : href} // isStatic resolves to false, so as=href
    prefetch={false}
    href={
        isStatic
            ? href
            : {
                  pathname: FriendlyPagesDestinations[type],
                  query: { [SLUG_TYPE_QUERY_PARAMETER_NAME]: FriendlyPagesTypes[type], ...queryParams },
              }
    }
    {...props}
>
    {children}
</NextLink>

If I navigate using the following link:

<ExtendedNextLink type="category" href="/test-category">
    link text
</ExtendedNextLink>,

the actual implementation of next/link shows me the following properties:

{
    asPath: "/test-category".
    pathname: "/categories/[categorySlug]", // this is caused by the dynamic pathname shown above
    query: { 
        slugType: "front_product_list" // also caused by the dynamic query above) 
    },
}

but the mocked one gets overwritten because of the as prop and by this logic in the mock (specifically in MemoryRouter):

const newRoute = parseUrlToCompleteUrl(url, this.pathname);
let asPath;
let asRoute;
if (as === undefined || as === null) {
    asRoute = undefined;
    asPath = getRouteAsPath(newRoute.pathname, newRoute.query, newRoute.hash);
}
else {
    asRoute = parseUrlToCompleteUrl(as, this.pathname);
    asPath = getRouteAsPath(asRoute.pathname, asRoute.query, asRoute.hash);
}

My question is, am I misunderstanding something? According to my understanding, if I navigate using a next/link where I paste arbitrary URL and query, the as prop should not overwrite it, as it should only modify the asPath property of the router. Is this a bug, or a feature?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions