Replies: 4 comments 4 replies
-
Hello, it's me from the future. I'm still using the above, but upgrading to Next 11 (and 12) required me to change the import of import { resolveHref } from 'next/dist/shared/lib/router/router'; |
Beta Was this translation helpful? Give feedback.
-
Hello, it's me from slightly further in the future. In Next 12 the import Router from 'next/router';
import { resolveHref } from 'next/dist/shared/lib/router/router';
const exampleRoute = {
pathname: '/work/[slug]',
query: {
slug: 'project-foo',
},
};
const [, resolvedAs] = resolveHref(Router, exampleRoute, true);
// ^-- resulting path as a string |
Beta Was this translation helpful? Give feedback.
-
Thanks for noting these changes here 😄. This absolutely should be included in the official package. import { resolveHref } from 'next/dist/shared/lib/router/utils/resolve-href'
// ... |
Beta Was this translation helpful? Give feedback.
-
Next.js 14
|
Beta Was this translation helpful? Give feedback.
-
I'm still new to Next.js, so apologies in advance if I'm missing something obvious.
I use
next/link
with dynamic routing in my project – here's an example. I'm using literals here but in practice these are generated from CMS data, but the point is the same.This works fine, but I have just come across a use-case where I need to output what the above URL object actually resolves to, i.e.
/work/project-foo
, as I want to output it as (part of) the value for anog:url
meta tag.Upon learning of the existence of the node.js core
url
module and its in-browser counterpart, I tried usingurl.resolve
:However this produces
/work/[slug]?slug=project-foo
. Theurl
package doesn't know about Next.js' dynamic routing – fair enough.I then learned that Next.js implements its own version, so I tried that:
Unfortunately this produces the same result (
/work/[slug]?slug=project-foo
), not seeming to parse the dynamic parameter placeholder.Reading the source some more, I tried using
resolveHref
from next-server's router package, as I'd seen it used bynext/link
here:This gets the result I'm after:
/work/project-foo
. Great!However:
resolveHref
ideally wants that first argument to come from the router state (that's whatnext/link
does), so what I've done here might not be bulletproof, but I don't yet understand if/why that's the case (though maybe this is fine).Any thoughts or pointers would be much appreciated. Thanks in advance!
Beta Was this translation helpful? Give feedback.
All reactions