Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative Routing in Next JS

I am using Next JS. Currently, my page is in the url

http://localhost:3000/project/613

Now, i want to push the page to

http://localhost:3000/project/613/time/123

Is there any way i can push relatively like router.push('/time/123')

Instead of entering the full URL router.push('project/613/time/123')

like image 908
Abinash Avatar asked Dec 09 '25 06:12

Abinash


2 Answers

While it's not exactly the same as relative routing you can prepend router.asPath to the relative part.

router.push(`${router.asPath}/time/123`)

Meaning you don't need to explicitly set the beginning of the path.

like image 110
juliomalves Avatar answered Dec 11 '25 19:12

juliomalves


To update, the easiest way to do it in 2024 seems to be <Link> and usePathName:


<Link href={`${pathname}/chapter/1`}>Chapter 1</Link>

E.g. this commit.

like image 20
Jasper Avatar answered Dec 11 '25 18:12

Jasper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!