If we want to change/customize the URL shown in the browser when a user clicks on a Link component we can use the as
property:
<Link href="/cats" as="/someurl">
<a>Go to the cats gallery</a>
</Link>
So, even if the href of the Link component is set to /cats
when the user clicks on that link we will have the following URL in the browser:
http://localhost:3000/someurl
This allows us to have urls that don't have a corespoding file in the /pages
folder.
We can use the as
property even if we have a query params for our routes.
One usecase will be to get more cleaner urls:
<Link href={{
pathname: '/product/[id]',
query: { id: '1' }
}} as="/p/1">
<a>Link to product /1</a>
</Link>
Keep in mind that there are two sides to the story. The client-side navigation and the server-side one. This means that if we directly paste the http://localhost:3000/someurl
URL in the address bar of the browser and hit enter we will get a 404 error page. We will get the same error if someone shares the url via a link, of if its bookmaked. This happens because the /someurl
URL does not actually exist. If we want this to work we will need to customize the behavior of the express NodeJs server where the app runs.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.